Skip to content

Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.

feat(core): FigmaSource adapter + FigmaApiSource (token via env, no leak)

gruminge9ce229fa5e6
diff --git a/understand-anything-plugin/packages/core/src/figma/__tests__/api-source.test.ts b/understand-anything-plugin/packages/core/src/figma/__tests__/api-source.test.ts
new file mode 100644
index 00000000..46e08655
--- /dev/null
+++ b/understand-anything-plugin/packages/core/src/figma/__tests__/api-source.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect, vi, afterEach } from "vitest";
+import { parseFileKey, FigmaApiSource } from "../source/api-source";
+
+afterEach(() => { vi.restoreAllMocks(); delete process.env.FIGMA_TOKEN; });
+
+describe("parseFileKey", () => {
+ it("extracts key from a /file/ URL", () => {
+ expect(parseFileKey("https://www.figma.com/file/ABC123/My-App")).toBe("ABC123");
+ });
+ it("extracts key from a /design/ URL with query", () => {
+ expect(parseFileKey("https://www.figma.com/design/XYZ789/App?node-id=1-2")).toBe("XYZ789");
+ });
+ it("accepts a bare key", () => {
+ expect(parseFileKey("ABC123")).toBe("ABC123");
+ });
+ it("throws on unparseable input", () => {
+ expect(() => parseFileKey("not a key!!")).toThrow();
+ });
+});
+
+describe("FigmaApiSource", () => {
+ it("throws a friendly error when FIGMA_TOKEN is missing", () => {
+ delete process.env.FIGMA_TOKEN;
+ expect(() => new FigmaApiSource("ABC123")).toThrow(/FIGMA_TOKEN/);
+ });
+ it("fetches the document and sends the token header", async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ name: "Doc", document: { id: "0:0", type: "DOCUMENT", name: "Doc", children: [] } }),
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const src = new FigmaApiSource("ABC123", "tok_secret");
+ const doc = await src.fetchDocument();
+ expect(doc.name).toBe("Doc");
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(String(url)).toContain("/files/ABC123");
+ expect((init.headers as Record<string, string>)["X-Figma-Token"]).toBe("tok_secret");
+ });
+ it("never leaks the token in error messages", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false, status: 403, statusText: "Forbidden" }));
+ const src = new FigmaApiSource("ABC123", "tok_secret");
+ await expect(src.fetchDocument()).rejects.toThrow(/403/);
+ await expect(src.fetchDocument()).rejects.not.toThrow(/tok_secret/);
+ });
+});
diff --git a/understand-anything-plugin/packages/core/src/figma/source/api-source.ts b/understand-anything-plugin/packages/core/src/figma/source/api-source.ts
new file mode 100644
index 00000000..b2e887fc
--- /dev/null
+++ b/understand-anything-plugin/packages/core/src/figma/source/api-source.ts
@@ -0,0 +1,50 @@
+import type { FigmaSource, FigmaDocument, FigmaStyles } from "./types";
+
+const FIGMA_API = "https://api.figma.com/v1";
+
+export function parseFileKey(urlOrKey: string): string {
+ const m = urlOrKey.match(/figma\.com\/(?:file|design)\/([A-Za-z0-9]+)/);
+ if (m) return m[1];
+ if (/^[A-Za-z0-9]+$/.test(urlOrKey.trim())) return urlOrKey.trim();
+ throw new Error(`Could not parse a Figma file key from: ${urlOrKey}`);
+}
+
+export class FigmaApiSource implements FigmaSource {
+ private readonly token: string;
+
+ constructor(private readonly fileKey: string, token: string | undefined = process.env.FIGMA_TOKEN) {
+ if (!token) {
+ throw new Error(
+ "FIGMA_TOKEN is not set. Create a personal access token at " +
+ "https://www.figma.com/settings, then run: export FIGMA_TOKEN=<token>",
+ );
+ }
+ this.token = token;
+ }
+
+ private async get<T>(path: string): Promise<T> {
+ // Token travels only in the header — never in the URL, never logged.
+ const res = await fetch(`${FIGMA_API}${path}`, { headers: { "X-Figma-Token": this.token } });
+ if (!res.ok) {
+ throw new Error(`Figma API ${path} failed: ${res.status} ${res.statusText}`);
+ }
+ return (await res.json()) as T;
+ }
+
+ fetchDocument(): Promise<FigmaDocument> {
+ return this.get<FigmaDocument>(`/files/${this.fileKey}`);
+ }
+
+ fetchStyles(): Promise<FigmaStyles> {
+ return this.get<FigmaStyles>(`/files/${this.fileKey}/styles`);
+ }
+
+ async renderImages(nodeIds: string[]): Promise<Record<string, string>> {
+ if (nodeIds.length === 0) return {};
+ const ids = encodeURIComponent(nodeIds.join(","));
+ const data = await this.get<{ images: Record<string, string> }>(
+ `/images/${this.fileKey}?ids=${ids}&format=png&scale=1`,
+ );
+ return data.images ?? {};
+ }
+}
diff --git a/understand-anything-plugin/packages/core/src/figma/source/types.ts b/understand-anything-plugin/packages/core/src/figma/source/types.ts
new file mode 100644
index 00000000..3b28e399
--- /dev/null
+++ b/understand-anything-plugin/packages/core/src/figma/source/types.ts
@@ -0,0 +1,27 @@
+export interface FigmaNode {
+ id: string;
+ name: string;
+ type: string; // DOCUMENT | CANVAS | FRAME | SECTION | COMPONENT | COMPONENT_SET | INSTANCE | TEXT | ...
+ children?: FigmaNode[];
+ componentId?: string; // on INSTANCE → main component node id
+ absoluteBoundingBox?: { width: number; height: number } | null;
+ styles?: Record<string, string>; // styleType (fill/text/effect/grid) → style key
+ transitionNodeID?: string | null; // prototype target node id
+}
+
+export interface FigmaDocument {
+ name: string;
+ document: FigmaNode; // root (DOCUMENT) whose children are CANVAS (pages)
+ components?: Record<string, { key: string; name: string; componentSetId?: string }>;
+ componentSets?: Record<string, { key: string; name: string }>;
+}
+
+export interface FigmaStyles {
+ meta?: { styles?: Array<{ key: string; name: string; style_type: string }> };
+}
+
+export interface FigmaSource {
+ fetchDocument(): Promise<FigmaDocument>;
+ fetchStyles(): Promise<FigmaStyles>;
+ renderImages(nodeIds: string[]): Promise<Record<string, string>>;
+}