Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-token-references.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@hebilicious/cssforge": patch
---

Preserve comments when substituting CSS variable aliases. Resolve explicit token references in Style Dictionary exports by their configuration path, including when themes share a CSS variable name.
129 changes: 129 additions & 0 deletions packages/cssforge/oracles/aliases.oracle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/**
* This oracle owns CSS alias substitution through `generateCSS` at the generated
* declaration. It covers `src/lib.ts#resolveValue` and its reference parser.
*
* ```ts
* generateCSS(config) // → var(--spacing-size-base, 0) for the mapped gap
* ```
*
* An alias name can also appear in a comment next to the reference. Only the
* name CSS reads as the argument should change.
*
* For every valid generated var() call with a mapped alias, the declaration
* substitutes its name and preserves the rest. The resolveValue JSDoc says
* “keeping any fallback and surrounding whitespace intact” and the comment
* test in tests/lib.test.ts says it “ignores comments and whitespace around
* the alias name.”
*
* The model renders the named argument separately from its surrounding text.
* The driver reads the generated custom-property value and the check compares
* the whole value. The grammar covers comments around a mapped name and
* unchanged external fallbacks. It leaves escaped identifiers, malformed CSS,
* and substitution outside this shape to separate properties.
*/

import { differs, oracleProperty, pass } from "@tanstack/oracles";
import fc from "fast-check";
import { generateCSS } from "../src/mod.ts";

const law = "substitutes only the mapped argument";
const checkpoint = "generated declaration";
const source = "spacing.custom.size.base";
const target = "--spacing-size-base";

const arbitrary = fc.record({
alias: fc.constantFrom("a", "gap", "button-space"),
before: fc.constantFrom("", "plain", "alias", "(", ")", '"'),
after: fc.constantFrom("", " ", "/**/", " /**/"),
fallback: fc.constantFrom("", ", 0", ", var(--external, 0)"),
});

type History = ReturnType<typeof arbitrary.generate>["value"];

function declarationValue(history: History, name: string) {
const comment = history.before === "alias" ? `--${history.alias}` : history.before;
const before = comment ? `/*${comment}*/ ` : "";
return `var(${before}${name}${history.after}${history.fallback})`;
}

oracleProperty({
id: "css-alias-substitution",
owns: ["src/lib.ts#resolveValue"],
law: {
statement:
"For every valid generated var() call with a mapped alias, the declaration substitutes its name and preserves the rest.",
authority: "src/lib.ts resolveValue JSDoc and tests/lib.test.ts comment cases",
limits: "Generated comments and external fallbacks around one mapped argument.",
},
histories: {
arbitrary,
runs: 100,
fixedSeeds: [47],
states: ["comment names alias", "comment contains delimiter", "comment touches name"],
constructed: [
{
name: "alias in comment",
enters: ["comment names alias"],
build: (base): History => ({ ...base, before: "alias" }),
},
{
name: "parenthesis in comment",
enters: ["comment contains delimiter"],
build: (base): History => ({ ...base, before: ")" }),
},
{
name: "comment immediately after name",
enters: ["comment touches name"],
build: (base): History => ({ ...base, after: "/**/" }),
},
],
fixed: [
{
name: "plain substitution with fallback",
history: { alias: "gap", before: "", after: "", fallback: ", 0" },
},
],
},
reached(history) {
const states = [];
if (history.before === "alias") states.push("comment names alias");
if (["(", ")", '"'].includes(history.before))
states.push("comment contains delimiter");
if (history.after === "/**/") states.push("comment touches name");
return states;
},
model: (history) => declarationValue(history, target),
driver(history, observe) {
try {
const css = generateCSS({
spacing: { custom: { size: { value: { base: "1rem" } } } },
primitives: {
button: {
value: {
base: {
value: { gap: declarationValue(history, `--${history.alias}`) },
variables: { [history.alias]: source },
settings: { pxToRem: false },
},
},
},
},
});
observe(checkpoint, css.match(/^--button-base-gap: (.*);$/mu)?.[1]);
} catch (error) {
observe(checkpoint, error);
}
},
check: (_history, trace, expected) =>
differs(checkpoint, law, trace[0]?.value, expected) ?? pass,
calibrations: [
{
name: "leaves a mapped name unchanged",
law,
history: { fixed: "plain substitution with fallback" },
corrupt: (_trace, history) => [
{ checkpoint, value: declarationValue(history, `--${history.alias}`) },
],
},
],
});
146 changes: 146 additions & 0 deletions packages/cssforge/oracles/collisions.oracle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/**
* This oracle owns repeated generated CSS names across theme scopes. Both
* public generators accept scoped reuse and reject same-scope duplicates.
* It covers src/generator.ts#assertNoKeyCollisions and src/modules/colors.ts#describeScope.
*
* ```ts
* generateCSS(config) // → two --accent declarations for distinct theme scopes
* generateStyleDictionaryJSON(config) // → collision error when both land at :root
* ```
*
* An explicit `:root` and an implicit root are the same scope, including
* under a common media rule. For every generated pair of themes sharing a
* custom-property name, both generators reject equal scopes and keep both
* declarations for distinct scopes. The collision contract in src/generator.ts
* states “Tokens that share a name but target different scopes are not a collision.”
*
* Each history specifies the effective CSS scope and how to spell it in the
* config. The model compares the scopes. The driver observes declarations or
* the collision diagnostic. Arbitrary selector equivalence is outside this grammar.
*/

