Primitree
API reference

DTCG API

@primitree/dtcg functions and types.

Read, resolve, convert, and build DTCG 2025.10 token data.

Remarks

The package emits token documents and a DTCG 2025.10 Resolver for Figma modes. Its functions do not read or write files.

Classes

DTCGOutputCapabilityError

Reports text, token values, or Resolver states rejected by an output writer.

Extends

  • Error

Constructors

Constructor

new DTCGOutputCapabilityError(format, tokenPath, type, reason?): DTCGOutputCapabilityError

Parameters
format

"css"

tokenPath

string

type

string

reason?

"value" | "token-state"

Returns

DTCGOutputCapabilityError

Overrides

Error.constructor

Constructor

new DTCGOutputCapabilityError(format, tokenPath, type, reason): DTCGOutputCapabilityError

Parameters
format

"tailwind"

tokenPath

string

type

string

reason

"tailwind-namespace"

Returns

DTCGOutputCapabilityError

Overrides

Error.constructor

Properties

format

readonly format: "css" | "tailwind"

Output kind that rejected the value or state.

tokenPath

readonly tokenPath: string

Token path or output location that the writer could not include.


ReferenceResolutionError

Resolver functions throw this error for an unresolved DTCG reference.

Extends

  • Error

Constructors

Constructor

new ReferenceResolutionError(message, path): ReferenceResolutionError

Parameters
message

string

path

string

Returns

ReferenceResolutionError

Overrides

Error.constructor

Properties

path

readonly path: string

Interfaces

ToDTCGOptions

Options for toDTCG.

Extended by

Properties

includeFigmaExtensions?

optional includeFigmaExtensions?: boolean

Attach Figma metadata (variable id, collection, scopes, codeSyntax) under $extensions['com.primitree']. Default: true.

resolverName?

optional resolverName?: string

Resolver document name.


ToDTCGResult

Result of toDTCG.

Properties

files

files: Record<string, DTCGDocument>

File-name map of token documents. One base file per collection (<collection>.tokens.json) plus one override file per non-default mode (<collection>.<mode>.tokens.json).

resolver

resolver: ResolverDocument

DTCG Resolver (2025.10) describing how modes combine.

resolverFileName

resolverFileName: "tokens.resolver.json"

Required file name for the Resolver document.

warnings

warnings: string[]

Conversion warnings. The converter still returns token files when this array is non-empty.


DTCGGraphFragmentOptions

Source details for createDTCGGraphFragment.

Properties

source

readonly source: string

Name used to create the Core source ID and qualify group and token IDs.

uri?

readonly optional uri?: string

Optional file name or URI copied into source, group, and token provenance.


PipelineFile

The pipeline returns each output file in this form.

Properties

path

path: string

Relative path inside the output directory.

contents

contents: string


DTCGOutputSet

Checked DTCG files and the Resolver that selects them.

Remarks

File names are relative to the Resolver file. Token files may use nested paths, such as themes/dark.tokens.json. The emitted tokens/ path can contain at most 64 nested directory levels, 16,639 UTF-8 bytes in total, and 255 UTF-8 bytes per segment. The fixed prefix leaves up to 63 nested levels in a token file name. Primitree readers look for a Resolver named tokens.resolver.json.

Properties

files

readonly files: Record<string, DTCGDocument>

Token files keyed by their path from the Resolver file.

resolver

readonly resolver: ResolverDocument

Resolver used to select the token files and contexts.

resolverFileName

readonly resolverFileName: "tokens.resolver.json"

Required file name for the Resolver output.


BuildOutputOptions

Options for CSS, Tailwind, and TypeScript files from buildDTCGOutputs.

Remarks

Token JSON and the Resolver are always returned. Each option defaults to true.

Properties

css?

readonly optional css?: boolean

Emit css/tokens.css. Default: true.

tailwind?

readonly optional tailwind?: boolean

Emit css/tokens.tailwind.css. Default: true.

typescript?

readonly optional typescript?: boolean

Emit ts/tokens.ts. Default: true.


BuildPipelineOptions

Options for buildPipeline.

Extends

Properties

includeFigmaExtensions?

optional includeFigmaExtensions?: boolean

Attach Figma metadata (variable id, collection, scopes, codeSyntax) under $extensions['com.primitree']. Default: true.

Inherited from

ToDTCGOptions.includeFigmaExtensions

resolverName?

optional resolverName?: string

Resolver document name.

Inherited from

ToDTCGOptions.resolverName

transformer?

optional transformer?: "none" | "style-dictionary" | "terrazzo"

Choose the transformer config to scaffold. Default: style-dictionary.

css?

optional css?: boolean

Emit css/tokens.css. Default: true.

