Merge pull request #2112 from heygen-com/vi/figma-scopes-retry

fix(figma): auth/retry/batch hardening, mapper fidelity, skill routing, setup docs
This commit is contained in:
Vance Ingalls
2026-07-09 19:56:52 -07:00
committed by GitHub
19 changed files with 782 additions and 137 deletions
+179 -2
View File
@@ -106,14 +106,18 @@ describe("variables", () => {
});
describe("error mapping", () => {
it("maps 429 to RATE_LIMITED and 401 to BAD_TOKEN", async () => {
it("maps 429 to RATE_LIMITED (after retries) and 401 to BAD_TOKEN", async () => {
const stub = fetchStub(() => jsonResponse(429, {}));
const c429 = createFigmaClient({
token: "t",
fetch: fetchStub(() => jsonResponse(429, {})).fetch,
fetch: stub.fetch,
sleep: () => Promise.resolve(),
});
await expect(c429.styles("F")).rejects.toThrowError(
expect.objectContaining({ code: "RATE_LIMITED" }),
);
// 1 initial + 3 retries = 4 attempts
expect(stub.calls).toHaveLength(4);
const c401 = createFigmaClient({
token: "t",
fetch: fetchStub(() => jsonResponse(401, {})).fetch,
@@ -123,6 +127,179 @@ describe("error mapping", () => {
);
});
it("retries 429 and succeeds when the limit clears", async () => {
let n = 0;
const waits: number[] = [];
const client = createFigmaClient({
token: "t",
fetch: (() => {
n += 1;
return Promise.resolve(
n < 3
? jsonResponse(429, {})
: jsonResponse(200, {
meta: { styles: [{ key: "k", name: "P", style_type: "FILL" }] },
}),
);
}) as FigmaFetch,
sleep: (ms) => {
waits.push(ms);
return Promise.resolve();
},
});
const styles = await client.styles("F");
expect(styles[0]?.key).toBe("k");
expect(n).toBe(3); // two 429s then success
expect(waits).toEqual([1000, 2000]); // exponential backoff
});
it("caps an oversized Retry-After at 60s so the CLI can't block for an hour", async () => {
let n = 0;
const waits: number[] = [];
const client = createFigmaClient({
token: "t",
fetch: (() => {
n += 1;
return Promise.resolve(
n === 1
? new Response("{}", { status: 429, headers: { "retry-after": "3600" } })
: jsonResponse(200, { meta: { styles: [] } }),
);
}) as FigmaFetch,
sleep: (ms) => {
waits.push(ms);
return Promise.resolve();
},
});
await client.styles("F");
expect(waits).toEqual([60_000]); // 3600s clamped, not 3_600_000
});
it("retries 429 on non-styles endpoints too (retry lives in the shared get)", async () => {
let n = 0;
const client = createFigmaClient({
token: "t",
fetch: (() => {
n += 1;
return Promise.resolve(
n < 2
? jsonResponse(429, {})
: jsonResponse(200, { images: { "1:2": "https://cdn/a.png" } }),
);
}) as FigmaFetch,
sleep: () => Promise.resolve(),
});
const out = await client.renderNodes("F", ["1:2"], { format: "png" });
expect(out[0]?.url).toBe("https://cdn/a.png");
expect(n).toBe(2); // one 429 then success
});
it("honors Retry-After (seconds) over the backoff default", async () => {
let n = 0;
const waits: number[] = [];
const client = createFigmaClient({
token: "t",
fetch: (() => {
n += 1;
return Promise.resolve(
n === 1
? new Response("{}", { status: 429, headers: { "retry-after": "5" } })
: jsonResponse(200, { meta: { styles: [] } }),
);
}) as FigmaFetch,
sleep: (ms) => {
waits.push(ms);
return Promise.resolve();
},
});
await client.styles("F");
expect(waits).toEqual([5000]);
});
it("names the endpoint scope in the styles 403 when the body is silent", async () => {
const client = createFigmaClient({
token: "t",
fetch: fetchStub(() => jsonResponse(403, { message: "no" })).fetch,
});
await expect(client.styles("F")).rejects.toThrowError(
expect.objectContaining({
code: "FORBIDDEN",
message: expect.stringContaining("library_content:read"),
}),
);
});
it("surfaces figma's own scope diagnosis verbatim from the 403 body (err field)", async () => {
const client = createFigmaClient({
token: "t",
fetch: fetchStub(() =>
jsonResponse(403, {
err: "Invalid scope(s): file_content:read, file_metadata:read. This endpoint requires the library_content:read scope",
}),
).fetch,
});
await expect(client.styles("F")).rejects.toThrowError(
expect.objectContaining({
code: "FORBIDDEN",
message: expect.stringContaining("requires the library_content:read scope"),
}),
);
});
it("reclassifies a 403 'Invalid token' body as BAD_TOKEN, not a scope problem", async () => {
// figma returns 403 (not 401) for bad PATs on file endpoints — verified live
const client = createFigmaClient({
token: "t",
fetch: fetchStub(() => jsonResponse(403, { err: "Invalid token" })).fetch,
});
const err = await client.styles("F").catch((e: unknown) => e);
expect(err).toBeInstanceOf(FigmaClientError);
if (err instanceof FigmaClientError) {
expect(err.code).toBe("BAD_TOKEN");
expect(err.message).toContain("Re-mint");
}
});
it("keeps REQUIRES_ENTERPRISE for a scopeless variables 403", async () => {
const client = createFigmaClient({
token: "t",
fetch: fetchStub(() => jsonResponse(403, { message: "no" })).fetch,
});
await expect(client.variables("F")).rejects.toThrowError(
expect.objectContaining({ code: "REQUIRES_ENTERPRISE" }),
);
});
});
describe("renderNodes (batch)", () => {
it("fetches many nodes in ONE /v1/images call and maps each url", async () => {
const stub = fetchStub(() =>
jsonResponse(200, {
images: { "1:2": "https://cdn/a.png", "3:4": "https://cdn/b.png" },
}),
);
const client = createFigmaClient({ token: "t", fetch: stub.fetch });
const out = await client.renderNodes("F", ["1:2", "3:4"], { format: "png" });
expect(stub.calls).toHaveLength(1);
expect(stub.calls[0]).toContain("ids=1%3A2%2C3%3A4"); // "1:2,3:4" url-encoded
expect(out).toEqual([
{ nodeId: "1:2", url: "https://cdn/a.png", ext: "png" },
{ nodeId: "3:4", url: "https://cdn/b.png", ext: "png" },
]);
});
it("returns url:null for a node figma couldn't render, without failing the batch", async () => {
const client = createFigmaClient({
token: "t",
fetch: fetchStub(() =>
jsonResponse(200, { images: { "1:2": "https://cdn/a.png", "3:4": null } }),
).fetch,
});
const out = await client.renderNodes("F", ["1:2", "3:4"], { format: "svg" });
expect(out[0]?.url).toBe("https://cdn/a.png");
expect(out[1]?.url).toBeNull();
});
it("wraps other failures as HTTP_ERROR with status", async () => {
const client = createFigmaClient({
token: "t",
+178 -35
View File
@@ -76,8 +76,24 @@ export interface FigmaFileVersion {
lastModified: string;
}
/** One batch render result — url is null when figma couldn't render that
* node (a bad node id in the batch shouldn't fail the whole call). */
export interface BatchRenderedNode {
nodeId: string;
url: string | null;
ext: FigmaAssetFormat;
}
export interface FigmaClient {
renderNode(ref: FigmaRef, opts: RenderNodeOptions): Promise<RenderedNode>;
/** Batch render many nodes of ONE file in a single /v1/images call — the
* documented rate-limit workaround (comma-separated ids). Per-node
* failures come back as url:null rather than throwing the batch. */
renderNodes(
fileKey: string,
nodeIds: string[],
opts: RenderNodeOptions,
): Promise<BatchRenderedNode[]>;
imageFills(fileKey: string): Promise<Map<string, string>>;
variables(fileKey: string): Promise<FigmaVariablesResult>;
styles(fileKey: string): Promise<FigmaStyleMeta[]>;
@@ -89,6 +105,63 @@ export interface FigmaClientOptions {
token: string;
fetch?: FigmaFetch;
baseUrl?: string;
/** Injectable delay for 429 backoff — tests pass a no-op so retries don't
* actually wait. Defaults to a real timer. */
sleep?: (ms: number) => Promise<void>;
/** Max 429 retries before giving up. Default 3. */
maxRetries?: number;
}
/** Read scope each endpoint needs, named exactly as figma's PAT settings UI
* lists them — so a 403 tells the user which checkbox to tick, not just
* "some read scope". The styles endpoint's `library_content:read` is the one
* the setup docs used to omit (it 403s even with file content + metadata). */
const SCOPE_HINTS = {
fileContent: "File content: Read-only",
fileMetadata: "File metadata: Read-only",
libraryContent: "Library content: Read-only (library_content:read)",
} as const;
/** Longest we'll auto-wait on a single Retry-After before giving up — past a
* minute the user is better off cancelling and reducing batch size (the
* RATE_LIMITED message says so) than watching the CLI block silently. */
const MAX_RETRY_WAIT_MS = 60_000;
/** Parse a Retry-After header (figma sends integer seconds; the HTTP spec
* also allows a date) into ms, capped at MAX_RETRY_WAIT_MS, or null when
* absent/unparseable. The cap keeps a spec-legal `Retry-After: 3600` (tier
* quota exhaustion) from silently blocking the CLI for an hour. */
function retryAfterMs(res: Response): number | null {
const raw = res.headers.get("retry-after");
if (raw === null) return null;
const secs = Number(raw);
if (Number.isFinite(secs)) return Math.min(MAX_RETRY_WAIT_MS, Math.max(0, secs * 1000));
const date = Date.parse(raw);
if (Number.isNaN(date)) return null;
return Math.min(MAX_RETRY_WAIT_MS, Math.max(0, date - Date.now()));
}
/** Figma's error bodies are precise — "Invalid token", or "Invalid scope(s):
* … requires the X scope" — and worth surfacing verbatim instead of a
* generic guess. The message lives under `err` on most endpoints but
* `message` on /variables; read both. Returns null when unparseable. */
async function readFigmaErrorMessage(res: Response): Promise<string | null> {
let text: string;
try {
text = await res.text();
} catch {
return null;
}
try {
const body: unknown = JSON.parse(text);
if (isRecord(body)) {
if (typeof body.err === "string") return body.err;
if (typeof body.message === "string") return body.message;
}
} catch {
// non-JSON body — fall through
}
return text.trim() === "" ? null : text.trim();
}
function requireNodeId(ref: FigmaRef): string {
@@ -125,6 +198,7 @@ export function createFigmaClient(options: FigmaClientOptions): FigmaClient {
" 1. figma.com/settings → Security → Personal access tokens → Generate new token",
" 2. Scopes (read-only is all this integration ever needs — it never writes to figma):",
" File content: Read-only · File metadata: Read-only",
" Library content: Read-only (needed for the `tokens` published-styles fallback)",
" Variables: Read-only (optional — brand variables, requires figma Enterprise;",
" without it `tokens` falls back to published styles)",
' 3. export FIGMA_TOKEN="figd_…" — add it to your shell profile or the project .env',
@@ -135,62 +209,125 @@ export function createFigmaClient(options: FigmaClientOptions): FigmaClient {
}
const doFetch: FigmaFetch = options.fetch ?? ((url, init) => fetch(url, init));
const base = options.baseUrl ?? "https://api.figma.com";
const sleep = options.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));
const maxRetries = options.maxRetries ?? 3;
async function get(path: string, enterpriseGated = false): Promise<unknown> {
const res = await doFetch(`${base}${path}`, {
headers: { "X-Figma-Token": token },
});
interface GetOptions {
/** 403 → REQUIRES_ENTERPRISE (variables) rather than FORBIDDEN. */
enterpriseGated?: boolean;
/** scope named in a FORBIDDEN message so the user knows which to add. */
scopeHint?: string;
}
/** Map a 403 to the right typed error using figma's own response body:
* "Invalid token" is a bad PAT (figma returns 403, NOT 401, for these on
* file endpoints), "Invalid scope(s) … requires X" is a missing scope
* surfaced verbatim. Falls back to the endpoint's scopeHint when the body
* is silent. */
function forbiddenError(body: string | null, opts: GetOptions): FigmaClientError {
// Every branch RETURNS the error (the caller throws once) — no mixed
// throw/return, so a future caller that wraps the result gets consistent
// behavior across all three cases.
if (body && /invalid token/i.test(body))
return new FigmaClientError(
"BAD_TOKEN",
"figma rejected the token (403 Invalid token) — it is invalid, expired, or revoked. Re-mint at figma.com/settings → Security, then update FIGMA_TOKEN.",
403,
);
if (opts.enterpriseGated)
return new FigmaClientError(
"REQUIRES_ENTERPRISE",
"figma variables require an Enterprise plan (403) — fall back to styles",
403,
);
if (body && /scope/i.test(body))
return new FigmaClientError(
"FORBIDDEN",
`figma denied access (403): ${body} — add the named scope at figma.com/settings → Security → Personal access tokens.`,
403,
);
const scopeLine = opts.scopeHint
? `This endpoint needs the "${opts.scopeHint}" scope — add it at figma.com/settings → Security → Personal access tokens.`
: "The token is missing a read scope, or your account can't view this file. Check File content: Read-only + File metadata: Read-only at figma.com/settings → Security.";
return new FigmaClientError(
"FORBIDDEN",
`figma denied access (403). ${scopeLine} Also confirm the file is visible to your account.`,
403,
);
}
/** Throw the typed error for a non-ok response (no-op when res.ok). */
async function throwForStatus(res: Response, path: string, opts: GetOptions): Promise<void> {
if (res.ok) return;
if (res.status === 401)
throw new FigmaClientError(
"BAD_TOKEN",
"figma rejected the token (401) — it is expired or revoked. Re-mint at figma.com/settings → Security, then update FIGMA_TOKEN.",
401,
);
if (res.status === 403 && enterpriseGated)
throw new FigmaClientError(
"REQUIRES_ENTERPRISE",
"figma variables require an Enterprise plan (403) — fall back to styles",
403,
);
if (res.status === 403)
throw new FigmaClientError(
"FORBIDDEN",
"figma denied access (403) — the token is missing a read scope, or your account can't view this file. Check the token has File content: Read-only + File metadata: Read-only (figma.com/settings → Security) and that the file is visible to your account.",
403,
);
if (res.status === 403) throw forbiddenError(await readFigmaErrorMessage(res), opts);
if (res.status === 429)
throw new FigmaClientError(
"RATE_LIMITED",
"figma rate limit hit (429) — back off and retry",
`figma rate limit hit (429) and still limited after ${maxRetries} retries — wait a minute and re-run, or import fewer nodes per call.`,
429,
);
if (!res.ok)
throw new FigmaClientError(
"HTTP_ERROR",
`figma request failed: HTTP ${res.status} ${path}`,
res.status,
);
throw new FigmaClientError(
"HTTP_ERROR",
`figma request failed: HTTP ${res.status} ${path}`,
res.status,
);
}
async function get(path: string, opts: GetOptions = {}): Promise<unknown> {
// Retry 429 with backoff before surfacing RATE_LIMITED — figma's limit is
// per-minute, so a couple of imports in quick succession hit it and a
// short wait clears it. Honor Retry-After when present, else exponential.
let res: Response;
for (let attempt = 0; ; attempt += 1) {
res = await doFetch(`${base}${path}`, { headers: { "X-Figma-Token": token } });
if (res.status !== 429 || attempt >= maxRetries) break;
const wait = retryAfterMs(res) ?? 1000 * 2 ** attempt;
await sleep(wait);
}
await throwForStatus(res, path, opts);
return res.json();
}
return {
async renderNode(ref, opts) {
const nodeId = requireNodeId(ref);
const params = new URLSearchParams({ ids: nodeId, format: opts.format });
if (opts.scale !== undefined) params.set("scale", String(opts.scale));
const body = await get(`/v1/images/${ref.fileKey}?${params}`);
const images = isRecord(body) && isRecord(body.images) ? body.images : {};
const url = images[nodeId];
if (typeof url !== "string" || url === "")
const [result] = await this.renderNodes(ref.fileKey, [nodeId], opts);
if (!result || result.url === null)
throw new FigmaClientError(
"RENDER_FAILED",
`figma could not render node ${nodeId} as ${opts.format}`,
);
return { url, ext: opts.format };
return { url: result.url, ext: opts.format };
},
async renderNodes(fileKey, nodeIds, opts) {
if (nodeIds.length === 0) return [];
// /v1/images accepts comma-separated ids — one call for the whole batch,
// which is figma's own answer to the per-minute rate limit.
const params = new URLSearchParams({ ids: nodeIds.join(","), format: opts.format });
if (opts.scale !== undefined) params.set("scale", String(opts.scale));
const body = await get(`/v1/images/${fileKey}?${params}`, {
scopeHint: SCOPE_HINTS.fileContent,
});
const images = isRecord(body) && isRecord(body.images) ? body.images : {};
return nodeIds.map((nodeId) => {
const url = images[nodeId];
return {
nodeId,
url: typeof url === "string" && url !== "" ? url : null,
ext: opts.format,
};
});
},
async imageFills(fileKey) {
const body = await get(`/v1/files/${fileKey}/images`);
const body = await get(`/v1/files/${fileKey}/images`, { scopeHint: SCOPE_HINTS.fileContent });
const meta = isRecord(body) && isRecord(body.meta) ? body.meta : {};
const images = isRecord(meta.images) ? meta.images : {};
const out = new Map<string, string>();
@@ -201,7 +338,7 @@ export function createFigmaClient(options: FigmaClientOptions): FigmaClient {
},
async variables(fileKey) {
const body = await get(`/v1/files/${fileKey}/variables/local`, true);
const body = await get(`/v1/files/${fileKey}/variables/local`, { enterpriseGated: true });
const meta = isRecord(body) && isRecord(body.meta) ? body.meta : {};
const variables = isRecord(meta.variables) ? meta.variables : {};
const collections = isRecord(meta.variableCollections) ? meta.variableCollections : {};
@@ -214,7 +351,9 @@ export function createFigmaClient(options: FigmaClientOptions): FigmaClient {
},
async styles(fileKey) {
const body = await get(`/v1/files/${fileKey}/styles`);
const body = await get(`/v1/files/${fileKey}/styles`, {
scopeHint: SCOPE_HINTS.libraryContent,
});
const meta = isRecord(body) && isRecord(body.meta) ? body.meta : {};
const styles = Array.isArray(meta.styles) ? meta.styles : [];
return styles.filter(
@@ -229,7 +368,9 @@ export function createFigmaClient(options: FigmaClientOptions): FigmaClient {
async nodeTree(ref) {
const nodeId = requireNodeId(ref);
const params = new URLSearchParams({ ids: nodeId, geometry: "paths" });
const body = await get(`/v1/files/${ref.fileKey}/nodes?${params}`);
const body = await get(`/v1/files/${ref.fileKey}/nodes?${params}`, {
scopeHint: SCOPE_HINTS.fileContent,
});
const nodes = isRecord(body) && isRecord(body.nodes) ? body.nodes : {};
const entry = nodes[nodeId];
const doc = isRecord(entry) ? entry.document : undefined;
@@ -244,7 +385,9 @@ export function createFigmaClient(options: FigmaClientOptions): FigmaClient {
},
async fileVersion(fileKey) {
const body = await get(`/v1/files/${fileKey}?depth=1`);
const body = await get(`/v1/files/${fileKey}?depth=1`, {
scopeHint: SCOPE_HINTS.fileMetadata,
});
const version = isRecord(body) && typeof body.version === "string" ? body.version : "";
const lastModified =
isRecord(body) && typeof body.lastModified === "string" ? body.lastModified : "";
@@ -234,6 +234,47 @@ describe("nodeToHtml", () => {
expect(out.html).toContain("<img");
});
it("routes IMAGE fills to the rasterize list regardless of node.type", () => {
const out = nodeToHtml(
frame([
{
id: "1:8",
name: "Sneaker Photo",
type: "RECTANGLE",
absoluteBoundingBox: BOX(120, 220, 200, 200),
fills: [{ type: "IMAGE", imageRef: "abc123" }],
},
]),
{ resolved: [], unresolved: [] },
);
expect(out.rasterize).toEqual([
{ nodeId: "1:8", name: "Sneaker Photo", slug: "sneaker-photo" },
]);
expect(out.html).toContain('data-figma-rasterize="1:8"');
expect(out.html).toContain("<img");
});
it("does not double-paint a rasterized node's own fill/corner-radius onto its img", () => {
const out = nodeToHtml(
frame([
{
id: "1:9",
name: "Blob",
type: "VECTOR",
absoluteBoundingBox: BOX(120, 220, 64, 64),
fills: [SOLID_BLUE],
cornerRadius: 12,
opacity: 0.5,
},
]),
{ resolved: [], unresolved: [] },
);
expect(out.html).not.toContain("background-color: #0066FF");
expect(out.html).not.toContain("border-radius: 12px");
// opacity is compositing, not shape — still applies on top of the export
expect(out.html).toContain("opacity: 0.5");
});
it("skips invisible nodes and invisible fills (respects visible:false)", () => {
const out = nodeToHtml(
frame([
+44 -19
View File
@@ -7,8 +7,11 @@
* - CSS where CSS is faithful: solid/linear-gradient fills, corner radius,
* opacity, drop shadow, blur, text styles.
* - Everything CSS can't match faithfully (vectors, boolean ops, exotic
* paint) routes to the rasterize list — the caller exports those nodes as
* images (Phase 1) and fills in the placeholder src.
* paint, IMAGE fills) routes to the rasterize list — the caller exports
* those nodes as images (Phase 1) and fills in the placeholder src. A
* rasterized node's own fill/corner-radius CSS is never emitted — the
* exported image already contains it; adding both double-paints (a flat
* color block behind/around the real art).
* - Bindings (§7.1): resolved sites emit var(--slug, literal) so a brand
* refresh propagates; unresolved sites bake the literal and carry a
* data-figma-unresolved flag. Never a dangling var().
@@ -113,6 +116,13 @@ function fillCss(node: FigmaNodeDocument): string | null {
return null;
}
/** IMAGE fills (photos, icons pasted as bitmaps) have no CSS equivalent —
* route to rasterize like vectors, regardless of node.type (a plain
* RECTANGLE/FRAME carries the fill just as often as a dedicated image node). */
function hasImageFill(node: FigmaNodeDocument): boolean {
return firstVisibleFill(node)?.type === "IMAGE";
}
function dropShadowCss(effect: Record<string, unknown>): string | null {
if (!isRecord(effect.offset)) return null;
const color = figmaColorToCss(effect.color);
@@ -234,33 +244,47 @@ function geometryCss(node: FigmaNodeDocument, parentBox: Box, isRoot: boolean):
return styles;
}
function shapeCss(node: FigmaNodeDocument, styles: string[]): void {
/** Corner-radius + clip describe the node's OWN shape — meaningless once
* that shape has already been baked into a rasterized image (see
* decorationCss). Opacity stays separate: it's compositing, still correct
* to apply on top of a raster/vector export. */
function cornerAndClipCss(node: FigmaNodeDocument, styles: string[]): void {
if (node.type === "ELLIPSE") {
styles.push("border-radius: 50%");
} else if (typeof node.cornerRadius === "number" && node.cornerRadius > 0) {
styles.push(`border-radius: ${round(node.cornerRadius)}px`);
}
if (node.clipsContent === true) styles.push("overflow: hidden");
}
function opacityCss(node: FigmaNodeDocument, styles: string[]): void {
if (typeof node.opacity === "number" && node.opacity < 1)
styles.push(`opacity: ${round(node.opacity)}`);
}
function decorationCss(node: FigmaNodeDocument, ctx: RenderContext): string[] {
function decorationCss(node: FigmaNodeDocument, ctx: RenderContext, rasterized: boolean): string[] {
const styles: string[] = [];
// backgroundValue is the binding-aware path (var(--slug, literal)) — TEXT
// color goes through it too, so a token-bound text fill keeps its link.
const bg = backgroundValue(node, ctx);
if (node.type === "TEXT") {
if (bg !== null) styles.push(`color: ${bg}`);
textCss(node, styles);
} else if (bg !== null) {
// background-color (longhand) for solid fills, never the shorthand: GSAP
// backgroundColor tweens can't read a var() through the shorthand (its
// pending-substitution longhands serialize empty), so .from/.to on an
// imported node would settle on transparent instead of the token color.
styles.push(bg.includes("gradient(") ? `background: ${bg}` : `background-color: ${bg}`);
// A rasterized node's fill/shape is already baked into the exported image
// — background-color/border-radius on top of it would double-paint (a
// flat color block behind or around the real art). Opacity and effects
// (shadow/blur) aren't baked by the export, so those still apply.
if (!rasterized) {
// backgroundValue is the binding-aware path (var(--slug, literal)) — TEXT
// color goes through it too, so a token-bound text fill keeps its link.
const bg = backgroundValue(node, ctx);
if (node.type === "TEXT") {
if (bg !== null) styles.push(`color: ${bg}`);
textCss(node, styles);
} else if (bg !== null) {
// background-color (longhand) for solid fills, never the shorthand: GSAP
// backgroundColor tweens can't read a var() through the shorthand (its
// pending-substitution longhands serialize empty), so .from/.to on an
// imported node would settle on transparent instead of the token color.
styles.push(bg.includes("gradient(") ? `background: ${bg}` : `background-color: ${bg}`);
}
cornerAndClipCss(node, styles);
}
shapeCss(node, styles);
opacityCss(node, styles);
effectsCss(node, styles);
return styles;
}
@@ -292,15 +316,16 @@ function renderNodeHtml(
): string {
if (node.visible === false || depth > MAX_DEPTH) return "";
const slug = uniqueSlug(ctx, node.name);
const rasterized = RASTERIZE_TYPES.has(node.type) || hasImageFill(node);
const style = escapeHtml(
[...geometryCss(node, parentBox, isRoot), ...decorationCss(node, ctx)].join("; "),
[...geometryCss(node, parentBox, isRoot), ...decorationCss(node, ctx, rasterized)].join("; "),
);
// data-hf-snippet marks the file as a mountable fragment, not a standalone
// composition — the project linter skips composition-root rules for it.
const snippetAttr = isRoot ? ' data-hf-snippet=""' : "";
const idAttrs = `id="${slug}"${snippetAttr} data-figma-id="${escapeHtml(node.id)}"${unresolvedAttr(node, ctx)}`;
if (RASTERIZE_TYPES.has(node.type)) {
if (rasterized) {
ctx.rasterize.push({ nodeId: node.id, name: node.name, slug });
return `<img ${idAttrs} data-figma-rasterize="${escapeHtml(node.id)}" alt="${escapeHtml(node.name)}" style="${style}" />`;
}