import { differs, oracleProperty, pass } from "@tanstack/oracles";
import fc from "fast-check";
import { generateCSS, generateStyleDictionaryJSON } from "../src/mod.ts";

const law = "rejects duplicate names exactly when scopes match";
const checkpoint = "generator results";
const scope = fc.record({
selector: fc.constantFrom(":root", ".one", ".two"),
condition: fc.constantFrom("", "@media (width > 600px)", "@media (width < 400px)"),
explicitRoot: fc.boolean(),
});
const arbitrary = fc.tuple(scope, scope);
type History = ReturnType<typeof arbitrary.generate>["value"];
type Scope = History[number];

const sameScope = ([left, right]: History) =>
left.selector === right.selector && left.condition === right.condition;

function theme(scope: Scope) {
const selector =
scope.selector === ":root" && !scope.explicitRoot ? undefined : scope.selector;
return {
value: { ink: { value: { accent: "red" }, settings: { variantNameOnly: true } } },
settings: { selector, atRule: scope.condition || undefined },
};
}

const collisionMessage =
'Token key collision: "theme.left.ink.accent" and "theme.right.ink.accent" both generate "--accent". Rename one of the configuration paths.';

oracleProperty({
id: "theme-name-collisions",
owns: ["src/generator.ts#assertNoKeyCollisions", "src/modules/colors.ts#describeScope"],
law: {
statement:
"For every generated pair of themes sharing a custom-property name, both generators reject equal scopes and keep both declarations for distinct scopes.",
authority:
"src/generator.ts assertNoKeyCollisions contract and tests/key-collision.test.ts",
limits: "Two variantNameOnly themes in root, class, and media-rule scopes.",
},
histories: {
arbitrary,
runs: 100,
fixedSeeds: [47],
states: ["same scope", "distinct scopes", "explicit and implicit root"],
constructed: [
{
name: "root spelled two ways",
enters: ["same scope", "explicit and implicit root"],
build: ([left]): History => [
{ ...left, selector: ":root", explicitRoot: true },
{ ...left, selector: ":root", explicitRoot: false },
],
},
{
name: "two selectors in one condition",
enters: ["distinct scopes"],
build: ([left]): History => [
{ ...left, selector: ".one" },
{ ...left, selector: ".two" },
],
},
],
},
reached(history) {
const [left, right] = history;
const states = [sameScope(history) ? "same scope" : "distinct scopes"];
if (
left.selector === ":root" &&
right.selector === ":root" &&
left.explicitRoot !== right.explicitRoot
) {
states.push("explicit and implicit root");
}
return states;
},
model: (history) =>
sameScope(history)
? [collisionMessage, collisionMessage]
: [2, ["--accent", "--accent"]],
driver([left, right], observe) {
const config = {
colors: {
palette: { value: {} },
theme: { left: theme(left), right: theme(right) },
},
};

const outputs = [
() => generateCSS(config).match(/--accent:/gu)?.length,
() => {
const result: {
theme: Record<
string,
{ ink: { accent: { attributes: { cssVariable: string } } } }
>;
} = JSON.parse(generateStyleDictionaryJSON(config));
return ["left", "right"].map(
(name) => result.theme[name]?.ink.accent.attributes.cssVariable,
);
},
];

observe(
checkpoint,
outputs.map((output) => {
try {
return output();
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
}),
);
},
check: (_history, trace, expected) =>
differs(checkpoint, law, trace[0]?.value, expected) ?? pass,
calibrations: [
{
name: "accepts two declarations in the same scope",
law,
history: { constructed: "root spelled two ways" },
corrupt: () => [{ checkpoint, value: [2, ["--accent", "--accent"]] }],
},
],
});
109 changes: 109 additions & 0 deletions packages/cssforge/oracles/reference-chains.oracle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* This oracle owns Style Dictionary's resolved values for chains of CSS
* custom-property references. It checks the values returned by
* `generateStyleDictionaryJSON` and covers src/generator.ts#resolveTokenValue.
*
* ```ts
* generateStyleDictionaryJSON(config) // → 1rem for a chain ending in 1rem
* generateStyleDictionaryJSON(config) // → var(...) for a cycle or an external name
* ```
*
* For every generated chain, all tokens resolve to the terminal literal or
* external reference. For every generated cycle, all tokens remain references
* to a member of that cycle. The README says resolved mode “recursively
* resolves references to other CSS Forge tokens” and that “Cycles and unknown
* CSS variables remain as var(...) instead of causing generation to fail.”
*
* A history specifies the chain length and the end directly. The model
* reads that end without following edges. The driver reads every token value.
* This grammar covers chains and simple cycles with one outgoing reference
* per token. It leaves compound values and CSS scope selection to other checks.
*/

import { differs, oracleProperty, pass } from "@tanstack/oracles";
import { generateStyleDictionaryJSON } from "../src/mod.ts";

const law = "resolves chains while preserving external references and cycles";
const checkpoint = "resolved chain";
const ends = ["literal", "external", "cycle"] as const;
const lengths = Array.from({ length: 8 }, (_, index) => index + 1);
const tokenName = (index: number) => `step-${index}`;
const reference = (index: number) => `var(--${tokenName(index)})`;
const terminalValue = {
literal: "1rem",
external: "var(--external)",
cycle: reference(0),
};

oracleProperty({
id: "style-dictionary-reference-chains",
owns: ["src/generator.ts#resolveTokenValue"],
law: {
statement:
"For every generated chain, all tokens resolve to the terminal literal or external reference. For every generated cycle, all tokens remain references to a member of that cycle.",
authority: "README.md, Style Dictionary JSON, Choose the value mode",
limits:
"Chains and simple cycles of one to eight nodes with a single outgoing reference.",
},
histories: {
enumerated: ends.flatMap((end) => lengths.map((length) => ({ length, end }))),
states: ends,
},
label: ({ length, end }) => `${end} with ${length} tokens`,
reached: ({ end }) => [end],
model({ length, end }) {
return end === "cycle"
? lengths.slice(0, length).map((index) => reference(index - 1))
: [terminalValue[end]];
},
driver({ length, end }, observe) {
const names = lengths.slice(0, length).map((index) => tokenName(index - 1));
const value = Object.fromEntries(
names.map((name, index) => [
name,
index + 1 === length ? terminalValue[end] : reference(index + 1),
]),
);

try {
const output: { theme: { base: { tokens: Record<string, { value: string }> } } } =
JSON.parse(
generateStyleDictionaryJSON({
colors: {
palette: { value: {} },
theme: {
base: {
value: { tokens: { value, settings: { variantNameOnly: true } } },
},
},
},
}),
);
observe(
checkpoint,
names.map((name) => output.theme.base.tokens[name]?.value),
);
} catch (error) {
observe(checkpoint, error);
}
},
check({ length }, trace, allowed) {
const observed = trace[0]?.value;
if (
Array.isArray(observed) &&
observed.length === length &&
observed.every((value) => allowed.includes(value))
) {
return pass;
}
return differs(checkpoint, law, observed, { length, allowed }) ?? pass;
},
calibrations: [
{
name: "leaves a reference to a known literal unresolved",
law,
history: { enumerated: "literal with 2 tokens" },
corrupt: () => [{ checkpoint, value: [reference(1), "1rem"] }],
},
],
});
Loading
Loading