tailwind?

optional tailwind?: boolean

Emit css/tokens.tailwind.css (Tailwind v4 @theme). Default: true.

typescript?

optional typescript?: boolean

Emit ts/tokens.ts. Default: true.

githubAction?

optional githubAction?: boolean

Emit a GitHub Actions workflow template. Default: true.

readme?

optional readme?: boolean

Emit a README into the output directory. Default: true.


PipelineSummary

Summary statistics for reporting.

Properties

collections

collections: number

variables

variables: number

tokenFiles

tokenFiles: number

contexts

contexts: Record<string, string[]>

files

files: string[]


BuildPipelineResult

Result of buildPipeline.

Properties

files

files: PipelineFile[]

warnings

warnings: string[]

summary

summary: PipelineSummary


EmitCssOptions

Options for emitCss.

Properties

optional banner?: string

Header comment for the generated stylesheet.


FlatToken

A flattened token with its dot-joined path.

Extended by

Properties

path

path: string

token

token: DTCGToken


TypedFlatToken

A flattened token and the type that applies after inheritance and alias lookup.

Remarks

type stays undefined when the token has no declaration, inherits no group declaration, and its whole-token alias chain reaches no typed token.

Extends

Properties

path

path: string

Inherited from

FlatToken.path

token

token: DTCGToken

Inherited from

FlatToken.token

type

type: DTCGTokenType | undefined

Effective token type, or undefined without a declaration or typed alias.


DTCGColorValue

A DTCG Color 2025.10 value.

Remarks

Each color has three components. The allowed numeric range depends on colorSpace. alpha ranges from 0 through 1. hex is an optional six-digit sRGB fallback.

See

DTCG color value format

Properties

colorSpace

colorSpace: DTCGColorSpace

components

components: [DTCGColorComponent, DTCGColorComponent, DTCGColorComponent]

alpha?

optional alpha?: number

hex?

optional hex?: string


DTCGDimensionValue

DTCG dimension value.

Properties

value

value: number

unit

unit: "px" | "rem"


DTCGDurationValue

A DTCG duration with a numeric value and an ms or s unit.

See

DTCG duration type

Properties

value

value: number

unit

unit: "s" | "ms"


FigmaMetadataExtension

Figma metadata preserved under $extensions['com.primitree'].

Properties

variableId

variableId: string

collectionId

collectionId: string

collectionName

collectionName: string

scopes?

optional scopes?: string[]

codeSyntax?

optional codeSyntax?: Record<string, string>

hiddenFromPublishing?

optional hiddenFromPublishing?: boolean

resolvedType?

optional resolvedType?: string


DTCGToken

A single DTCG design token.

Properties

$type?

optional $type?: DTCGTokenType

$value

$value: DTCGTokenValue

$description?

optional $description?: string

$deprecated?

optional $deprecated?: string | boolean

$extensions?

optional $extensions?: Record<string, unknown>


DTCGGroup

A DTCG group: nested groups and tokens.

Indexable

[name: string]: string | boolean | Record<string, unknown> | DTCGToken | DTCGGroup | undefined

Properties

$type?

optional $type?: DTCGTokenType

$description?

optional $description?: string

$deprecated?

optional $deprecated?: string | boolean

$extensions?

optional $extensions?: Record<string, unknown>

$root?

optional $root?: DTCGToken


DTCGRef

A $ref pointer used in resolver documents.

Properties

$ref

$ref: string


ResolverSet

A resolver set: named group of token sources.

Properties

sources

sources: (DTCGGroup | DTCGRef)[]


ResolverModifier

A resolver modifier: contextual token overrides (e.g. light/dark).

Properties

description?

optional description?: string

default?

optional default?: string

contexts

contexts: Record<string, (DTCGRef | DTCGDocument)[]>


ResolverDocument

A DTCG Resolver document (Resolver Module, 2025.10).

Properties

$schema?

optional $schema?: string

name?

optional name?: string

version

version: "2025.10"

description?

optional description?: string

sets?

optional sets?: Record<string, ResolverSet>

modifiers?

optional modifiers?: Record<string, ResolverModifier>

resolutionOrder

resolutionOrder: DTCGRef[]

Type Aliases

ResolverContextValidation

ResolverContextValidation = { contexts: Record<string, string>; ok: true; untypedTokenPaths: string[]; } | { contexts: Record<string, string>; ok: false; error: ReferenceResolutionError; }

The result of validating one Resolver context selection.

Union Members

Type Literal

{ contexts: Record<string, string>; ok: true; untypedTokenPaths: string[]; }

contexts

readonly contexts: Record<string, string>

Context selection that passed validation.

ok

readonly ok: true

untypedTokenPaths

