Core API
@primitree/core functions and types.
Framework-independent Figma Variables and token graph utilities.
Remarks
The package exports Figma Variables REST clients, endpoint builders, data types, normalization, alias resolution, diffs, error helpers, and retry support. It also exports functions to build, inspect, resolve, and compare token graphs. It has no React or SWR dependency.
Example
import { fetcher, FIGMA_LOCAL_VARIABLES_ENDPOINT } from '@primitree/core'
const data = await fetcher(FIGMA_LOCAL_VARIABLES_ENDPOINT(fileKey), token)Classes
VariablesParseError
normalizeVariables throws this error for documents outside the supported Figma variables shapes.
Extends
Error
Constructors
Constructor
new VariablesParseError(
message):VariablesParseError
Parameters
message
string
Returns
Overrides
Error.constructor
AliasResolutionError
Alias resolution functions throw this error for an alias chain without a concrete value.
Extends
Error
Constructors
Constructor
new AliasResolutionError(
message,code,chain):AliasResolutionError
Parameters
message
string
code
chain
string[]
Returns
Overrides
Error.constructor
Properties
code
readonlycode:AliasResolutionErrorCode
chain
readonlychain:string[]
Variable IDs traversed before the failure, in order.
FigmaApiError
Figma REST helpers throw this error after an unsuccessful API response.
Remarks
The error keeps the HTTP status code. A 429 response can include the
Retry-After value in seconds.
Example
import { FigmaApiError } from '@primitree/core';
try {
await fetcher(url, token);
} catch (error) {
if (error instanceof FigmaApiError) {
if (error.statusCode === 401) {
// Handle authentication error
} else if (error.statusCode === 429) {
// Handle rate limit
console.log(`Retry after ${error.retryAfter} seconds`);
}
}
}Extends
Error
Constructors
Constructor
new FigmaApiError(
message,statusCode,retryAfter?):FigmaApiError
Parameters
message
string
statusCode
number
retryAfter?
number
Returns
Overrides
Error.constructor
Properties
statusCode
readonlystatusCode:number
HTTP status code from the API response.
retryAfter
readonlyretryAfter:number|undefined
Retry-After header value in seconds for HTTP 429 responses. Undefined for responses without a Retry-After header.
Interfaces
FetcherOptions
Options for fetcher.
Properties
signal?
optionalsignal?:AbortSignal
Signal that can cancel the request.
timeout?
optionaltimeout?:number
Request timeout in milliseconds.
fetch?
optionalfetch?: {(input,init?):Promise<Response>; (input,init?):Promise<Response>; }
Fetch implementation. Defaults to globalThis.fetch.
Call Signature
(
input,init?):Promise<Response>
Parameters
input
URL | RequestInfo
init?
RequestInit
Returns
Promise<Response>
Call Signature
(
input,init?):Promise<Response>
Parameters
input
string | URL | Request
init?
RequestInit
Returns
Promise<Response>
baseUrl?
optionalbaseUrl?:string
API base URL. Defaults to https://api.figma.com.
MutatorOptions
Options for mutator.
Properties
signal?
optionalsignal?:AbortSignal
Signal that can cancel the request.
timeout?
optionaltimeout?:number
Request timeout in milliseconds.
fetch?
optionalfetch?: {(input,init?):Promise<Response>; (input,init?):Promise<Response>; }
Fetch implementation. Defaults to globalThis.fetch.
Call Signature
(
input,init?):Promise<Response>
Parameters
input
URL | RequestInfo
init?
RequestInit
Returns
Promise<Response>
Call Signature
(
input,init?):Promise<Response>
Parameters
input
string | URL | Request
init?
RequestInit
Returns
Promise<Response>
baseUrl?
optionalbaseUrl?:string
API base URL. Defaults to https://api.figma.com.
DiffCollectionRef
A collection reference in a diff.
Properties
id
id:
string
name
name:
string
DiffVariableRef
A variable reference in a diff.
Properties
id
id:
string
name
name:
string
collectionName
collectionName:
string
DiffRename
Rename record with a stable Figma ID.
Properties
id
id:
string
from
from:
string
to
to:
string
collectionName
collectionName:
string
DiffModeChange
A mode added or removed on a collection.
Properties
collectionName
collectionName:
string
modeId
modeId:
string
modeName
modeName:
string
DiffValueChange
A per-mode value change.
Properties
id
id:
string
name
name:
string
collectionName
collectionName:
string
modeName
modeName:
string
from
from:
VariableValue|undefined
to
to:
VariableValue|undefined
DiffTypeChange
A resolved type change, classified as breaking.
Properties
id
id:
string
name
name:
string
collectionName
collectionName:
string
from
from:
string
to
to:
string
DiffMove
A variable moved between collections.
Properties
id
id:
string
name
name:
string
from
from:
string
to
to:
string
VariablesDiff
Semantic difference between two Figma variables exports. The comparison
uses stable Figma IDs and reports renames in the renamed lists.
Properties
collections
collections:
object
added
added:
DiffCollectionRef[]
removed
removed:
DiffCollectionRef[]
renamed
renamed:
DiffRename[]
modesAdded
modesAdded:
DiffModeChange[]
modesRemoved
modesRemoved:
DiffModeChange[]
modesRenamed
modesRenamed:
object[]
variables
variables:
object
added
added:
DiffVariableRef[]
removed
removed:
DiffVariableRef[]
renamed
renamed:
DiffRename[]
moved
moved:
DiffMove[]
typeChanged
typeChanged:
DiffTypeChange[]
valueChanged
valueChanged:
DiffValueChange[]
descriptionChanged
descriptionChanged:
DiffVariableRef[]
breaking
breaking:
boolean
True when the diff contains a breaking change.
hasChanges
hasChanges:
boolean
GraphDiagnostic
Properties
code
readonlycode:string
phase
readonlyphase:GraphPhase
message
readonlymessage:string
path?
readonlyoptionalpath?: readonlystring[]
tokenId?
readonlyoptionaltokenId?:TokenId
Provenance
Properties
uri?
readonlyoptionaluri?:string
pointer?
readonlyoptionalpointer?:string
digest?
readonlyoptionaldigest?:string
line?
readonlyoptionalline?:number
column?
readonlyoptionalcolumn?:number
SourceRecord
Properties
id
readonlyid:SourceId
type
readonlytype:string
name?
readonlyoptionalname?:string
precedence
readonlyprecedence:number
provenance
readonlyprovenance: readonlyProvenance[]
GroupNode
Properties
id
readonlyid:GroupId
sourceId
readonlysourceId:SourceId
name
readonlyname:string
path
readonlypath: readonlystring[]
provenance
readonlyprovenance: readonlyProvenance[]
AuthoredTokenValue
Properties
value
readonlyvalue:TokenValue
conditions
readonlyconditions:ContextSelection
priority
readonlypriority:number
provenance
readonlyprovenance: readonlyProvenance[]
TokenNode
Properties
id
readonlyid:TokenId
sourceId
readonlysourceId:SourceId
groupId?
readonlyoptionalgroupId?:GroupId
name
readonlyname:string
path
readonlypath: readonlystring[]
type
readonlytype:TokenType
values
readonlyvalues: readonlyAuthoredTokenValue[]
provenance
readonlyprovenance: readonlyProvenance[]
ReferenceEdge
Properties
from
readonlyfrom:TokenId
to
readonlyto:TokenId
conditions
readonlyconditions:ContextSelection
GraphFragment
Properties
source
readonlysource:SourceRecord
groups
readonlygroups: readonlyGroupNode[]
tokens
readonlytokens: readonlyTokenNode[]
references
readonlyreferences: readonlyReferenceEdge[]
TokenGraph
Properties
sources
readonlysources: readonlySourceRecord[]
groups
readonlygroups: readonlyGroupNode[]
tokens
readonlytokens: readonlyTokenNode[]
references
readonlyreferences: readonlyReferenceEdge[]
ViewToken
Properties
tokenId
readonlytokenId:TokenId
path
readonlypath: readonlystring[]
GraphView
Properties
schemaVersion
readonlyschemaVersion:1
id
readonlyid:GraphViewId
sourceIds
readonlysourceIds: readonlySourceId[]
groups
readonlygroups: readonlyGroupId[]
tokens
readonlytokens: readonlyViewToken[]
DependencyQueryOptions
Properties
transitive?
readonlyoptionaltransitive?:boolean
ResolvedToken
Properties
tokenId
readonlytokenId:TokenId
path
readonlypath: readonlystring[]
type
readonlytype:TokenType
value
readonlyvalue:JsonValue
sourceSelection
readonlysourceSelection:ContextSelection
directReferences
readonlydirectReferences: readonlyTokenId[]
referenceChain
readonlyreferenceChain: readonlyTokenId[]
GraphSnapshot
Properties
graph
readonlygraph:TokenGraph
view
readonlyview:GraphView
TokenInspection
Properties
tokenId
readonlytokenId:TokenId
path
readonlypath: readonlystring[]
token
readonlytoken:TokenNode
dependencies
readonlydependencies: readonlyTokenId[]
dependents
readonlydependents: readonlyTokenId[]
resolution
readonlyresolution:ResolvedToken
GraphChange
Properties
kind
readonlykind:GraphChangeKind
tokenId
readonlytokenId:TokenId
impactedTokenIds
readonlyimpactedTokenIds: readonlyTokenId[]
GraphDiff
Properties
changes
readonlychanges: readonlyGraphChange[]
NormalizedMode
A single mode within a normalized collection.
Properties
id
id:
string
Figma mode ID (e.g. 1:0).
name
name:
string
Human-readable mode name (e.g. Light).
NormalizedCollection
A normalized Figma variable collection.
Remarks
The same shape regardless of whether the input came from the REST API, a fallback file, or a plugin-based export.
Properties
id
id:
string
name
name:
string
modes
modes:
NormalizedMode[]
defaultModeId
defaultModeId:
string
variableIds
variableIds:
string[]
hiddenFromPublishing
hiddenFromPublishing:
boolean
NormalizedVariable
A normalized Figma variable.
Properties
id
id:
string
name
name:
string
Slash-separated variable path as authored in Figma (e.g. color/bg/brand).
collectionId
collectionId:
string
resolvedType
resolvedType:
ResolvedType
valuesByMode
valuesByMode:
Record<string,VariableValue>
description
description:
string
hiddenFromPublishing
hiddenFromPublishing:
boolean
scopes
scopes:
VariableScope[]
codeSyntax
codeSyntax:
Record<string,string>
NormalizedVariables
Normalized model from normalizeVariables.
Remarks
Ordered arrays preserve source order. ID-keyed maps support direct lookup.
Properties
collections
collections:
NormalizedCollection[]
variables
variables:
NormalizedVariable[]
collectionsById
collectionsById:
Record<string,NormalizedCollection>
variablesById
variablesById:
Record<string,NormalizedVariable>
ResolvedValue
Result of resolving a variable's value in a specific mode context.
Properties
value
value:
ConcreteValue
The concrete value after following any alias chain.
resolvedType
resolvedType:
ResolvedType
The resolved type from the variable that supplied the concrete value.
aliasChain
aliasChain:
string[]
IDs of the variables traversed to reach the concrete value, starting with the requested variable. Length 1 means the value was not an alias.
Color
RGBA value for a Figma COLOR variable.
Remarks
Each component ranges from 0 through 1.
Example
const color: Color = { r: 0.5, g: 0.8, b: 0.2, a: 1 }Properties
r
r:
number
Red channel, 0–1
g
g:
number
Green channel, 0–1
b
b:
number
Blue channel, 0–1
a
a:
number
Alpha channel, 0–1 (opacity)
VariableAlias
Reference to another Figma variable.
Remarks
The type discriminator has the fixed value VARIABLE_ALIAS.
Example
const alias: VariableAlias = { type: 'VARIABLE_ALIAS', id: 'VariableID:123:456' }Properties
type
type:
"VARIABLE_ALIAS"
Fixed VARIABLE_ALIAS discriminator.
id
id:
string
The referenced variable's Figma variable ID.
FigmaVariable
Figma local variable from the Variables REST API.
Remarks
valuesByMode maps each mode ID to its value. variableCollectionId
identifies the owning collection.
Example
const variable: FigmaVariable = {
id: 'VariableID:123:456',
name: 'Primary Color',
variableCollectionId: 'VariableCollectionId:789:012',
resolvedType: 'COLOR',
valuesByMode: { 'MODE:dark': { r: 0, g: 0, b: 0, a: 1 } },
description: 'Main brand color',
hiddenFromPublishing: false,
scopes: ['ALL_FILLS'],
codeSyntax: { css: 'var(--primary-color)' },
updatedAt: '2024-06-21T23:59:59Z',
}Properties
id
id:
string
Unique Figma variable ID
name
name:
string
Human-readable variable name
variableCollectionId
variableCollectionId:
string
Parent collection ID
resolvedType
resolvedType:
ResolvedType
Data type for this variable (BOOLEAN, FLOAT, STRING, or COLOR)
valuesByMode
valuesByMode:
Record<string,VariableValue>
Map of mode IDs to variable values (by type)
description
description:
string
Optional freeform description
hiddenFromPublishing
hiddenFromPublishing:
boolean
Set to true to hide this variable from publishing
scopes
scopes:
VariableScope[]
Array of allowed or assigned Figma variable scopes
codeSyntax
codeSyntax:
Record<string,string>
Map of language IDs to code sample strings for this variable
updatedAt
updatedAt:
string
ISO8601 timestamp of last update
VariableMode
Mode in a Figma variable collection.
Remarks
A collection maps variable values to its mode IDs.
Example
const mode: VariableMode = { modeId: 'MODE:dark', name: 'Dark' }Properties
modeId
modeId:
string
Unique mode ID
name
name:
string
Human-readable mode name
FigmaCollection
Figma variable collection with its modes and variable IDs.
Remarks
The collection owns the listed variables and supplies their mode IDs.
Example
const collection: FigmaCollection = {
id: 'VariableCollectionId:789:012',
name: 'Theme Colors',
modes: [{ modeId: 'MODE:dark', name: 'Dark' }],
defaultModeId: 'MODE:dark',
variableIds: ['VariableID:123:456'],
hiddenFromPublishing: false,
updatedAt: '2024-06-21T23:59:59Z',
}Properties
id
id:
string
Unique Figma collection ID
name
name:
string
Human-readable collection name
modes
modes:
VariableMode[]
List of VariableMode objects
defaultModeId
defaultModeId:
string
The default mode for this collection
variableIds
variableIds:
string[]
Array of IDs of variables in this collection
hiddenFromPublishing
hiddenFromPublishing:
boolean
Set to true to hide this collection from publishing
updatedAt
updatedAt:
string
ISO8601 timestamp of last update
LocalVariablesResponse
Response from the Figma local variables endpoint.
Remarks
meta contains ID-keyed local collections and variables for one file.
Example
import type { LocalVariablesResponse } from '@primitree/core';
function handleResponse(response: LocalVariablesResponse) {
const collections = Object.values(response.meta.variableCollections);
const variables = Object.values(response.meta.variables);
}Properties
meta
meta:
object
Metadata object containing collections and variables.
variableCollections
variableCollections:
Record<string,FigmaCollection>
Map of collection IDs to FigmaCollection objects.
variables
variables:
Record<string,FigmaVariable>
Map of variable IDs to FigmaVariable objects.
PublishedVariable
Published Figma variable from the Variables REST API.
Properties
id
id:
string
subscribed_id
subscribed_id:
string
name
name:
string
key
key:
string
variableCollectionId
variableCollectionId:
string
resolvedType
resolvedType:
ResolvedType
updatedAt
updatedAt:
string
PublishedVariableCollection
Published Figma variable collection from the Variables REST API.
Properties
id
id:
string
subscribed_id
subscribed_id:
string
name
name:
string
key
key:
string
updatedAt
updatedAt:
string
PublishedVariablesResponse
Response from the Figma published variables endpoint.
Properties
meta
meta:
object
variableCollections
variableCollections:
Record<string,PublishedVariableCollection>
variables
variables:
Record<string,PublishedVariable>
FigmaError
Figma REST API error data.
Remarks
The response contains an HTTP status code and message.
Example
import type { FigmaError } from '@primitree/core';
function handleError(error: FigmaError) {
console.error(error.statusCode, error.message);
}Properties
statusCode
statusCode:
number
HTTP status code from the Figma API.
message
message:
string
Human-readable error message describing the failure.
CreateVariablePayload
Fields for creating a Figma variable.
Remarks
Figma requires name, variableCollectionId, and resolvedType.
Example
import type { CreateVariablePayload } from '@primitree/core';
const newVariable: CreateVariablePayload = {
name: 'Primary Color',
variableCollectionId: 'VariableCollectionId:123:456',
resolvedType: 'COLOR',
description: 'Main brand color',
hiddenFromPublishing: false,
scopes: ['ALL_FILLS'],
codeSyntax: { css: 'var(--primary-color)' },
}Properties
name
name:
string
The human-readable name of the variable.
variableCollectionId
variableCollectionId:
string
The ID of the collection this variable belongs to.
resolvedType
resolvedType:
ResolvedType
The data type of the variable value (e.g., 'COLOR', 'FLOAT').
description?
optionaldescription?:string
Optional description text for documentation or tooling.
hiddenFromPublishing?
optionalhiddenFromPublishing?:boolean
Optional flag to hide the variable from published styles.
scopes?
optionalscopes?:VariableScope[]
Optional scopes that restrict use of the variable.
codeSyntax?
optionalcodeSyntax?:Record<string,string>
Optional mapping of language identifiers to code snippets for this variable.
UpdateVariablePayload
Fields that a Figma variable update can change.
Remarks
The API accepts partial updates.
Example
import type { UpdateVariablePayload } from '@primitree/core';
const updatePayload: UpdateVariablePayload = {
name: 'Updated Color Name',
description: 'Updated description',
}Properties
name?
optionalname?:string
New name for the variable.
description?
optionaldescription?:string
New description text.
hiddenFromPublishing?
optionalhiddenFromPublishing?:boolean
Update publishing visibility.
scopes?
optionalscopes?:VariableScope[]
Update scopes.
codeSyntax?
optionalcodeSyntax?:Record<string,string>
Update code syntax mapping.
VariableModeValue
Value assignment for one variable and mode.
Remarks
A null value requires modeId to identify an extended-mode override.
modeId accepts an extended-mode ID or a mapped inherited-mode temporary
ID. Figma rejects root-mode null assignments upstream.
Example
import type { VariableModeValue } from '@primitree/core';
const modeValue: VariableModeValue = {
variableId: 'VariableID:123:456',
modeId: 'MODE:dark',
value: { r: 0, g: 0, b: 0, a: 1 },
};Properties
variableId
variableId:
string
ID of the Figma variable that receives the value.
modeId
modeId:
string
The mode ID (e.g., 'MODE:dark') this value applies to.
value
value:
VariableMutationValue
The variable value, including RGB/RGBA colors, aliases, or null to remove an extended-mode override.
BulkUpdatePayload
Bulk mutation payload for collections, modes, variables, and values.
Remarks
Figma processes the included changes in one request.
Example
import type { BulkUpdatePayload } from '@primitree/core';
const payload: BulkUpdatePayload = {
variableCollections: [{ action: 'UPDATE', id: 'VariableCollectionId:123', name: 'New Name' }],
variableModes: [{ action: 'CREATE', name: 'Light', variableCollectionId: 'VariableCollectionId:123' }],
variables: [{ action: 'DELETE', id: 'VariableID:456' }],
variableModeValues: [{ variableId: 'VariableID:789', modeId: 'MODE:dark', value: true }],
}Properties
variableCollections?
optionalvariableCollections?:VariableCollectionChange[]
Optional array of collection changes.
variableModes?
optionalvariableModes?:VariableModeChange[]
Optional array of mode changes.
variables?
optionalvariables?:VariableChange[]
Optional array of variable changes.
variableModeValues?
optionalvariableModeValues?:VariableModeValue[]
Optional array of variable-mode value assignments.
BulkUpdateResponse
Response from a Figma Variables bulk mutation.
Remarks
meta.tempIdToRealId maps client IDs to the IDs Figma created.
Example
import type { BulkUpdateResponse } from '@primitree/core';
function handleResponse(response: BulkUpdateResponse) {
if (response.error) {
console.error('Update failed:', response.message);
} else {
console.log('Update succeeded, IDs:', response.meta?.tempIdToRealId);
}
}Properties
error
error:
boolean
True for an error response.
status
status:
number
HTTP status code from the API response.
message?
optionalmessage?:string
Optional human-readable error or status message.
meta?
optionalmeta?:object
Optional metadata including temporary-to-real ID mapping.
tempIdToRealId
tempIdToRealId:
Record<string,string>
MutationState
Mutation hook state.
Remarks
The status, data, and error fields describe the latest mutation.
Type Parameters
TData
TData
Mutation result type.
Properties
status
status:
"idle"|"loading"|"success"|"error"
data
data:
TData|null
error
error:
Error|null
MutationOptions
Options for configuring mutation behavior.
Properties
throwOnError?
optionalthrowOnError?:boolean
Selects mutation error handling.
-
false(default): The hook stores errors in theerrorstate.mutatereturnsundefinedon error. Read theisErrorflag anderrorstate to handle the failure. -
true: The hook rethrows errors fortry/catch. Themutatefunction throws on error.
Default
falseMutationResult
Return value of mutation hooks.
Remarks
Mutation state and the function that starts a mutation.
Return Value Semantics
The mutate function returns Promise<TData | undefined>:
- On success: Returns the mutation result data (
TData) - On error with
throwOnError: false(default): Returnsundefinedand stores error inerrorstate - On error with
throwOnError: true: Throws the error (use try/catch)
Examples
// Check the return value when throwOnError is false.
const result = await mutate(payload);
if (result === undefined) {
// Check error state
console.error('Mutation failed:', error);
} else {
// Use result
console.log('Created:', result);
}
// Use try/catch when throwOnError is true.
try {
const result = await mutate(payload);
console.log('Created:', result);
} catch (err) {
console.error('Mutation failed:', err);
}
// Read status flags while rendering.
if (isSuccess) {
console.log('Created:', data);
}
if (isError) {
console.error('Failed:', error);
}Type Parameters
TData
TData
Mutation result type.
TPayload
TPayload
Mutation payload type.
Properties
mutate
mutate: (
payload) =>Promise<TData|undefined>
Trigger the mutation with the given payload.
Parameters
payload
TPayload
Returns
Promise<TData | undefined>
The mutation result. With throwOnError: false, the function
returns undefined after an error. With throwOnError: true, it throws.
status
status:
"idle"|"loading"|"success"|"error"
Current mutation status: 'idle' | 'loading' | 'success' | 'error'
data
data:
TData|null
Latest successful mutation result. Null before a successful mutation.
error
error:
Error|null
Latest mutation error. Null before a failure.
isLoading
isLoading:
boolean
true while the mutation is in progress.
isSuccess
isSuccess:
boolean
true after a successful mutation.
isError
isError:
boolean
true after a failed mutation.
FilterVariablesCriteria
Criteria for filtering Figma variables.
Properties
resolvedType?
optionalresolvedType?:ResolvedType
Filter by resolved variable type (e.g., 'COLOR', 'FLOAT', 'STRING', 'BOOLEAN').
name?
optionalname?:string
Substring to match against variable names.
caseInsensitive?
optionalcaseInsensitive?:boolean
Set to true for case-insensitive name matching.
Default Value
falseRedactTokenOptions
Options for masking part of a Figma token.
Remarks
Properties
visibleStart?
optionalvisibleStart?:number
Number of characters to show at the start of the token.
Default Value
5visibleEnd?
optionalvisibleEnd?:number
Number of characters to show at the end of the token.
Default Value
3emptyPlaceholder?
optionalemptyPlaceholder?:string
Placeholder text for null/undefined tokens.
Default Value
'[no token]'RetryOptions
Options for configuring retry behavior.
Properties
maxRetries?
optionalmaxRetries?:number
Maximum number of retry attempts.
Default Value
3initialDelayMs?
optionalinitialDelayMs?:number
Initial delay in milliseconds before the first retry.
Default Value
1000backoffMultiplier?
optionalbackoffMultiplier?:number
Multiplier for exponential backoff between retries.
Default Value
2maxDelayMs?
optionalmaxDelayMs?:number
Maximum delay in milliseconds between retries.
Default Value
30000retryOnlyRateLimits?
optionalretryOnlyRateLimits?:boolean
Set to true to retry rate limit errors (429) and reject other errors.
Set to false to retry any error.
Default Value
trueonRetry?
optionalonRetry?: (attempt,delayMs,error) =>void
Function that runs before each retry attempt. Use it for logging or UI state updates.
Parameters
attempt
number
delayMs
number
error
Error
Returns
void
Type Aliases
SourceId
SourceId =
GraphId<"SourceId">
GroupId
GroupId =
GraphId<"GroupId">
TokenId
TokenId =
GraphId<"TokenId">
GraphViewId
GraphViewId =
GraphId<"GraphViewId">
QualifiedIdKind
QualifiedIdKind =
"group"|"token"
QualifiedIdForKind
QualifiedIdForKind<
Kind> =Kindextends"group"?GroupId:TokenId
Type Parameters
Kind
Kind extends QualifiedIdKind
GraphPhase
GraphPhase =
"source"|"compose"|"view"|"resolve"|"inspect"|"diff"
Result
Result<
Value> = {ok:true;value:Value;diagnostics: readonlyGraphDiagnostic[]; } | {ok:false;diagnostics: readonly [GraphDiagnostic,...GraphDiagnostic[]]; }
Type Parameters
Value
Value
JsonPrimitive
JsonPrimitive =
null|boolean|number|string
JsonValue
JsonValue =
JsonPrimitive| readonlyJsonValue[] | {[key:string]:JsonValue; }
StandardTokenType
StandardTokenType =
"border"|"color"|"cubicBezier"|"dimension"|"duration"|"fontFamily"|"fontWeight"|"gradient"|"number"|"shadow"|"string"|"strokeStyle"|"transition"|"typography"
TokenType
TokenType =
StandardTokenType|"boolean"|`extension:${string}`
ContextSelection
ContextSelection =
Readonly<Record<string,string>>
TokenValue
TokenValue = {
kind:"literal";value:JsonValue; } | {kind:"reference";target:TokenId; }
TokenInspectionTarget
TokenInspectionTarget = {
kind:"token-id";tokenId:TokenId; } | {kind:"path";path: readonlystring[]; }
GraphChangeKind
GraphChangeKind =
"added"|"removed"|"changed"
AliasResolutionErrorCode
AliasResolutionErrorCode =
"CYCLE"|"MISSING_TARGET"|"MISSING_VALUE"
Reasons an alias chain can fail to resolve.
ConcreteValue
ConcreteValue =
string|number|boolean|Color
A concrete (non-alias) variable value after alias resolution.
ResolvedType
ResolvedType =
"BOOLEAN"|"FLOAT"|"STRING"|"COLOR"
Figma variable resolved type.
Remarks
Figma returns this value in a variable's resolvedType field.
Example
const type: ResolvedType = 'COLOR'VariableScope
VariableScope =
"ALL_SCOPES"|"TEXT_CONTENT"|"CORNER_RADIUS"|"WIDTH_HEIGHT"|"GAP"|"STROKE_FLOAT"|"OPACITY"|"EFFECT_FLOAT"|"FONT_WEIGHT"|"FONT_SIZE"|"LINE_HEIGHT"|"LETTER_SPACING"|"PARAGRAPH_SPACING"|"PARAGRAPH_INDENT"|"FONT_FAMILY"|"FONT_STYLE"|"FONT_VARIATIONS"|"ALL_FILLS"|"FRAME_FILL"|"SHAPE_FILL"|"TEXT_FILL"|"STROKE_COLOR"|"EFFECT_COLOR"
Figma Variables API scope.
Remarks
A scope controls where Figma offers a variable in the editor.
Example
const scopes: VariableScope[] = ['ALL_FILLS', 'TEXT_CONTENT']VariableValue
VariableValue =
string|boolean|number|Color|VariableAlias
Value for Figma variable payloads and responses.
VariableAction
VariableAction =
"CREATE"|"UPDATE"|"DELETE"
Figma Variables mutation action.
Remarks
Bulk payload entries use this discriminator.
VariableCollectionChange
VariableCollectionChange =
TemporaryId&object&RootCollectionCreate|ExtendedCollectionCreate|ChangeId&object|ChangeId&object
Create, update, or delete operation for a variable collection.
Remarks
Create actions require a name and may provide a temporary ID. Root collections can provide an initial mode ID, while extended collections identify their parent and may map parent mode IDs. Update and delete actions require an existing ID.
Example
import type { VariableCollectionChange } from '@primitree/core';
const change: VariableCollectionChange = {
action: 'CREATE',
name: 'New Collection',
initialModeId: 'MODE:dark',
}VariableModeChange
VariableModeChange =
TemporaryId&object|ChangeId&object|ChangeId&object
Create, update, or delete operation for a variable mode.
Remarks
Create actions require a name and collection ID and may provide a temporary ID. Update and delete actions require an existing mode ID and collection ID.
Example
import type { VariableModeChange } from '@primitree/core';
const modeChange: VariableModeChange = {
action: 'CREATE',
name: 'Light Mode',
variableCollectionId: 'VariableCollectionId:123:456',
}VariableChange
VariableChange =
TemporaryId&object|ChangeId&object&VariableMutableFields|ChangeId&object
Create, update, or delete operation for a Figma variable.
Remarks
Create actions require a name, collection ID, and resolved type and may provide a temporary ID. Update and delete actions require an existing variable ID. Update actions cannot change fields that Figma accepts during creation.
Example
import type { VariableChange } from '@primitree/core';
const varChange: VariableChange = {
action: 'DELETE',
id: 'VariableID:123:456',
}VariableMutationValue
VariableMutationValue =
VariableValue|Omit<Color,"a"> |null
Value for a Figma variable assignment in a mutation request.
Remarks
Figma accepts null to remove an extended-mode override. Its modeId may
be an extended-mode ID or a mapped inherited-mode temporary ID. Figma
rejects null for root-mode values upstream.
FallbackDataKind
FallbackDataKind =
"local"|"published"
Figma Variables response kind for fallback data.
ClassifiedFallbackData
ClassifiedFallbackData = {
kind:"local";data:LocalVariablesResponse; } | {kind:"published";data:PublishedVariablesResponse; }
Fallback data paired with its Variables API response kind.
Variables
FIGMA_API_BASE_URL
constFIGMA_API_BASE_URL:"https://api.figma.com"='https://api.figma.com'
Base URL for the Figma REST API.
FIGMA_FILES_ENDPOINT
constFIGMA_FILES_ENDPOINT:"https://api.figma.com/v1/files"
Base URL for Figma file endpoints.
CONTENT_TYPE_JSON
constCONTENT_TYPE_JSON:"application/json"='application/json'
The HTTP Content-Type header value for JSON requests.
FIGMA_TOKEN_HEADER
constFIGMA_TOKEN_HEADER:"X-FIGMA-TOKEN"='X-FIGMA-TOKEN'
The HTTP header key used to pass the Figma Personal Access Token.
ERROR_MSG_TOKEN_REQUIRED
constERROR_MSG_TOKEN_REQUIRED:"Provide a Figma API token."='Provide a Figma API token.'
Message for requests without a Figma API token.
ERROR_MSG_TOKEN_FILE_KEY_REQUIRED
constERROR_MSG_TOKEN_FILE_KEY_REQUIRED:"Provide a Figma API token and file key."='Provide a Figma API token and file key.'
Message for requests without a Figma API token and file key.
ERROR_MSG_BULK_UPDATE_FAILED
constERROR_MSG_BULK_UPDATE_FAILED:"The bulk update request failed."='The bulk update request failed.'
Message for a failed bulk update request.
ERROR_MSG_CREATE_VARIABLE_FAILED
constERROR_MSG_CREATE_VARIABLE_FAILED:"The create-variable request failed."='The create-variable request failed.'
Message for a failed create-variable request.
ERROR_MSG_DELETE_VARIABLE_FAILED
constERROR_MSG_DELETE_VARIABLE_FAILED:"The delete-variable request failed."='The delete-variable request failed.'
Message for a failed delete-variable request.
ERROR_MSG_UPDATE_VARIABLE_FAILED
constERROR_MSG_UPDATE_VARIABLE_FAILED:"The update-variable request failed."='The update-variable request failed.'
Message for a failed update-variable request.
ERROR_MSG_FETCH_FIGMA_DATA_FAILED
constERROR_MSG_FETCH_FIGMA_DATA_FAILED:"The Figma API request failed."='The Figma API request failed.'
Message for a failed Figma API request.
Functions
fetcher()
fetcher<
TResponse>(url,token,options?):Promise<TResponse>
Send an authenticated GET request to the Figma REST API.
Type Parameters
TResponse
TResponse = unknown
Parameters
url
string
Absolute Figma URL or path relative to baseUrl.
token
string
Figma Personal Access Token.
options?
Request signal, timeout, fetch implementation, and base URL.
Returns
Promise<TResponse>
Parsed JSON response.
Remarks
The function parses JSON responses. It throws FigmaApiError for an
unsuccessful response and preserves Retry-After for HTTP 429 responses.
Throws
Error for an empty token.
Throws
FigmaApiError for a non-2xx response from Figma.
Throws
AbortError when the caller aborts the signal or the timeout expires.
Example
import { fetcher } from '@primitree/core';
async function loadVariables(fileKey: string, token: string) {
const url = `https://api.figma.com/v1/files/${fileKey}/variables`;
const data = await fetcher(url, token);
return data;
}
// With timeout:
const data = await fetcher(url, token, { timeout: 5000 });
// With abort signal:
const controller = new AbortController();
const data = await fetcher(url, token, { signal: controller.signal });
controller.abort(); // Cancel the requestmutator()
mutator<
TResponse>(url,token,_action,body?,options?):Promise<TResponse>
Send an authenticated POST request to the Figma Variables REST API.
Type Parameters
TResponse
TResponse = unknown
Parsed response type.
Parameters
url
string
Absolute Figma URL or path relative to baseUrl.
token
string
Figma Personal Access Token.
_action
Compatibility parameter. Request entries select the action.
body?
Record<string, unknown> | BulkUpdatePayload | { variables?: Record<string, unknown>[]; }
Mutation request body.
options?
Request signal, timeout, fetch implementation, and base URL.
Returns
Promise<TResponse>
Parsed JSON response, or an empty object for HTTP 204.
Remarks
Entry-level action fields select create, update, and delete operations.
The function serializes the body and parses JSON responses. It returns an
empty object for HTTP 204.
Throws
Error for an empty token.
Throws
FigmaApiError for a non-2xx response from Figma.
Throws
AbortError when the caller aborts the signal or the timeout expires.
Example
import { mutator } from '@primitree/core';
async function updateVariable(fileKey: string, token: string, variableId: string) {
const url = `https://api.figma.com/v1/files/${fileKey}/variables`;
const payload = { variables: [{ action: 'UPDATE', id: variableId, name: 'Updated Name' }] };
const result = await mutator(url, token, 'UPDATE', payload);
return result;
}
// With timeout:
const result = await mutator(url, token, 'UPDATE', payload, { timeout: 5000 });FIGMA_PUBLISHED_VARIABLES_PATH()
FIGMA_PUBLISHED_VARIABLES_PATH(
fileKey):string
Build the published variables path for a Figma file.
Parameters
fileKey
string
Returns
string
FIGMA_FILE_VARIABLES_PATH()
FIGMA_FILE_VARIABLES_PATH(
fileKey):string
Build the variables mutation path for a Figma file.
Parameters
fileKey
string
Returns
string
FIGMA_LOCAL_VARIABLES_ENDPOINT()
FIGMA_LOCAL_VARIABLES_ENDPOINT(
fileKey):string
Build the local variables URL for a Figma file.
Parameters
fileKey
string
Figma file key.
Returns
string
Local variables endpoint URL.
Example
const url = FIGMA_LOCAL_VARIABLES_ENDPOINT('your-file-key')diffVariables()
diffVariables(
oldInput,newInput):VariablesDiff
Compute the semantic diff between two Figma variables exports.
Parameters
oldInput
unknown
The earlier export (e.g. the committed backup).
newInput
unknown
The newer export.
Returns
Remarks
Accepts the same input shapes as normalizeVariables. It matches
records across exports by Figma variable, collection, and mode ID. Renamed
records appear as renames.
Example
const diff = diffVariables(previousJson, currentJson)
if (diff.breaking) {
console.error(formatDiffMarkdown(diff))
process.exit(1)
}formatValue()
formatValue(
value):string
Human-readable rendering of a Figma variable value for diff output.
Parameters
value
VariableValue | undefined
Returns
string
formatDiffMarkdown()
formatDiffMarkdown(
diff):string
Render a VariablesDiff as a Markdown report.
Parameters
diff
Returns
string
createSourceId()
Parameters
value
string
Returns
qualifyId()
qualifyId<
Kind>(input):Result<QualifiedIdForKind<Kind>>
Type Parameters
Kind
Kind extends QualifiedIdKind
Parameters
input
sourceId
kind
Kind
localId
string
Returns
Result<QualifiedIdForKind<Kind>>
createGraphFragment()
createGraphFragment(
input):Result<GraphFragment>
Parameters
input
unknown
Returns
composeGraph()
composeGraph(
fragments):Result<TokenGraph>
Parameters
fragments
readonly GraphFragment[]
Returns
createSourceView()
Parameters
graph
options
id
string
Returns
getReferences()
getReferences(
graph,tokenId):Result<readonlyReferenceEdge[]>
Parameters
graph
tokenId
Returns
Result<readonly ReferenceEdge[]>
getDependencies()
getDependencies(
graph,tokenId,options?):Result<readonlyTokenId[]>
Parameters
graph
tokenId
options?
Returns
getDependents()
getDependents(
graph,tokenId,options?):Result<readonlyTokenId[]>
Parameters
graph
tokenId
options?
Returns
resolveToken()
resolveToken(
graph,view,tokenId,selection?):Result<ResolvedToken>
Parameters
graph
view
tokenId
selection?
Readonly<Record<string, string>>
Returns
resolveView()
resolveView(
graph,view,selection?):Result<readonlyResolvedToken[]>
Parameters
graph
view
selection?
Readonly<Record<string, string>>
Returns
Result<readonly ResolvedToken[]>
inspectToken()
inspectToken(
snapshot,target,selection?):Result<TokenInspection>
Parameters
snapshot
target
selection?
Readonly<Record<string, string>>
Returns
diffGraphViews()
Parameters
before
after
Returns
normalizeVariables()
normalizeVariables(
input):NormalizedVariables&object
Normalize a supported Figma variables JSON shape.
Parameters
input
unknown
A Figma variables document (object or JSON string).
Returns
NormalizedVariables & object
The normalized collections and variables, plus any warnings.
Remarks
Accepts the REST local variables response (the output of
primitree export and Dev Mode plugin exports), bare meta
objects, and plugin-style { variables, collections } documents,
as parsed objects or raw JSON strings.
The function drops variables that reference a missing collection and adds
a warning. It rebuilds each collection's variableIds from the variables
that pass validation.
Throws
VariablesParseError for an unsupported input shape.
Example
import { normalizeVariables } from '@primitree/core'
import { readFileSync } from 'node:fs'
const normalized = normalizeVariables(readFileSync('variables.json', 'utf8'))
console.log(normalized.collections.map(c => c.name))toLocalVariablesResponse()
toLocalVariablesResponse(
normalized):object
Convert a normalized model back into the REST LocalVariablesResponse
shape used across the Primitree packages.
Parameters
normalized
Returns
object
meta
meta:
object
meta.variableCollections
variableCollections:
Record<string,FigmaCollection>
meta.variables
variables:
Record<string,FigmaVariable>
isVariableAlias()
isVariableAlias(
value):value is VariableAlias
Type guard for Figma variable alias values.
Parameters
value
unknown
Returns
value is VariableAlias
resolveVariableValue()
resolveVariableValue(
normalized,variableId,modeId?):ResolvedValue
Resolve a variable's value in a given mode by following alias chains across collections.
Parameters
normalized
The normalized variables model.
variableId
string
ID of the variable to resolve.
modeId?
string
Mode ID to resolve against (defaults to the variable's collection default mode).
Returns
The concrete value, the type that supplied it, and the alias chain walked.
Remarks
Mode selection mirrors Figma's behavior for static resolution:
- The resolver uses the requested
modeIdfor a matching variable value. For a requested mode with no value, the resolver selects the collection's default mode. - For aliases in another collection, the resolver checks the requested
modeIdin that collection. Mode IDs are unique per collection, so this check matches within the same collection. For a target collection without that mode ID, the resolver selects the target collection's default mode.
Cycles and dangling alias targets throw AliasResolutionError.
Example
const { value, aliasChain } = resolveVariableValue(normalized, 'VariableID:1:23', '1:0')resolveAllVariableValues()
resolveAllVariableValues(
normalized):object
Resolve each variable for the modes in its collection.
Parameters
normalized
Returns
object
Map of variable ID to mode ID to resolved value. The function
catches alias failures and collects them in errors.
values
values:
Record<string,Record<string,ResolvedValue>>
errors
errors:
AliasResolutionError[]
isFigmaApiError()
isFigmaApiError(
error):error is FigmaApiError
Check whether a value is a FigmaApiError.
Parameters
error
unknown
The error to check.
Returns
error is FigmaApiError
true for FigmaApiError values; false for other values.
Example
import { isFigmaApiError } from '@primitree/core';
try {
await mutate(payload);
} catch (error) {
if (isFigmaApiError(error)) {
if (error.statusCode === 401) {
// Handle authentication error
} else if (error.statusCode === 429) {
// Handle rate limit
}
}
}getErrorStatus()
getErrorStatus(
error):number|null
Return the HTTP status from a FigmaApiError.
Parameters
error
unknown
The error to extract status code from.
Returns
number | null
The HTTP status code. getErrorStatus returns null for other values.
Example
import { getErrorStatus } from '@primitree/core';
const status = getErrorStatus(error);
if (status === 401) {
// Handle unauthorized
}getErrorMessage()
getErrorMessage(
error,defaultMessage?):string
Return an error message or the supplied fallback.
Parameters
error
unknown
The error to extract message from.
defaultMessage?
string = 'No error message available'
Fallback for values without an error message. Default: "No error message available".
Returns
string
The error message string.
Example
import { getErrorMessage } from '@primitree/core';
const message = getErrorMessage(error);
toast.error(message);hasErrorStatus()
hasErrorStatus(
error,statusCode):boolean
Check whether an error has an HTTP status code.
Parameters
error
unknown
The error to check.
statusCode
number
The HTTP status code to check for.
Returns
boolean
true for the specified status code; false for other values.
Example
import { hasErrorStatus } from '@primitree/core';
if (hasErrorStatus(error, 401)) {
// Handle unauthorized
}isRateLimited()
isRateLimited(
error):boolean
Check whether an error is a Figma HTTP 429 response.
Parameters
error
unknown
The error to check.
Returns
boolean
true for HTTP 429 errors; false for other values.
Example
import { isRateLimited } from '@primitree/core';
if (isRateLimited(error)) {
// Retry after the rate-limit delay
}getRetryAfter()
getRetryAfter(
error):number|null
Return the Retry-After value from a Figma HTTP 429 error.
Parameters
error
unknown
The error to extract retry-after from.
Returns
number | null
The retry delay in seconds. getRetryAfter returns null for other errors.
Example
import { getRetryAfter } from '@primitree/core';
const retryAfter = getRetryAfter(error);
if (retryAfter !== null) {
setTimeout(() => {
// Retry the request
}, retryAfter * 1000);
}filterVariables()
filterVariables(
variables,criteria):FigmaVariable[]
Filter Figma variables by resolved type and name substring.
Parameters
variables
Variables to filter.
criteria
Type and name filters.
Returns
Variables that match the supplied filters.
Remarks
Name matching respects case unless caseInsensitive is true.
Example
import { filterVariables } from '@primitree/core'
const colors = filterVariables(variables, { resolvedType: 'COLOR' })
const brand = filterVariables(variables, {
name: 'brand',
caseInsensitive: true,
})redactToken()
redactToken(
token,options?):string
Mask the middle of a Figma token for display.
Parameters
token
string | null | undefined
Token to mask.
options?
Visible character counts and empty placeholder.
Returns
string
Masked token or the configured placeholder.
Remarks
Masked output contains visible token characters. Keep it out of logs, analytics, and error reports.
Example
import { redactToken } from '@primitree/core'
redactToken('figd_abc123xyz789def456')
// 'figd_***...***456'withRetry()
withRetry<
T>(fn,options?): () =>Promise<T>
Wrap an async function with retry and exponential backoff.
Type Parameters
T
T
Parameters
fn
() => Promise<T>
The async function to wrap with retry logic
options?
Configuration for retry behavior
Returns
Wrapped function with retry behavior
() => Promise<T>
Remarks
withRetry retries Figma HTTP 429 errors by default. A Retry-After
response value replaces the backoff delay.
Example
import { withRetry, fetcher } from '@primitree/core';
const fetchWithRetry = withRetry(
() => fetcher(url, token),
{ maxRetries: 3, onRetry: (attempt, delay) => console.log(`Retry ${attempt} in ${delay}ms`) }
);
const data = await fetchWithRetry();isLocalVariablesResponse()
isLocalVariablesResponse(
data):data is LocalVariablesResponse
Check the fields that distinguish a local variables response.
Parameters
data
unknown
The data to validate
Returns
data is LocalVariablesResponse
true for LocalVariablesResponse data
Remarks
The guard checks meta.variableCollections, meta.variables, collection
modes, and variable values.
Example
import { isLocalVariablesResponse } from '@primitree/core';
if (isLocalVariablesResponse(fallbackData)) {
console.log(fallbackData.meta.variables)
} else {
console.error('Invalid fallback file structure');
}isPublishedVariablesResponse()
isPublishedVariablesResponse(
data):data is PublishedVariablesResponse
Check the fields that distinguish a published variables response.
Parameters
data
unknown
The data to validate
Returns
data is PublishedVariablesResponse
true for PublishedVariablesResponse data
Remarks
The guard checks the published entry keys that the local response omits.
Example
import { isPublishedVariablesResponse } from '@primitree/core';
if (isPublishedVariablesResponse(fallbackData)) {
console.log(fallbackData.meta.variables)
} else {
console.error('Invalid fallback file structure');
}classifyFallbackData()
classifyFallbackData(
data,explicitKind?):ClassifiedFallbackData|undefined
Classify fallback data as a local or published response.
Parameters
data
unknown
The data to validate and classify
explicitKind?
Kind used to resolve an empty response.
Returns
ClassifiedFallbackData | undefined
Classified data, or undefined for invalid or ambiguous data.
Remarks
Empty response maps match both response shapes, so callers must provide a kind. The classifier rejects invalid runtime discriminator values.
validateFallbackData()
validateFallbackData(
data):LocalVariablesResponse|PublishedVariablesResponse|undefined
Return local or published fallback data after a structural check.
Parameters
data
unknown
The data to validate
Returns
LocalVariablesResponse | PublishedVariablesResponse | undefined
The validated data or undefined
Remarks
Empty response maps match both shapes, so this function returns undefined
for an empty response without an explicit kind.