Skip to content

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

TypeScript

feat(theme): add theme-local token support (#5844)

rubyycheung7418f0e721e2
diff --git a/.changeset/theme-local-tokens.md b/.changeset/theme-local-tokens.md
new file mode 100644
index 0000000000..828186a9d1
--- /dev/null
+++ b/.changeset/theme-local-tokens.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/cli': patch
+'@astryxdesign/core': patch
+---
+
+[new] Add the opt-in theme-local token contract for maintained theme families.
+
+@rubyycheung
diff --git a/docs/architecture/theme-authoring-contract.md b/docs/architecture/theme-authoring-contract.md
index 9b752c1c30..139f9ce663 100644
--- a/docs/architecture/theme-authoring-contract.md
+++ b/docs/architecture/theme-authoring-contract.md
@@ -18,6 +18,7 @@ applies_to:
packages/core/src/theme/expandMotionScale.ts,
packages/core/src/theme/mergeComponents.ts,
packages/core/src/theme/onMediaTokens.ts,
+ packages/core/src/theme/localTokens.ts,
packages/cli/assets/theme.template.ts,
]
verified_by:
@@ -30,7 +31,14 @@ verified_by:
packages/core/src/theme/onMediaTokens.test.ts,
scripts/check-theme-template.test.mjs,
]
-deciding_specs: []
+deciding_specs:
+ [
+ spec:AST-006/DEC-1,
+ spec:AST-006/DEC-2,
+ spec:AST-006/DEC-3,
+ spec:AST-006/DEC-4,
+ spec:AST-006/DEC-6,
+ ]
---
# Theme authoring contract
@@ -51,6 +59,7 @@ source configuration independently.
- a name and optional normalized base theme;
- higher-order color, typography, radius, and motion configuration;
- explicit semantic token overrides;
+- optional theme-family-local token declarations;
- component target/style-key overrides;
- icon and indicator registries;
- syntax tokens; and
@@ -67,7 +76,9 @@ Normalization follows one precedence order:
3. explicit token overrides;
4. generated component typography followed by explicit component overrides;
5. inherited and explicit media-surface overrides;
-6. inherited and explicit icon/indicator registry entries.
+6. inherited and explicit theme-local declarations, validated against the
+ resolved token, component, and media surfaces; and
+7. inherited and explicit icon/indicator registry entries.
Explicit values win within their surface. Component maps merge by component,
style key, and CSS property rather than replacing the entire inherited target.
@@ -90,31 +101,40 @@ style key, and CSS property rather than replacing the entire inherited target.
inherited properties on the same component/style key.
- **INV7 — Surface overrides inherit coherently.** `onDark` and `onLight` combine
system defaults, inherited surface values, and local overrides in that order.
-- **INV8 — Authoring and output are separate systems.** This record owns the
+- **INV8 — Local-token enrollment is explicit and closed.** Supplying
+ `localTokens`, or extending an exact enrolled base, produces a flattened local
+ declaration map plus ownership and lineage metadata. Enrolled themes validate
+ exact namespaces, case-insensitive `var()` references, cycles, and collisions
+ with `tokens`; unenrolled themes retain their legacy behavior.
+- **INV9 — Authoring and output are separate systems.** This record owns the
normalized theme definition. The shared compiler owns turning it into styles;
runtime and build own using or saving that output.
This record does not own:
- semantic token names/defaults;
-- turning `DefinedTheme` into style rules, including private-variable expansion
- and cascade/layer behavior;
+- turning `DefinedTheme` into style rules, including local-token emission,
+ private-variable expansion, and cascade/layer behavior;
- runtime mounting, scope lifetime, root synchronization, or DOM observation;
- CLI file generation and packaging; or
- which component targets, states, and public properties participate.
-One future `architecture:theme-compilation` record owns platform output. For web,
-runtime and static build use one CSS compiler and the same maintained stylesheet
-rules. A future native compiler may turn the same theme definition into native
-style objects without making CSS concepts part of shared authoring. Runtime
-application and CLI packaging use the compiled output without changing it. The
-participating public surface belongs to
+`architecture:theme-compilation` owns platform output. For web, runtime and
+static build use one CSS compiler and the same maintained stylesheet rules. A
+future native compiler may turn the same theme definition into native style
+objects without making CSS concepts part of shared authoring. Runtime application
+and CLI packaging use the compiled output without changing it. The participating
+public surface belongs to
`architecture:component-theming-surface`.
## Change coupling
- Adding an authoring field defines its normalization, precedence, inheritance,
validation, template exposure, and negative tests together.
+- A local-token change preserves explicit enrollment, exact owner namespaces,
+ source/built lineage parity, and the separation from portable `tokens`. One
+ name cannot appear in both maps because CSS output and portable token helpers
+ would otherwise resolve different values.
- Changing precedence is a compatibility decision because existing themes may
contain both generated and explicit values.
- Changing `ComponentStyleMap` merge behavior verifies base, generated, explicit,
@@ -132,13 +152,17 @@ participating public surface belongs to
`expandMotionScale.ts` own their derived token/component values.
- `mergeComponents.ts` owns the shared deep-merge rule.
- `onMediaTokens.ts` owns normalization of inverted-surface overrides.
+- `localTokens.ts` owns opt-in enrollment, exact namespaces, reference closure,
+ cycle detection, cross-map collision rejection, and flattened lineage.
- `packages/cli/assets/theme.template.ts` is an author-facing projection and must
remain aligned; it does not define additional semantics.
## Deciding specs
-None. This record captures the approved shipped authoring and normalization
-architecture.
+AST-006 decisions 1–4 and 6 establish the shipped theme-local authoring shape,
+exact naming and inheritance rules, enrolled-only validation, and shared value
+contract. The remaining authoring and normalization architecture predates that
+spec and remains unchanged.
## Verification
@@ -148,4 +172,5 @@ architecture.
| INV3, INV4 | extension and invalid-base tests | Child themes require a base stylesheet or silently accept a non-theme base |
| INV6 | component merge tests across base/generated/explicit rules | Restating one property drops inherited component styles |
| INV7 | `onMediaTokens.test.ts` and generated surface-rule tests | A child loses inherited surface customization or surface precedence changes |
+| INV8 | `defineTheme.test.ts` and CLI source/built inheritance tests | Enrollment, validation, or lineage differs across runtime and static authoring paths |
| Authoring projection | `scripts/check-theme-template.test.mjs` | A supported authoring concept is missing or misstated in the template |
diff --git a/docs/architecture/theme-compilation.md b/docs/architecture/theme-compilation.md
index 3d85690588..d3a2bdfd44 100644
--- a/docs/architecture/theme-compilation.md
+++ b/docs/architecture/theme-compilation.md
@@ -24,7 +24,7 @@ verified_by:
packages/cli/api/theme/build/build.test.mjs,
packages/cli/api/theme/build/build.public-component-vars.test.mjs,
]
-deciding_specs: []
+deciding_specs: [spec:AST-006/DEC-2, spec:AST-006/DEC-4]
---
# Theme compilation
@@ -46,13 +46,15 @@ The compiler receives a `DefinedTheme` from the theme-authoring system.
The current web compiler works like this:
-1. `generateThemeRules` turns tokens and component overrides into CSS rules.
+1. `generateThemeRules` turns portable tokens, theme-local tokens, and component
+ overrides into CSS rules.
2. The same code adds state rules, media-surface rules, scopes, and layers.
3. The `Theme` provider mounts those rules when a theme was not built ahead of
time.
4. The CLI saves those rules into CSS and packages the related JavaScript and
types.
-5. A built theme is marked so the provider does not compile or inject it again.
+5. A built theme preserves local-token ownership and lineage metadata and is
+ marked so the provider does not compile or inject it again.
For top-level declarations in base component target rules, the compiler preserves
generic CSS properties as written. When a guaranteed property needs to reach
@@ -100,11 +102,16 @@ Platform-specific details stay inside that compiler.
- **INV10 — Shared intent keeps the same meaning.** A token or supported component
override means the same thing across outputs. Platform-only features have an
explicit support boundary.
+- **INV11 — Theme-local names remain exact.** For an enrolled theme, the compiler
+ emits the normalized `localTokens` map beside portable declarations without
+ rewriting names or values. Runtime and static output use the same rules, and
+ invalid enrolled input is rejected before either path writes partial CSS.
This record does not own:
-- token names and defaults;
-- `DefineThemeInput`, inheritance, or authoring precedence;
+- token names and defaults, including the meanings of theme-local names;
+- `DefineThemeInput`, local-token enrollment and lineage, inheritance, or
+ authoring precedence;
- which component parts and properties are public theme APIs; or
- provider nesting, root synchronization, and DOM observation after compilation.
@@ -126,6 +133,8 @@ This record does not own:
tested as a compatibility guarantee unless the component-theming record admits
that property into the guaranteed set.
- Changing scope or layer output tests both source and distribution builds.
+- Changing local-token emission or packaging verifies exact-name runtime/static
+ parity, atomic failure, and preservation of built-theme lineage metadata.
- Adding a platform compiler names the shared concepts it supports and tests
that they keep the same meaning. Unsupported concepts fail clearly instead of
disappearing.
@@ -133,7 +142,8 @@ This record does not own:
## Owning code
-- `generateThemeRules.ts` owns the web compiler and canonical CSS output.
+- `generateThemeRules.ts` owns the web compiler and canonical CSS output,
+ including portable and theme-local declarations in the same scoped block.
- `Theme.tsx` mounts compiled CSS for themes that were not built ahead of time.
- `derivedVarRegistry.ts` owns checked mappings from guaranteed public properties
to private component variables.
@@ -147,8 +157,10 @@ This record does not own:
## Deciding specs
-None. The system owner selected one definition with platform-specific outputs and
-the guaranteed, best-effort, public-semantic, and private implementation tiers.
+AST-006 decisions 2 and 4 establish exact local-token output and atomic shared
+validation for enrolled themes. The system owner separately selected one
+definition with platform-specific outputs and the guaranteed, best-effort,
+public-semantic, and private implementation tiers.
## Verification
@@ -160,6 +172,7 @@ the guaranteed, best-effort, public-semantic, and private implementation tiers.
| INV6, INV7 | Existing registry and CLI public-variable tests (partial) | Private variables become authorable, or a reviewed public semantic variable fails build/runtime |
| INV8 | Component target metadata and compatibility review | Successful generic emission is treated as a guaranteed public behavior |
| INV9, INV10 | Platform compiler tests when another compiler ships | CSS details enter shared authoring, or shared theme intent silently disappears |
+| INV11 | `defineTheme.test.ts` and `build.test.mjs` local-token fixtures | Runtime/static output rewrites a local name, disagrees, or leaves partial output after failure |
| Built themes | Theme and CLI build tests | Runtime recompiles a built theme, or built output omits canonical rules |
## Known conformance and verification gaps
diff --git a/docs/architecture/theme-tokens.md b/docs/architecture/theme-tokens.md
index 5c46a978f2..dc792db32a 100644
--- a/docs/architecture/theme-tokens.md
+++ b/docs/architecture/theme-tokens.md
@@ -13,6 +13,7 @@ applies_to:
[
packages/core/src/theme/tokens.stylex.ts,
packages/core/src/theme/tokens.ts,
+ packages/core/src/theme/localTokens.ts,
packages/core/src/theme/domainTokens/,
packages/core/src/theme/syntax/,
packages/cli/assets/theme.template.ts,
@@ -20,10 +21,11 @@ applies_to:
verified_by:
[
packages/core/src/theme/tokens.test.ts,
+ packages/core/src/theme/defineTheme.test.ts,
scripts/check-theme-template.test.mjs,
scripts/generate-token-docs.mjs,
]
-deciding_specs: []
+deciding_specs: [spec:AST-006/DEC-1, spec:AST-006/DEC-5]
---
# Theme token architecture
@@ -57,6 +59,13 @@ available to theme validation and resolution.
The CLI theme template and generated token documentation are projections of
this vocabulary. They do not define additional tokens.
+Theme-family-local tokens are a separate enrolled map. They may reuse the
+existing token value shape, but they do not enter `TokenName`, defaults,
+`tokenVar`, `tokenVars`, `resolveThemeToken`, `resolveThemeTokens`, generated
+portable documentation, or Core component source. A name cannot be present in
+both portable `tokens` and `localTokens` because CSS and non-CSS resolution would
+then have contradictory winners.
+
## Boundaries and invariants
- **INV1 — `defineVars` declarations are canonical.** A core token name and its
@@ -77,10 +86,14 @@ this vocabulary. They do not define additional tokens.
second set of resolved values.
- **INV7 — Projections cannot drift silently.** Theme-template inventory and
generated token docs change with the canonical family or fail validation.
+- **INV8 — Theme-local names stay non-portable.** Enrolled local declarations
+ remain outside the canonical vocabulary, typed helpers, generated portable
+ documentation, and Core component dependencies.
This record does not own:
- the `defineTheme` input shape, generated scales, or precedence;
+- local-token names, meanings, enrollment, ownership, lineage, and emission;
- mounting, nesting, color-mode selection, or runtime theme observation;
- turning a normalized theme into scoped CSS and build files;
- component-specific targets, visual states, or private derived variables.
@@ -102,6 +115,9 @@ does not silently change authoring, runtime, compiler, or component contracts.
- Changes to JavaScript resolution preserve CSS cascade semantics for supported
references and color expressions; unsupported expressions remain intact
rather than being guessed.
+- Adding a theme-local name does not update portable defaults, name types,
+ helpers, or generated token docs. Authoring validation rejects a duplicate
+ across `tokens` and `localTokens` before the compiler or helpers can disagree.
## Owning code
@@ -112,12 +128,17 @@ does not silently change authoring, runtime, compiler, or component contracts.
- `packages/core/src/theme/defineTheme.ts` aggregates token types/defaults for
validation and authoring; it does not become a second token source.
- `packages/core/src/theme/tokens.ts` owns server-safe references and resolution.
+- `packages/core/src/theme/localTokens.ts` enforces the boundary between the
+ portable and enrolled local maps; it does not add local names to this
+ vocabulary.
- `packages/cli/assets/theme.template.ts` and generated token docs are checked
projections for theme authors and consumers.
## Deciding specs
-None. This record captures the approved shipped token architecture.
+AST-006 decisions 1 and 5 establish that theme-local names are additive,
+theme-family contracts rather than portable Astryx tokens. The existing portable
+vocabulary and helper architecture remain unchanged.
## Verification
@@ -126,5 +147,6 @@ None. This record captures the approved shipped token architecture.
| INV1, INV2, INV7 | `scripts/check-theme-template.test.mjs` and token-doc generation check | A token family exists without a matching author-facing inventory or generated documentation |
| INV5 | Domain-token exports and theme-generation tests | Domain names disappear from validation or require importing unused domain implementation |
| INV6 | `packages/core/src/theme/tokens.test.ts` | JavaScript resolution disagrees with defaults, mode selection, references, or supported color expressions |
+| INV8 | `defineTheme.test.ts`, template checks, and token-doc generation | A local name enters portable helpers/docs or can conflict with a portable declaration |
| Released token compatibility | Type checking plus representative package/source builds | A released CSS variable or typed token name disappears without an explicit migration decision |
| Visual defaults | Real Chromium examples in light, dark, status, and high-contrast contexts | A changed default produces unreadable or semantically inconsistent output |
diff --git a/docs/specs/AST-006/spec.md b/docs/specs/AST-006/spec.md
index ff9432a408..b322208b8e 100644
--- a/docs/specs/AST-006/spec.md
+++ b/docs/specs/AST-006/spec.md
@@ -8,7 +8,7 @@ archive_reason: null
superseded_by: null
approved_by: cixzhang
approved_at: 2026-08-31
-phase: accepted
+phase: shipped
owners: [cixzhang, rubyycheung, imdreamrunner]
affects_architecture:
[
@@ -31,7 +31,7 @@ Theme authors get one explicit, checked path for theme-family-local reuse;
component and application authors keep the same portable token contract they have
today.
-The accepted API is one optional `DefineThemeInput.localTokens` field. Supplying
+The shipped API is one optional `DefineThemeInput.localTokens` field. Supplying
it explicitly enrolls a theme in the new contract; omitting it preserves existing
behavior, even when legacy component overrides already mention
`--astryx-theme-*`. A local token is declared with its complete CSS
@@ -42,10 +42,10 @@ contract, but a shipped enrolled definition recorded by its owning theme spec
does: its exact name and semantic meaning are public within that theme family,
not portable across themes or intended for Core component source.
-This current record accepts the cross-theme API and invariants independently of
-whether any particular theme has completed its own adoption evidence. Theme-local
-names, meanings, values, mappings, and rendered evidence remain owned by each
-adopting theme's colocated record.
+This current record governs the shipped cross-theme API and invariants
+independently of whether any particular theme has completed its own adoption
+evidence. Theme-local names, meanings, values, mappings, and rendered evidence
+remain owned by each adopting theme's colocated record.
## Non-goals
@@ -62,12 +62,10 @@ adopting theme's colocated record.
authorization for application code to depend on it.
- Defining any adopting theme's role meaning, value, component mappings, or
evidence. Those belong to that theme's colocated record.
-- Implementing runtime, build, package, theme, or component changes in this
- specification-only pull request.
## Requirements
-The requirements below are the accepted cross-theme contract.
+The requirements below are the shipped cross-theme contract.
- **FR1 — Local tokens are purely additive, optional, and explicitly enrolled.**
`DefineThemeInput` MUST gain at most one new authoring surface: optional
@@ -154,7 +152,7 @@ The requirements below are the accepted cross-theme contract.
genuinely match the documented meaning and MUST provide rendered evidence for
its actual light/dark and relevant interaction states.
-### Accepted authoring shape
+### Shipped authoring shape
`defineTheme` remains the only authoring operation. Opt-in requires the existing
`name` to already be the exact lower-kebab identifier used in every local token.
@@ -197,14 +195,12 @@ component mapping.
## Current-state impact
-Current `main` has a closed portable core/domain token vocabulary and no
-first-class local-token field. Unknown keys that reach permissive existing paths
-can serialize, and broad object spreads can therefore resemble intentional local
-authoring without ownership, reference closure, or lineage validation.
+Current `main` keeps its closed portable core/domain token vocabulary and now
+ships a separate first-class local-token field. Unknown keys that reach
+permissive legacy paths can still serialize, but only explicit `localTokens`
+enrollment creates ownership, reference closure, and lineage validation.
-If implemented:
-
-- `architecture:theme-authoring-contract` adds only the optional `localTokens`
+- `architecture:theme-authoring-contract` owns the optional `localTokens`
input, its exact-name map, explicit enrollment state, flattened inheritance,
and lineage metadata;
- `architecture:theme-compilation` emits that exact map through the shared
@@ -214,11 +210,10 @@ If implemented:
vocabulary and explicitly excludes theme-local names from its public helpers
and documentation.
-The current architecture records remain authoritative for shipped behavior until
-AST-006 is implemented. This accepted spec decides future implementation; their
-`deciding_specs` relationships update with the implementation that changes those
-surfaces. A draft theme record may reference this current spec while keeping its
-own value, mapping, and evidence decisions unresolved.
+Those current architecture records are authoritative for the shipped behavior
+and cite the applicable AST-006 decisions. A draft theme record may reference
+this current spec while keeping its own value, mapping, and evidence decisions
+unresolved.
### Compatibility and adoption
@@ -244,8 +239,8 @@ own value, mapping, and evidence decisions unresolved.
- Descendant compatibility follows explicit enrollment and exact lineage. A
released enrolled theme or token rename, or semantic meaning change, requires
an explicit migration or alias before descendants move.
-- This specification-only change has no Changeset. A later implementation or
- theme output change carries its own release note.
+- The infrastructure implementation carries its own Changeset. A later adopting
+ theme output change carries a separate release note.
## Verification
@@ -262,7 +257,7 @@ own value, mapping, and evidence decisions unresolved.
### Completion criteria
-AST-006 moves from `accepted` to `shipped` only when:
+AST-006 is `shipped` because the implementation satisfies these criteria:
- optional `DefineThemeInput.localTokens` is the only new local-token authoring
surface and its presence is the root enrollment trigger;
@@ -295,7 +290,7 @@ AST-006 moves from `accepted` to `shipped` only when:
## Decision log
-The decisions below were approved by `cixzhang` as part of this current accepted
+The decisions below were approved by `cixzhang` as part of this current shipped
specification.
### DEC-1 — Add one optional local-token field without changing tokens
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 4ee127bdcd..c6d7786ad5 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -829,6 +829,21 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
};
const inheritableFields =
+ (themeDef.__localTokenLineage !== undefined
+ ? ` localTokens: ${JSON.stringify(themeDef.localTokens ?? {}, null, 2)
+ .split('\n')
+ .map((line, i) => (i === 0 ? line : ' ' + line))
+ .join('\n')},\n` +
+ ` __localTokenOwners: ${JSON.stringify(
+ themeDef.__localTokenOwners ?? {},
+ null,
+ 2,
+ )
+ .split('\n')
+ .map((line, i) => (i === 0 ? line : ' ' + line))
+ .join('\n')},\n` +
+ ` __localTokenLineage: ${JSON.stringify(themeDef.__localTokenLineage)},\n`
+ : '') +
serializeField('components', themeDef.components) +
serializeField('__onDark', themeDef.__onDark) +
serializeField('__onLight', themeDef.__onLight);
@@ -1142,9 +1157,9 @@ export async function themeBuild(
'onDark',
'onLight',
];
- const needsResolution = INPUT_ONLY_FIELDS.some(
- field => themeDef[field] !== undefined,
- );
+ const needsResolution =
+ INPUT_ONLY_FIELDS.some(field => themeDef[field] !== undefined) ||
+ ('localTokens' in themeDef && themeDef.__localTokenLineage === undefined);
if (needsResolution) {
resolvedTheme = _defineTheme({...themeDef});
} else {
@@ -1174,6 +1189,7 @@ export async function themeBuild(
// a substring check on it would fire for every theme.
const themeOwnValues = JSON.stringify([
resolvedTheme.tokens ?? {},
+ resolvedTheme.localTokens ?? {},
resolvedTheme.components ?? {},
]);
const colorSchemeDecl = themeOwnValues.includes('light-dark(')
@@ -1240,9 +1256,9 @@ export async function themeBuild(
}
const displayTheme = resolvedTheme || themeDef;
- const tokenCount = displayTheme.tokens
- ? Object.keys(displayTheme.tokens).length
- : 0;
+ const tokenCount =
+ Object.keys(displayTheme.tokens ?? {}).length +
+ Object.keys(displayTheme.localTokens ?? {}).length;
const componentCount = displayTheme.components
? Object.keys(displayTheme.components).length
: 0;
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
index 3cb722c2f4..ff726d38af 100644
--- a/packages/cli/api/theme/build/build.test.mjs
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -84,6 +84,131 @@ describe('themeBuild() — receipt', () => {
}
});
+ it('emits local tokens and preserves enrollment metadata in the built module', async () => {
+ const themeFile = path.join(tmpDir, 'local-theme.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'local-theme',
+ localTokens: {
+ '--astryx-theme-local-theme-color-status-fill-accent': ['#0077b6', '#48cae4'],
+ },
+ components: {
+ badge: {
+ 'variant:info': {
+ backgroundColor: 'var(--astryx-theme-local-theme-color-status-fill-accent)',
+ },
+ },
+ },
+ };\n`,
+ );
+
+ const result = await themeBuild('local-theme.mjs', {}, {cwd: tmpDir});
+ const css = fs.readFileSync(path.join(tmpDir, 'local-theme.css'), 'utf8');
+ const built = fs.readFileSync(path.join(tmpDir, 'local-theme.js'), 'utf8');
+
+ expect(result?.data.tokenCount).toBe(1);
+ expect(css).toContain(
+ '--astryx-theme-local-theme-color-status-fill-accent: light-dark(#0077b6, #48cae4);',
+ );
+ expect(built).toContain('localTokens: {');
+ expect(built).toContain('__localTokenOwners: {');
+ expect(built).toContain('__localTokenLineage: ["local-theme"]');
+ });
+
+ it.each(['VAR', 'vAr'])(
+ 'rejects undeclared local-token references using %s() before writing outputs',
+ async functionName => {
+ const themeFile = path.join(tmpDir, 'invalid-local-theme.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'invalid-local-theme',
+ localTokens: {},
+ components: {
+ badge: {
+ base: {
+ color: '${functionName}(--astryx-theme-invalid-local-theme-color-missing)',
+ },
+ },
+ },
+ };\n`,
+ );
+
+ await expect(
+ themeBuild('invalid-local-theme.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toThrow(/has no declaration/);
+ expect(fs.existsSync(path.join(tmpDir, 'invalid-local-theme.css'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'invalid-local-theme.js'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'invalid-local-theme.d.ts'))).toBe(
+ false,
+ );
+ },
+ );
+
+ it.each(['VAR', 'vAr'])(
+ 'rejects local-token cycles using %s() before writing outputs',
+ async functionName => {
+ const themeFile = path.join(tmpDir, 'cyclic-local-theme.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'cyclic-local-theme',
+ localTokens: {
+ '--astryx-theme-cyclic-local-theme-color-a': '${functionName}(--astryx-theme-cyclic-local-theme-color-b)',
+ '--astryx-theme-cyclic-local-theme-color-b': '${functionName}(--astryx-theme-cyclic-local-theme-color-a)',
+ },
+ };\n`,
+ );
+
+ await expect(
+ themeBuild('cyclic-local-theme.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toThrow(/cycle detected/);
+ expect(fs.existsSync(path.join(tmpDir, 'cyclic-local-theme.css'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'cyclic-local-theme.js'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'cyclic-local-theme.d.ts'))).toBe(
+ false,
+ );
+ },
+ );
+
+ it('rejects cross-map duplicate token names before writing outputs', async () => {
+ const themeFile = path.join(tmpDir, 'duplicate-local-theme.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'duplicate-local-theme',
+ tokens: {
+ '--astryx-theme-duplicate-local-theme-color-accent': '#0077b6',
+ },
+ localTokens: {
+ '--astryx-theme-duplicate-local-theme-color-accent': '#48cae4',
+ },
+ };\n`,
+ );
+
+ await expect(
+ themeBuild('duplicate-local-theme.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toThrow(/both tokens and localTokens/);
+ expect(fs.existsSync(path.join(tmpDir, 'duplicate-local-theme.css'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'duplicate-local-theme.js'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'duplicate-local-theme.d.ts'))).toBe(
+ false,
+ );
+ });
+
it('is silent by default (noopLogger) — no console output for a scripted caller', async () => {
const themeFile = path.join(tmpDir, 'quiet.mjs');
fs.writeFileSync(
@@ -456,6 +581,55 @@ describe('themeBuild() — extends', () => {
expect(css).toContain('--radius-element: 6px;');
});
+ it('preserves local-token enrollment when extending a built theme module', async () => {
+ fs.writeFileSync(
+ path.join(extDir, 'local-base.mjs'),
+ `import {defineTheme} from '@astryxdesign/core/theme';
+ export const localBaseTheme = defineTheme({
+ name: 'local-base',
+ localTokens: {
+ '--astryx-theme-local-base-color-status-fill': ['#123456', '#abcdef'],
+ },
+ components: {
+ badge: {
+ base: {
+ backgroundColor: 'var(--astryx-theme-local-base-color-status-fill)',
+ },
+ },
+ },
+ });\n`,
+ );
+ await themeBuild('local-base.mjs', {}, {cwd: extDir});
+
+ fs.writeFileSync(
+ path.join(extDir, 'local-child.mjs'),
+ `import {defineTheme} from '@astryxdesign/core/theme';
+ import {localBaseTheme} from './local-base.js';
+ export const localChildTheme = defineTheme({
+ name: 'local-child',
+ extends: localBaseTheme,
+ localTokens: {
+ '--astryx-theme-local-base-color-status-fill': '#654321',
+ '--astryx-theme-local-child-color-surface-raised': '#fedcba',
+ },
+ });\n`,
+ );
+
+ await themeBuild('local-child.mjs', {}, {cwd: extDir});
+ const css = fs.readFileSync(path.join(extDir, 'local-child.css'), 'utf8');
+ const built = fs.readFileSync(path.join(extDir, 'local-child.js'), 'utf8');
+
+ expect(css).toContain(
+ '--astryx-theme-local-base-color-status-fill: #654321;',
+ );
+ expect(css).toContain(
+ '--astryx-theme-local-child-color-surface-raised: #fedcba;',
+ );
+ expect(built).toContain(
+ '__localTokenLineage: ["local-base","local-child"]',
+ );
+ });
+
it('resolves extends on a plain object theme file (no defineTheme call)', async () => {
fs.writeFileSync(path.join(extDir, 'ext-base.mjs'), BASE_SOURCE);
fs.writeFileSync(
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index ccf8a368e2..e964534765 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -162,7 +162,7 @@ function App() {
content: [
{
type: 'prose',
- text: 'defineTheme creates a theme from token overrides and optional scale configs. Scale configs generate tokens from parameters. Explicit token overrides always take precedence over scale-generated values, token by token. One caveat for the accent: overriding --color-accent in tokens re-points the reference tokens (--color-accent-muted, --color-text-accent, --color-icon-accent) but NOT --color-on-accent, which stays baked from the color.accent seed. To give each scheme its own accent with a consistent derived palette, pass a [light, dark] tuple to color.accent instead of overriding the token.',
+ text: 'defineTheme creates a theme from token overrides and optional scale configs. Scale configs generate tokens from parameters. Explicit token overrides always take precedence over scale-generated values, token by token. Theme maintainers may declare reusable, non-portable roles through localTokens using complete --astryx-theme-<name>-* custom-property names; these roles remain inside that enrolled theme family and do not expand the shared token vocabulary. One caveat for the accent: overriding --color-accent in tokens re-points the reference tokens (--color-accent-muted, --color-text-accent, --color-icon-accent) but NOT --color-on-accent, which stays baked from the color.accent seed. To give each scheme its own accent with a consistent derived palette, pass a [light, dark] tuple to color.accent instead of overriding the token.',
},
{
type: 'code',
@@ -184,8 +184,15 @@ const myTheme = defineTheme({
// Explicit overrides take precedence over scale-generated values
'--color-background-body': ['#FFFFFF', '#0A0A0A'],
},
+ localTokens: {
+ '--astryx-theme-my-theme-color-status-fill-accent': ['#0077B6', '#48CAE4'],
+ },
components: {
- button: { 'variant:primary': { color: 'white' } },
+ badge: {
+ 'variant:info': {
+ backgroundColor: 'var(--astryx-theme-my-theme-color-status-fill-accent)',
+ },
+ },
},
});`,
},
diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.ts
index f00f68e705..4215ef4c17 100644
--- a/packages/cli/assets/theme.template.ts
+++ b/packages/cli/assets/theme.template.ts
@@ -222,6 +222,13 @@ export const myTheme = defineTheme({
'--shadow-low': '0 1px 2px light-dark(#0000001A, #00000066)',
},
+ /**
+ * Optional theme-family-local roles. Use the complete exact name and keep
+ * references inside this maintained theme family. These do not become
+ * portable Astryx tokens.
+ */
+ // localTokens: {'--astryx-theme-my-theme-color-status-fill-accent': ['#0077B6', '#48CAE4']},
+
// ───────────────────────────────────────────────────────────────────────
// components — per-component CSS, emitted inside
// `@scope ([data-astryx-theme="my-theme"])`, so it only touches your theme.
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index a2aec99d0c..ea9c065bf6 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -4,6 +4,7 @@ import {describe, it, expect, vi} from 'vitest';
import type {IconRegistry} from '../Icon/globalIconRegistry';
import type {DefinedTheme} from './defineTheme';
import {defineTheme, generateThemeCSS, isDefinedTheme} from './defineTheme';
+import {resolveThemeToken} from './tokens';
function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
const {prose, component} = generateThemeCSS(theme);
@@ -79,6 +80,155 @@ describe('defineTheme', () => {
warn.mockRestore();
});
+ it('keeps explicitly enrolled local tokens separate and emits their exact names', () => {
+ const theme = defineTheme({
+ name: 'ocean-theme',
+ localTokens: {
+ '--astryx-theme-ocean-theme-color-status-fill-accent': [
+ '#0077b6',
+ '#48cae4',
+ ],
+ },
+ components: {
+ badge: {
+ 'variant:info': {
+ backgroundColor:
+ 'var(--astryx-theme-ocean-theme-color-status-fill-accent)',
+ },
+ },
+ },
+ });
+
+ expect(theme.tokens).not.toHaveProperty(
+ '--astryx-theme-ocean-theme-color-status-fill-accent',
+ );
+ expect(theme.localTokens).toEqual({
+ '--astryx-theme-ocean-theme-color-status-fill-accent':
+ 'light-dark(#0077b6, #48cae4)',
+ });
+ expect(theme.__localTokenOwners).toEqual({
+ '--astryx-theme-ocean-theme-color-status-fill-accent': 'ocean-theme',
+ });
+ expect(theme.__localTokenLineage).toEqual(['ocean-theme']);
+ expect(generateThemeTestCSS(theme)).toContain(
+ '--astryx-theme-ocean-theme-color-status-fill-accent: light-dark(#0077b6, #48cae4);',
+ );
+ });
+
+ it('rejects a name declared in both tokens and localTokens before CSS and token helpers can disagree', () => {
+ const token = '--astryx-theme-ocean-theme-color-status-fill-accent';
+ const legacyTheme = defineTheme({
+ name: 'ocean-theme',
+ tokens: {
+ // @ts-expect-error legacy tokens remain permissive at runtime
+ [token]: '#0077b6',
+ },
+ });
+
+ expect(generateThemeTestCSS(legacyTheme)).toContain(`${token}: #0077b6;`);
+ expect(resolveThemeToken(legacyTheme, token, {mode: 'light'})).toBe(
+ '#0077b6',
+ );
+
+ expect(() =>
+ defineTheme({
+ name: 'ocean-theme',
+ tokens: {
+ // @ts-expect-error legacy tokens remain permissive at runtime
+ [token]: '#0077b6',
+ },
+ localTokens: {
+ [token]: '#48cae4',
+ },
+ }),
+ ).toThrow(/both tokens and localTokens/);
+ });
+
+ it('does not reinterpret legacy reserved-prefix references without enrollment', () => {
+ const theme = defineTheme({
+ name: 'legacy',
+ tokens: {
+ // @ts-expect-error legacy permissive token input remains unchanged
+ '--astryx-theme-legacy-color-old': '#123456',
+ },
+ components: {
+ badge: {
+ base: {color: 'var(--astryx-theme-missing-color-old)'},
+ },
+ },
+ });
+
+ expect(theme.tokens['--astryx-theme-legacy-color-old']).toBe('#123456');
+ expect(theme).not.toHaveProperty('localTokens');
+ expect(theme).not.toHaveProperty('__localTokenOwners');
+ expect(theme).not.toHaveProperty('__localTokenLineage');
+ });
+
+ it.each([
+ ['Uppercase', '--astryx-theme-Uppercase-color-accent'],
+ ['wrong-space', '--astryx-theme-other-color-accent'],
+ ['wrong-space', '--astryx-theme-wrong-space-Color-accent'],
+ ])('rejects malformed local token enrollment for %s', (name, token) => {
+ expect(() =>
+ defineTheme({
+ name,
+ localTokens: {[token]: '#123456'},
+ }),
+ ).toThrow(/localTokens|local token/);
+ });
+
+ it.each(['VAR', 'vAr'])(
+ 'rejects undeclared local references using %s() in nested and media component rules',
+ functionName => {
+ expect(() =>
+ defineTheme({
+ name: 'ocean',
+ localTokens: {},
+ components: {
+ button: {
+ base: {
+ ':hover': {
+ color: `${functionName}(--astryx-theme-ocean-color-missing)`,
+ },
+ },
+ },
+ },
+ }),
+ ).toThrow(/has no declaration/);
+
+ expect(() =>
+ defineTheme({
+ name: 'ocean',
+ localTokens: {},
+ onDark: {
+ components: {
+ badge: {
+ base: {
+ color: `${functionName}(--astryx-theme-ocean-color-missing)`,
+ },
+ },
+ },
+ },
+ }),
+ ).toThrow(/has no declaration/);
+ },
+ );
+
+ it.each(['VAR', 'vAr'])(
+ 'rejects cycles between local tokens using %s()',
+ functionName => {
+ expect(() =>
+ defineTheme({
+ name: 'cycle',
+ localTokens: {
+ '--astryx-theme-cycle-color-a': `${functionName}(--astryx-theme-cycle-color-b)`,
+ '--astryx-theme-cycle-color-b': `${functionName}(--astryx-theme-cycle-color-a)`,
+ },
+ }),
+ ).toThrow(/cycle detected/);
+ },
+ );
+
it('includes icons in the theme', () => {
const icons = {close: 'X'} as Partial<IconRegistry>;
const theme = defineTheme({name: 'icons', icons});
@@ -1023,6 +1173,83 @@ describe('container padding mapping', () => {
});
describe('defineTheme extends', () => {
+ it('inherits enrollment, allows exact replacement, and owns new child names', () => {
+ const base = defineTheme({
+ name: 'base-theme',
+ localTokens: {
+ '--astryx-theme-base-theme-color-status-fill': '#123456',
+ },
+ });
+ const child = defineTheme({
+ name: 'child-theme',
+ extends: base,
+ localTokens: {
+ '--astryx-theme-base-theme-color-status-fill': '#654321',
+ '--astryx-theme-child-theme-color-surface-raised': '#abcdef',
+ },
+ });
+
+ expect(child.localTokens).toEqual({
+ '--astryx-theme-base-theme-color-status-fill': '#654321',
+ '--astryx-theme-child-theme-color-surface-raised': '#abcdef',
+ });
+ expect(child.__localTokenOwners).toEqual({
+ '--astryx-theme-base-theme-color-status-fill': 'base-theme',
+ '--astryx-theme-child-theme-color-surface-raised': 'child-theme',
+ });
+ expect(child.__localTokenLineage).toEqual(['base-theme', 'child-theme']);
+ });
+
+ it('inherits enrollment when the child declares no local tokens', () => {
+ const base = defineTheme({name: 'base-theme', localTokens: {}});
+ const child = defineTheme({name: 'child-theme', extends: base});
+
+ expect(child.localTokens).toEqual({});
+ expect(child.__localTokenLineage).toEqual(['base-theme', 'child-theme']);
+ });
+
+ it('preserves legacy descendant names when they only inherit enrollment', () => {
+ const base = defineTheme({
+ name: 'base-theme',
+ localTokens: {
+ '--astryx-theme-base-theme-color-status-fill': '#123456',
+ },
+ });
+ const legacyChild = defineTheme({name: 'Legacy.Theme', extends: base});
+ const grandchild = defineTheme({name: 'grandchild', extends: legacyChild});
+
+ expect(legacyChild.localTokens).toEqual(base.localTokens);
+ expect(legacyChild.__localTokenLineage).toEqual([
+ 'base-theme',
+ 'Legacy.Theme',
+ ]);
+ expect(grandchild.localTokens).toEqual(base.localTokens);
+ expect(grandchild.__localTokenLineage).toEqual([
+ 'base-theme',
+ 'Legacy.Theme',
+ 'grandchild',
+ ]);
+ });
+
+ it('rejects a new declaration in another theme namespace', () => {
+ const base = defineTheme({
+ name: 'base-theme',
+ localTokens: {
+ '--astryx-theme-base-theme-color-status-fill': '#123456',
+ },
+ });
+
+ expect(() =>
+ defineTheme({
+ name: 'child-theme',
+ extends: base,
+ localTokens: {
+ '--astryx-theme-base-theme-color-new-role': '#abcdef',
+ },
+ }),
+ ).toThrow(/exact namespace/);
+ });
+
it('inherits tokens from base theme', () => {
const base = defineTheme({
name: 'base',
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 3bf1617f3b..0e02addec8 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -82,6 +82,7 @@ import {domainTokenDefaults} from './domainTokens';
import type {SyntaxThemeDefinition} from './syntax';
import {registerTheme} from './themeRegistry';
import {deepMergeComponents} from './mergeComponents';
+import {resolveLocalTokenContract} from './localTokens';
// =============================================================================
// Types
@@ -303,6 +304,13 @@ export interface DefineThemeInput {
* Values can be a string or [light, dark] tuple.
* Only include tokens you want to override; defaults fill the rest. */
tokens?: Partial<Record<TokenName, TokenValue>>;
+ /**
+ * Theme-family-local CSS custom properties. Keys use the complete
+ * `--astryx-theme-${name}-...` spelling and values follow `TokenValue`.
+ * These names are available only to this enrolled theme lineage and do not
+ * become portable `TokenName` values.
+ */
+ localTokens?: Record<string, TokenValue>;
/**
* Component style overrides — keyed by component name (lowercase).
* Each entry maps style keys to CSS property overrides, scoped under
@@ -387,6 +395,8 @@ export interface DefinedTheme {
name: string;
/** Token overrides — only the tokens the consumer specified */
tokens: Record<string, string>;
+ /** Resolved theme-family-local token declarations. */
+ localTokens?: Record<string, string>;
/** Component style overrides */
components?: ComponentStyleMap;
/** Icon registry */
@@ -402,6 +412,10 @@ export interface DefinedTheme {
* @internal
*/
__inputTokens?: Partial<Record<string, TokenValue>>;
+ /** Exact owner theme for every inherited local-token declaration. @internal */
+ __localTokenOwners?: Record<string, string>;
+ /** Exact enrolled theme lineage; presence marks this theme as enrolled. @internal */
+ __localTokenLineage?: string[];
/**
* Resolved on-media token overrides for dark surfaces.
* Generated by defineTheme from defaults + user onDark overrides.
@@ -670,6 +684,15 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
const __onDark = resolveOnMedia('dark', input.onDark, base?.__onDark);
const __onLight = resolveOnMedia('light', input.onLight, base?.__onLight);
+ const localTokenContract = resolveLocalTokenContract(
+ input,
+ base,
+ tokens,
+ components,
+ __onDark,
+ __onLight,
+ );
+
// 5. Merge icons — input icons override base icons
const icons =
input.icons && base?.icons
@@ -686,6 +709,13 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
const theme: DefinedTheme = {
name: input.name,
tokens,
+ ...(localTokenContract
+ ? {
+ localTokens: localTokenContract.localTokens,
+ __localTokenOwners: localTokenContract.owners,
+ __localTokenLineage: localTokenContract.lineage,
+ }
+ : {}),
components,
icons,
indicators,
diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.ts
index 9aa54f9a25..b84303685a 100644
--- a/packages/core/src/theme/generateThemeRules.ts
+++ b/packages/core/src/theme/generateThemeRules.ts
@@ -345,7 +345,10 @@ export function generateThemeRules(theme: DefinedTheme): string[] {
const val = (key: string): string => tokens[key] || `var(${key})`;
// 1. Token block — CSS custom properties on :scope
- const tokenEntries = Object.entries(tokens);
+ const tokenEntries = [
+ ...Object.entries(tokens),
+ ...Object.entries(theme.localTokens ?? {}),
+ ];
if (tokenEntries.length > 0) {
const declarations = tokenEntries
.map(([prop, value]) => ` ${prop}: ${value};`)
diff --git a/packages/core/src/theme/localTokens.ts b/packages/core/src/theme/localTokens.ts
new file mode 100644
index 0000000000..397fa080bb
--- /dev/null
+++ b/packages/core/src/theme/localTokens.ts
@@ -0,0 +1,272 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {ComponentStyleMap, DefinedTheme, TokenValue} from './defineTheme';
+import type {ResolvedOnMedia} from './onMediaTokens';
+
+const LOCAL_TOKEN_PREFIX = '--astryx-theme-';
+const THEME_NAME_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
+const LOCAL_TOKEN_SUFFIX_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+const CSS_VAR_PATTERN = /var\(\s*(--[^,\s)]+)/gi;
+
+export interface ResolvedLocalTokenContract {
+ localTokens: Record<string, string>;
+ owners: Record<string, string>;
+ lineage: string[];
+}
+
+function hasOwn(object: object, key: PropertyKey): boolean {
+ return Object.prototype.hasOwnProperty.call(object, key);
+}
+
+function isExactLocalTokenName(name: string, owner: string): boolean {
+ const prefix = `${LOCAL_TOKEN_PREFIX}${owner}-`;
+ return (
+ name.startsWith(prefix) &&
+ LOCAL_TOKEN_SUFFIX_PATTERN.test(name.slice(prefix.length))
+ );
+}
+
+function resolveTokenValue(value: TokenValue, path: string): string {
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (
+ Array.isArray(value) &&
+ value.length === 2 &&
+ typeof value[0] === 'string' &&
+ typeof value[1] === 'string'
+ ) {
+ return `light-dark(${value[0]}, ${value[1]})`;
+ }
+ throw new Error(
+ `${path} must be a CSS string or a [light, dark] string tuple.`,
+ );
+}
+
+function collectLocalReferences(value: unknown, refs: Set<string>): void {
+ if (typeof value === 'string') {
+ CSS_VAR_PATTERN.lastIndex = 0;
+ for (
+ let match = CSS_VAR_PATTERN.exec(value);
+ match;
+ match = CSS_VAR_PATTERN.exec(value)
+ ) {
+ const name = match[1];
+ if (name.startsWith(LOCAL_TOKEN_PREFIX)) {
+ refs.add(name);
+ }
+ }
+ return;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ collectLocalReferences(item, refs);
+ }
+ return;
+ }
+ if (value && typeof value === 'object') {
+ for (const nested of Object.values(value)) {
+ collectLocalReferences(nested, refs);
+ }
+ }
+}
+
+function assertNoLocalTokenCycles(localTokens: Record<string, string>): void {
+ const dependencies = new Map<string, string[]>();
+ for (const [name, value] of Object.entries(localTokens)) {
+ const refs = new Set<string>();
+ collectLocalReferences(value, refs);
+ dependencies.set(
+ name,
+ [...refs].filter(reference => hasOwn(localTokens, reference)),
+ );
+ }
+
+ const visiting = new Set<string>();
+ const visited = new Set<string>();
+ const visit = (name: string, path: string[]): void => {
+ if (visiting.has(name)) {
+ const start = path.indexOf(name);
+ const cycle = [...path.slice(start), name].join(' -> ');
+ throw new Error(`Theme-local token cycle detected: ${cycle}.`);
+ }
+ if (visited.has(name)) {
+ return;
+ }
+ visiting.add(name);
+ for (const dependency of dependencies.get(name) ?? []) {
+ visit(dependency, [...path, name]);
+ }
+ visiting.delete(name);
+ visited.add(name);
+ };
+
+ for (const name of Object.keys(localTokens)) {
+ visit(name, []);
+ }
+}
+
+function assertDeclaredReferences(
+ localTokens: Record<string, string>,
+ components: ComponentStyleMap | undefined,
+ onDark: ResolvedOnMedia | undefined,
+ onLight: ResolvedOnMedia | undefined,
+): void {
+ const refs = new Set<string>();
+ collectLocalReferences(localTokens, refs);
+ collectLocalReferences(components, refs);
+ collectLocalReferences(onDark?.components, refs);
+ collectLocalReferences(onLight?.components, refs);
+
+ for (const reference of refs) {
+ if (!hasOwn(localTokens, reference)) {
+ throw new Error(
+ `Theme-local token reference "${reference}" has no declaration in the enrolled theme lineage.`,
+ );
+ }
+ }
+}
+
+function assertInheritedContract(
+ themeName: string,
+ base: DefinedTheme,
+): asserts base is DefinedTheme & {
+ localTokens: Record<string, string>;
+ __localTokenOwners: Record<string, string>;
+ __localTokenLineage: string[];
+} {
+ const lineage = base.__localTokenLineage;
+ if (
+ !Array.isArray(lineage) ||
+ lineage.length === 0 ||
+ lineage[lineage.length - 1] !== base.name ||
+ lineage.some(name => typeof name !== 'string' || name.length === 0)
+ ) {
+ throw new Error(
+ `defineTheme("${themeName}"): the base theme has invalid theme-local token lineage metadata.`,
+ );
+ }
+ if (
+ !base.localTokens ||
+ typeof base.localTokens !== 'object' ||
+ Array.isArray(base.localTokens) ||
+ !base.__localTokenOwners ||
+ typeof base.__localTokenOwners !== 'object' ||
+ Array.isArray(base.__localTokenOwners)
+ ) {
+ throw new Error(
+ `defineTheme("${themeName}"): the base theme has incomplete theme-local token metadata.`,
+ );
+ }
+
+ for (const [name, value] of Object.entries(base.localTokens)) {
+ const owner = base.__localTokenOwners[name];
+ if (
+ typeof value !== 'string' ||
+ !owner ||
+ !lineage.includes(owner) ||
+ !isExactLocalTokenName(name, owner)
+ ) {
+ throw new Error(
+ `defineTheme("${themeName}"): inherited local token "${name}" does not match its exact lineage metadata.`,
+ );
+ }
+ }
+ for (const name of Object.keys(base.__localTokenOwners)) {
+ if (!hasOwn(base.localTokens, name)) {
+ throw new Error(
+ `defineTheme("${themeName}"): inherited local-token owner metadata names undeclared token "${name}".`,
+ );
+ }
+ }
+}
+
+/**
+ * Resolve and validate the opt-in theme-local token contract.
+ *
+ * Themes that omit `localTokens` and do not extend an enrolled base bypass this
+ * function's reserved-namespace checks so legacy token behavior stays intact.
+ */
+export function resolveLocalTokenContract(
+ input: {
+ name: string;
+ localTokens?: Record<string, TokenValue>;
+ },
+ base: DefinedTheme | undefined,
+ tokens: Record<string, string>,
+ components: ComponentStyleMap | undefined,
+ onDark: ResolvedOnMedia | undefined,
+ onLight: ResolvedOnMedia | undefined,
+): ResolvedLocalTokenContract | undefined {
+ const directlyEnrolled = hasOwn(input, 'localTokens');
+ const inherited = base?.__localTokenLineage !== undefined;
+
+ if (!directlyEnrolled && !inherited) {
+ return undefined;
+ }
+
+ if (directlyEnrolled && !THEME_NAME_PATTERN.test(input.name)) {
+ throw new Error(
+ `defineTheme("${input.name}"): themes using localTokens require a stable lower-kebab name.`,
+ );
+ }
+
+ if (inherited && base) {
+ assertInheritedContract(input.name, base);
+ }
+
+ const localTokens = {...base?.localTokens};
+ const owners = {...base?.__localTokenOwners};
+ const declarations = input.localTokens;
+
+ if (
+ directlyEnrolled &&
+ (declarations === null ||
+ declarations === undefined ||
+ typeof declarations !== 'object' ||
+ Array.isArray(declarations))
+ ) {
+ throw new Error(
+ `defineTheme("${input.name}"): localTokens must be a token map.`,
+ );
+ }
+
+ for (const [name, value] of Object.entries(declarations ?? {})) {
+ const inheritedOwner = owners[name];
+ if (!inheritedOwner) {
+ const expectedPrefix = `${LOCAL_TOKEN_PREFIX}${input.name}-`;
+ if (!isExactLocalTokenName(name, input.name)) {
+ throw new Error(
+ `defineTheme("${input.name}"): local token "${name}" must use the exact namespace "${expectedPrefix}" followed by a lowercase kebab-case purpose.`,
+ );
+ }
+ owners[name] = input.name;
+ }
+ localTokens[name] = resolveTokenValue(
+ value,
+ `defineTheme("${input.name}").localTokens["${name}"]`,
+ );
+ }
+
+ for (const name of Object.keys(localTokens)) {
+ if (!owners[name]) {
+ throw new Error(
+ `defineTheme("${input.name}"): inherited local token "${name}" has no owner metadata.`,
+ );
+ }
+ if (hasOwn(tokens, name)) {
+ throw new Error(
+ `defineTheme("${input.name}"): token "${name}" cannot be declared in both tokens and localTokens.`,
+ );
+ }
+ }
+
+ assertDeclaredReferences(localTokens, components, onDark, onLight);
+ assertNoLocalTokenCycles(localTokens);
+
+ return {
+ localTokens,
+ owners,
+ lineage: [...(base?.__localTokenLineage ?? []), input.name],
+ };
+}
diff --git a/scripts/check-theme-template.test.mjs b/scripts/check-theme-template.test.mjs
index e82210c912..5c8b84d462 100644
--- a/scripts/check-theme-template.test.mjs
+++ b/scripts/check-theme-template.test.mjs
@@ -246,7 +246,11 @@ describe('theme template stays in sync with the theme system', () => {
const {publicVars} = themingTargets();
// Domain tokens (syntax, data-viz) live outside tokens.stylex.ts and are
// referenced by prefix in the inventory, not by full name.
- const domainPrefixes = ['--color-syntax-', '--color-data-'];
+ const domainPrefixes = [
+ '--color-syntax-',
+ '--color-data-',
+ '--astryx-theme-my-theme-',
+ ];
const bogus = templateVars().filter(
v =>
!known.has(v) &&