readonly untypedTokenPaths: string[]

Token paths without an explicit, inherited, or alias-derived type.


Type Literal

{ contexts: Record<string, string>; ok: false; error: ReferenceResolutionError; }

contexts

readonly contexts: Record<string, string>

Context selection that failed reference or document validation.

ok

readonly ok: false

error

readonly error: ReferenceResolutionError


DTCGColorSpace

DTCGColorSpace = "srgb" | "srgb-linear" | "hsl" | "hwb" | "lab" | "lch" | "oklab" | "oklch" | "display-p3" | "a98-rgb" | "prophoto-rgb" | "rec2020" | "xyz-d65" | "xyz-d50"

One of the 14 color spaces named by DTCG Color 2025.10.

See

DTCG supported color spaces


DTCGColorComponent

DTCGColorComponent = number | "none"

A numeric color component or the DTCG missing-component marker.

Remarks

none marks a component as missing. It has a different meaning from zero.

See

DTCG none keyword


DTCGCubicBezierValue

DTCGCubicBezierValue = [number, number, number, number]

Four control-point coordinates for a DTCG cubic Bezier curve.

Remarks

The entries are P1x, P1y, P2x, and P2y. Both x coordinates range from 0 through 1. Both y coordinates may be any finite number.

See

DTCG cubic Bezier type


DTCGFontFamilyValue

DTCGFontFamilyValue = string | string[]

A DTCG font family name or ordered fallback list.

Remarks

A string names one font family. A string array keeps the authored fallback order.

See

DTCG font family type


DTCGFontWeightValue

DTCGFontWeightValue = number | "thin" | "hairline" | "extra-light" | "ultra-light" | "light" | "normal" | "regular" | "book" | "medium" | "semi-bold" | "demi-bold" | "bold" | "extra-bold" | "ultra-bold" | "black" | "heavy" | "extra-black" | "ultra-black"

A DTCG font weight number or named value.

Remarks

Numeric values range from 1 through 1000. Named values use the lowercase names listed by DTCG 2025.10.

See

DTCG font weight type


DTCGTokenType

DTCGTokenType = "color" | "cubicBezier" | "dimension" | "number" | "fontWeight" | "fontFamily" | "duration" | "string" | "boolean"

Token types that Primitree reads or emits.

Remarks

DTCG 2025.10 does not define boolean. Primitree documents it as an extension because Figma variables support boolean values.


DTCGTokenValue

DTCGTokenValue = DTCGColorValue | DTCGCubicBezierValue | DTCGDimensionValue | DTCGDurationValue | DTCGFontFamilyValue | DTCGFontWeightValue | string | number | boolean

A token $value, including {dot.path} reference strings.


DTCGDocument

DTCGDocument = DTCGGroup

A DTCG token document (the root group of a *.tokens.json file).

Variables

PRIMITREE_EXTENSION_KEY

const PRIMITREE_EXTENSION_KEY: "com.primitree" = 'com.primitree'

Key for Figma metadata in a token's $extensions object.


RESOLVER_SCHEMA_URL

const RESOLVER_SCHEMA_URL: "https://www.designtokens.org/schemas/2025.10/resolver.json" = 'https://www.designtokens.org/schemas/2025.10/resolver.json'

DTCG 2025.10 Resolver JSON Schema URL.

Functions

colorToHex()

colorToHex(color): string

Convert a Figma RGBA color (0–1 channels) to #rrggbb. Alpha values below 1 use #rrggbbaa.

Parameters

color

Color

Returns

string


figmaColorToDTCG()

figmaColorToDTCG(color): DTCGColorValue

Convert a Figma RGBA color into a DTCG 2025.10 color value object (sRGB components with a hex fallback).

Parameters

color

Color

Returns

DTCGColorValue


isFigmaColor()

isFigmaColor(value): value is Color

Type guard for Figma color objects.

Parameters

value

unknown

Returns

value is Color


toDTCG()

toDTCG(input, options?): ToDTCGResult

Convert supported Figma variables JSON into DTCG 2025.10 token files and a Resolver document.

Parameters

input

unknown

Figma variables JSON for normalizeVariables.

options?

ToDTCGOptions = {}

Emission options.

Returns

ToDTCGResult

Remarks

  • The emitter writes one base token file per collection with its default-mode values, wrapped in a group named after the collection so cross-collection alias references ({semantic.color.bg.brand}) are unambiguous.
  • The emitter writes an override file for each non-default mode.
  • The Resolver records multi-mode collections as modifiers with mode-name contexts. The default mode context applies no overrides.
  • The emitter keeps Figma aliases as DTCG references.
  • Boolean variables use the documented Primitree boolean extension.

Example

import { toDTCG } from '@primitree/dtcg'

const { files, resolver } = toDTCG(variablesJson)
for (const [name, doc] of Object.entries(files)) {
  await fs.writeFile(name, JSON.stringify(doc, null, 2))
}

createDTCGGraphFragment()

createDTCGGraphFragment(document, options): Result<GraphFragment>

Read Primitree's supported DTCG value subset into a Core graph fragment.

Parameters

document

unknown

Parsed token document that uses the supported value subset.

options

DTCGGraphFragmentOptions

Source name and optional provenance URI.

Returns

Result<GraphFragment>

A Core result containing a graph fragment or source diagnostics.

Remarks

The caller reads and parses JSON. This function performs no file I/O.

A group $type applies to its child groups and tokens until another group or token sets its own type. The reader accepts $root and keeps $root as the final token path segment.

Supported DTCG token types are color, cubicBezier, dimension, duration, number, fontWeight, fontFamily, and string. The reader also accepts Primitree's documented boolean extension.

Color values may use any of the 14 color spaces checked by this package. Each color has three components in the allowed range for its color space. A component may be none. Alpha from 0 through 1 and six-digit hex text are optional. Dimension values use a finite number with px or rem. Duration values use a finite number with ms or s. Cubic Bezier values use four finite coordinates. Both x coordinates range from 0 through 1. Number values must be finite. Font weights use numbers from 1 through 1000 or the names listed by DTCG. Font families use one name or an ordered list of names. String values use text.

The reader creates immediate edges for whole-token brace references in the supplied document. An alias may omit $type when its reference chain reaches a typed token. The reader requires an alias and its immediate target to have the same effective type whenever that target exists. Core resolves token values later.

A typed alias may keep a missing target for Core composeGraph to report. A cycle whose aliases share one effective type remains in the fragment. Core resolveToken reports graph.reference-cycle when a caller resolves a token in that cycle. The reader rejects a cycle with no type because it cannot infer that type.

The reader checks that $description is text, $deprecated is boolean or text, and $extensions is a plain object. Core graph records do not store those fields, so the returned fragment omits them.

Group and token paths may contain at most 64 segments. Their dot-joined paths may contain at most 256 characters. Token values may contain at most 64 nested levels.

Each call has one 100,000-unit work limit. It counts document entries, characters in brace references, each literal value scan, token-value object key, and token-value array entry.

The reader rejects $extends, JSON Pointer references, references nested inside literal values, unknown reserved properties, and token types outside the supported list.

Example

import { createDTCGGraphFragment } from '@primitree/dtcg'

const result = createDTCGGraphFragment(
  {
    scale: {
      $type: 'number',
      base: { $value: 4 },
      control: { $value: '{scale.base}' },
    },
  },
  { source: 'brand', uri: 'tokens.json' }
)

if (!result.ok) {
  throw new Error(result.diagnostics[0]?.message ?? 'DTCG input failed')
}

const fragment = result.value

See

DTCG 2025.10 Format Module


inferTokenType()

inferTokenType(variable): "string" | "number" | "boolean" | "color" | "dimension" | "duration" | "fontFamily" | "fontWeight"

Infer the DTCG $type for a Figma variable using its resolved type, scopes, and (as a fallback) naming conventions.

Parameters

variable

NormalizedVariable

Returns

"string" | "number" | "boolean" | "color" | "dimension" | "duration" | "fontFamily" | "fontWeight"

Remarks

Heuristics for FLOAT variables:

  1. Scopes win: OPACITY/EFFECT_FLOATnumber, FONT_WEIGHTfontWeight, LINE_HEIGHTnumber, sizing scopes → dimension.
  2. Otherwise the variable name decides (radius, space, gap, ... → dimension; durationduration; weightfontWeight; ...).
  3. Defaults to number.

slugify()

slugify(input): string

Kebab-case slug for file names, resolver set/modifier names, and collection group names.

Parameters

input

string

Returns

string


sanitizeSegment()

sanitizeSegment(segment): string

Sanitize one path segment according to DTCG name restrictions. Token names cannot contain {, }, or ., and cannot start with $.

Parameters

segment

string

Returns

string


toPathSegments()

toPathSegments(variableName): string[]

Split a Figma variable name (color/bg/brand) into sanitized DTCG path segments.

Parameters

variableName

string

Returns

string[]


allocateUniqueSlugs()

allocateUniqueSlugs<T>(items, getName): string[]

Allocate unique slugs while preserving each item's input position.

Type Parameters

T

T

Parameters

items

readonly T[]

getName

(item) => string

Returns

string[]


uniqueSlugs()

uniqueSlugs(names): Map<string, string>

Return unique slugs for a list of names. Collisions receive -2, -3, and later suffixes.

Parameters

names

string[]

Returns

Map<string, string>


buildDTCGOutputs()

buildDTCGOutputs(input, options?): BuildPipelineResult

Build DTCG, CSS, TypeScript, and Tailwind files in memory.

Parameters

input

DTCGOutputSet

Checked token files and their Resolver.

options?

BuildOutputOptions = {}

CSS, Tailwind, and TypeScript files to include.

Returns

BuildPipelineResult

Candidate files, counts, contexts, and an empty warning list.

Remarks

The input must contain checked local DTCG files and a Resolver that selects them. This function does not read or write files. Projects may select Tailwind output without CSS if they supply matching custom properties.

The function accepts at most 1,000 token files. After the fixed tokens/ prefix, a token file output can contain at most 64 nested directory levels, 16,639 UTF-8 bytes in total, and 255 UTF-8 bytes per segment. A relative token file name can therefore contain at most 63 nested directory levels. JSON sorting stops after 64 levels, 100,000 items, or 20 MiB of names and string values. These limits apply before the function creates CSS or TypeScript text. The generated Resolver keeps modifier and context order. This preserves CSS rule order and each modifier’s fallback context when tools load the file again.

The summary reads at most 64 token-group levels. Its 1,000,000-unit work limit counts Resolver reads and token merges.

CSS and Tailwind evaluate at most 1,000 active-context permutations. CSS, Tailwind, and TypeScript read at most 64 token-group levels and return at most 20 MiB. Tailwind reads at most 100,000 items per context. Each output has a 1,000,000-unit work limit. CSS counts active Resolver contexts, token merges, value comparisons, declarations, token paths, and token text. Tailwind counts active Resolver contexts, token merges, token walking, alias type resolution, namespace checks, token paths, name allocation, and output text. TypeScript also counts flattening, reference resolution, token paths, sorting, and value serialization.

Throws

DTCGOutputCapabilityError - CSS rejects a checked value or Resolver state that it cannot represent, or a token path changes Tailwind namespace between Resolver states.

Throws

Error - The builder rejects unsafe file names and emitted token paths whose depth or size exceeds these limits. It also rejects a Resolver file name other than tokens.resolver.json, lone surrogates in Resolver names, output path collisions, and CSS name collisions.

Throws

TypeError - JSON sorting rejects cycles and data above its limits. The summary, CSS, Tailwind, and TypeScript outputs reject calls that exceed their work limits or read more than 64 token-group levels. CSS and TypeScript reject output above 20 MiB. CSS and Tailwind reject more than 1,000 active context permutations. Tailwind rejects input above 100,000 items per context.

Example

import {
  buildDTCGOutputs,
  type DTCGDocument,
} from '@primitree/dtcg'

const tokens = {
  scale: {
    base: { $type: 'number', $value: 4 },
  },
} satisfies DTCGDocument

const result = buildDTCGOutputs({
  files: { 'source.tokens.json': tokens },
  resolver: {
    version: '2025.10',
    sets: {
      source: { sources: [{ $ref: 'source.tokens.json' }] },
    },
    resolutionOrder: [{ $ref: '#/sets/source' }],
  },
  resolverFileName: 'tokens.resolver.json',
})

console.log(result.files.map(file => file.path))

See

DTCG Resolver 2025.10


buildPipeline()

buildPipeline(input, options?): BuildPipelineResult

Build token JSON, a Resolver, CSS, Tailwind v4 mappings, TypeScript values, transformer config, workflow, and README as in-memory files.

Parameters

input

unknown

options?

BuildPipelineOptions = {}

Returns

BuildPipelineResult

Remarks

Pure function: callers decide whether to write to disk (primitree build) or zip in the browser (the playground).


cssVarName()

cssVarName(path): string

Convert a dot path to a CSS custom property name.

Dots separate path segments. ASCII letters, digits, and non-ASCII code points stay unchanged. Each other code point becomes a lowercase hex marker, such as _3f_ for ?. This keeps different valid token paths from sharing a CSS name.

Parameters

path

string

Returns

string


cssValue()

cssValue(value): string | null

Format a DTCG token value as CSS.

Parameters

value

DTCGTokenValue

Token value to format.

Returns

string | null

CSS text, or null when CSS output cannot represent the value.

Remarks

References become var(--...). Color values keep their DTCG color space, components, and alpha. A color's optional hex fallback stays in DTCG output and does not replace the authored components. Cubic Bezier values become CSS cubic-bezier() timing functions.

Example

const value = cssValue({
  colorSpace: 'display-p3',
  components: [0.2, 0.4, 1],
  alpha: 0.75,
})
// value is "color(display-p3 0.2 0.4 1 / 0.75)"

typedCssValue()

typedCssValue(value, type): string | null

Format a DTCG token value as CSS using its effective token type.

Parameters

value

DTCGTokenValue

Resolved token value to format.

type

DTCGTokenType | undefined

Effective token type after inheritance and alias resolution.

Returns

string | null

CSS text, or null when CSS output cannot represent the value.

Remarks

Most token values format the same way regardless of type. DTCG font-weight names that CSS does not accept need the effective fontWeight type to produce numeric equivalents. The type can come from the token, a parent group, or an alias target.

Example

const weight = typedCssValue('semi-bold', 'fontWeight')
// weight is "600"

const label = typedCssValue('semi-bold', 'string')
// label is "semi-bold"

emitCss()

emitCss(files, resolver, options?): string

Emit CSS custom properties from token files and a Resolver.

Parameters

files

Record<string, DTCGDocument>

Token files keyed by their path from the Resolver file.

resolver

ResolverDocument

Resolver that selects files and default contexts.

options?

EmitCssOptions = {}

Optional stylesheet banner.

Returns

string

CSS custom properties for the selected token values.

Remarks

:root contains the default values. A single non-default axis writes the token values that differ from :root. Two or more non-default axes write the full selected token set under a compound selector. The emitter escapes string values, modifier axes, and context names before writing CSS. Color values keep their DTCG color space, components, and alpha.

One call evaluates at most 1,000 active-context permutations, reads at most 64 token-group levels, and returns at most 20 MiB. Its 1,000,000-unit work limit counts active Resolver contexts, token merges, value comparisons, declarations, token paths, and token text. The emitter rejects token paths that map to the same CSS custom property name. The emitter also rejects CSS comment terminators in custom banners, U+0000, and lone UTF-16 surrogates in raw CSS text.

Throws

TypeError - A call exceeds 1,000 active-context permutations, 1,000,000 work units, 64 token-group levels, or 20 MiB of CSS.

Throws

DTCGOutputCapabilityError - The CSS writer cannot format a token value, custom banner, Resolver context name, or token path across Resolver states.

Throws

Error - Two token paths map to the same CSS custom property name.


emitTailwind()

emitTailwind(files, resolver): string

Emit a Tailwind CSS v4 @theme inline file that maps design tokens onto Tailwind's theme namespaces, referencing the custom properties from the generated tokens.css so mode switching keeps working.

Parameters

files

Record<string, DTCGDocument>

Token files keyed by their path from the Resolver file.

resolver

ResolverDocument

Resolver that selects files and default contexts.

Returns

string

Tailwind CSS v4 theme variables linked to generated CSS variables.

Remarks

Mapping: color--color-*; dimension--radius-* for paths that mention radius and --spacing-* for other paths; fontFamily--font-*; fontWeight--font-weight-*; cubicBezier--ease-*. The emitter skips types without a Tailwind namespace. A token path must map to the same namespace in every Resolver context where Tailwind reads it.

One call evaluates at most 1,000 active-context permutations, reads at most 64 token-group levels and 100,000 items per context, and returns at most 20 MiB. Its 1,000,000-unit work limit counts active Resolver contexts, token merges, token walking, alias type resolution, namespace checks, token paths, name allocation, and output text.

Throws

TypeError - A call exceeds 1,000 active-context permutations, 1,000,000 work units, 64 token-group levels, 100,000 items per context, or 20 MiB of output.

Throws

DTCGOutputCapabilityError - A token path changes Tailwind namespace or disappears between Resolver contexts.

Throws

Error - Two emitted token paths map to the same CSS custom property name.


emitTypescript()

emitTypescript(files, resolver): string

Emit a typed TypeScript module for the generated tokens: a TokenPath union, a map of CSS var() accessors, and the resolved default-context values.

One call reads at most 64 token-group levels and returns at most 20 MiB. Its 1,000,000-unit work limit counts Resolver reads, token merges, token flattening, reference resolution, token paths, sorting, and value serialization.

Parameters

files

Record<string, DTCGDocument>

resolver

ResolverDocument

Returns

string

Throws

TypeError - A call exceeds 1,000,000 work units or 64 token-group levels, or returns more than 20 MiB.


flattenTypedTokens()

flattenTypedTokens(document): TypedFlatToken[]

Flatten a DTCG document and include each token's effective type.

Parameters

document

DTCGGroup

Token document to flatten.

Returns

TypedFlatToken[]

Tokens with their dot-joined paths and effective types.

Remarks

A token's effective type comes from its own $type, an inherited group $type, or the target of an untyped whole-token alias.

One call reads at most 64 token-group levels and spends at most 1,000,000 work units on document entries, token paths, and alias type resolution.

Throws

ReferenceResolutionError - Invalid document structure.

Throws

TypeError - The call exceeds its depth or work limit.


mergeDocuments()

mergeDocuments(documents): DTCGGroup

Deep-merge DTCG documents; later documents override earlier ones at the token level (a token in a later document replaces the same path).

One call reads at most 64 token-group levels and spends at most 1,000,000 work units on document entries and group paths.

Parameters

documents

DTCGGroup[]

Returns

DTCGGroup

Throws

TypeError - The call exceeds its depth or work limit.


flattenTokens()

flattenTokens(document): FlatToken[]

Flatten a DTCG document into a list of { path, token } entries.

One call reads at most 64 token-group levels and spends at most 1,000,000 work units on document entries and token paths.

Parameters

document

DTCGGroup

Returns

FlatToken[]

Throws

TypeError - The call exceeds its depth or work limit.


resolveTokenValues()

resolveTokenValues(flat): Map<string, DTCGTokenValue>

Resolve {dot.path} references in a flattened token map.

Parameters

flat

FlatToken[]

Returns

Map<string, DTCGTokenValue>

Map of token path to resolved value.

Remarks

One call can spend up to 1,000,000 work units. Work includes token paths, references, reference walks, cycle messages, and resolved entries.

Throws

ReferenceResolutionError - A target is missing or a reference cycle exists.

Throws

TypeError - The call exceeds 1,000,000 work units.


resolveTokenValuesSafe()

resolveTokenValuesSafe(flat): object

Resolve references while collecting failures in an errors array.

Parameters

flat

FlatToken[]

Returns

object

Resolved values and one error for each input token that fails.

values

values: Map<string, DTCGTokenValue>

errors

errors: ReferenceResolutionError[]

Remarks

One call can spend up to 1,000,000 work units. Work includes token paths, references, reference walks, cycle messages, and resolved entries.

Throws

TypeError - The call exceeds 1,000,000 work units.


listContexts()

listContexts(resolver): Record<string, string[]>

List Resolver modifier axes and contexts.

One call can spend up to 1,000,000 work units reading modifier and context names, defaults, and context arrays.

Parameters

resolver

ResolverDocument

Returns

Record<string, string[]>

Throws

TypeError - The call exceeds 1,000,000 work units.


applyResolver()

applyResolver(files, resolver, input?): DTCGGroup

Apply a DTCG Resolver to token files for a context selection.

Parameters

files

Record<string, DTCGDocument>

File-name map of token documents from toDTCG.

resolver

ResolverDocument

The resolver document.

input?

Record<string, string> = {}

Context selection per modifier (e.g. { semantic: 'dark' }). Missing modifiers use their declared default, falling back to the first declared context.

Returns

DTCGGroup

Example

const { files, resolver } = toDTCG(variablesJson)
const darkTokens = applyResolver(files, resolver, { semantic: 'dark' })

One call reads at most 64 token-group levels and spends at most 1,000,000 work units on Resolver entries, source text, token documents, and merges.

Throws

TypeError - The call exceeds its depth or work limit.


listPermutations()

listPermutations(resolver): Record<string, string>[]

List Resolver context permutations.

A Resolver can produce at most 1,000 permutations. One call also has a 1,000,000-unit work limit for reading contexts and copying selections.

Parameters

resolver

ResolverDocument

Returns

Record<string, string>[]

Array of context selections (e.g. [{ semantic: 'light', density: 'compact' }, ...]).

Throws

TypeError - The Resolver produces more than 1,000 permutations or exceeds the work limit.


validateResolverContexts()

validateResolverContexts(files, resolver): ResolverContextValidation[]

Validate every Resolver context selection within one shared work budget.

Parameters

files

Record<string, DTCGDocument>

File-name map of token documents.

resolver

ResolverDocument

Resolver document whose context selections to validate.

Returns

ResolverContextValidation[]

One validation result for each declared context permutation.

Remarks

Successful results include paths whose tokens have no explicit, inherited, or whole-token-alias-derived type. Reference and token-document failures stay attached to their context so callers can report every failing selection.

One call validates at most 1,000 context permutations, reads at most 64 token-group levels, and spends at most 1,000,000 work units across context enumeration, Resolver application, effective-type flattening, reference resolution, and returned results.

Throws

TypeError - The call exceeds its permutation, depth, or work limit.

Throws

ReferenceResolutionError - The Resolver cannot enumerate its context selections.


isToken()

isToken(node): node is DTCGToken

Check whether a node is an object with its own $value.

Parameters

node

unknown

Returns

node is DTCGToken


isReferenceValue()

isReferenceValue(value): value is string

Type guard for DTCG reference strings like {color.bg.brand}.

Parameters

value

unknown

Returns

value is string

On this page

RemarksClassesDTCGOutputCapabilityErrorExtendsConstructorsConstructorParametersformattokenPathtypereason?ReturnsOverridesConstructorParametersformattokenPathtypereasonReturnsOverridesPropertiesformattokenPathReferenceResolutionErrorExtendsConstructorsConstructorParametersmessagepathReturnsOverridesPropertiespathInterfacesToDTCGOptionsExtended byPropertiesincludeFigmaExtensions?resolverName?ToDTCGResultPropertiesfilesresolverresolverFileNamewarningsDTCGGraphFragmentOptionsPropertiessourceuri?PipelineFilePropertiespathcontentsDTCGOutputSetRemarksPropertiesfilesresolverresolverFileNameBuildOutputOptionsRemarksPropertiescss?tailwind?typescript?BuildPipelineOptionsExtendsPropertiesincludeFigmaExtensions?Inherited fromresolverName?Inherited fromtransformer?css?tailwind?typescript?githubAction?readme?PipelineSummaryPropertiescollectionsvariablestokenFilescontextsfilesBuildPipelineResultPropertiesfileswarningssummaryEmitCssOptionsPropertiesbanner?FlatTokenExtended byPropertiespathtokenTypedFlatTokenRemarksExtendsPropertiespathInherited fromtokenInherited fromtypeDTCGColorValueRemarksSeePropertiescolorSpacecomponentsalpha?hex?DTCGDimensionValuePropertiesvalueunitDTCGDurationValueSeePropertiesvalueunitFigmaMetadataExtensionPropertiesvariableIdcollectionIdcollectionNamescopes?codeSyntax?hiddenFromPublishing?resolvedType?DTCGTokenProperties$type?$value$description?$deprecated?$extensions?DTCGGroupIndexableProperties$type?$description?$deprecated?$extensions?$root?DTCGRefProperties$refResolverSetPropertiessourcesResolverModifierPropertiesdescription?default?contextsResolverDocumentProperties$schema?name?versiondescription?sets?modifiers?resolutionOrderType AliasesResolverContextValidationUnion MembersType LiteralcontextsokuntypedTokenPathsType LiteralcontextsokerrorDTCGColorSpaceSeeDTCGColorComponentRemarksSeeDTCGCubicBezierValueRemarksSeeDTCGFontFamilyValueRemarksSeeDTCGFontWeightValueRemarksSeeDTCGTokenTypeRemarksDTCGTokenValueDTCGDocumentVariablesPRIMITREE_EXTENSION_KEYRESOLVER_SCHEMA_URLFunctionscolorToHex()ParameterscolorReturnsfigmaColorToDTCG()ParameterscolorReturnsisFigmaColor()ParametersvalueReturnstoDTCG()Parametersinputoptions?ReturnsRemarksExamplecreateDTCGGraphFragment()ParametersdocumentoptionsReturnsRemarksExampleSeeinferTokenType()ParametersvariableReturnsRemarksslugify()ParametersinputReturnssanitizeSegment()ParameterssegmentReturnstoPathSegments()ParametersvariableNameReturnsallocateUniqueSlugs()Type ParametersTParametersitemsgetNameReturnsuniqueSlugs()ParametersnamesReturnsbuildDTCGOutputs()Parametersinputoptions?ReturnsRemarksThrowsThrowsThrowsExampleSeebuildPipeline()Parametersinputoptions?ReturnsRemarkscssVarName()ParameterspathReturnscssValue()ParametersvalueReturnsRemarksExampletypedCssValue()ParametersvaluetypeReturnsRemarksExampleemitCss()Parametersfilesresolveroptions?ReturnsRemarksThrowsThrowsThrowsemitTailwind()ParametersfilesresolverReturnsRemarksThrowsThrowsThrowsemitTypescript()ParametersfilesresolverReturnsThrowsflattenTypedTokens()ParametersdocumentReturnsRemarksThrowsThrowsmergeDocuments()ParametersdocumentsReturnsThrowsflattenTokens()ParametersdocumentReturnsThrowsresolveTokenValues()ParametersflatReturnsRemarksThrowsThrowsresolveTokenValuesSafe()ParametersflatReturnsvalueserrorsRemarksThrowslistContexts()ParametersresolverReturnsThrowsapplyResolver()Parametersfilesresolverinput?ReturnsExampleThrowslistPermutations()ParametersresolverReturnsThrowsvalidateResolverContexts()ParametersfilesresolverReturnsRemarksThrowsThrowsisToken()ParametersnodeReturnsisReferenceValue()ParametersvalueReturns