Add use-figma skill with Figma API tool scripts

Includes 6 Node.js scripts for extracting design specs from Figma
(layout, typography, colors, screenshots, tokens, code connect map).
README explains API token setup.
This commit is contained in:
ivan.jovanovikj committed 2026-03-03 16:55:22 +01:00
1 parent 093fdef71a
commit c5bf4b57e4
8 files changed
+2574

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
# use-figma
Figma design tools for extracting specs and implementing pixel-perfect designs.
## Setup
### 1. Get a Figma API token
1. Go to [Figma Account Settings](https://www.figma.com/developers/api#access-tokens)
2. Generate a new **Personal Access Token**
3. Required scopes: `file_read`
4. Optional scopes: `file_variables:read` (needed for `get-variable-definitions`)
### 2. Configure the token
Create a `.env.tools` file in your project root:
```
FIGMA_ACCESS_TOKEN=your_token_here
```
Make sure `.env.tools` is in your `.gitignore` — never commit tokens.
### 3. Verify it works
```bash
node use-figma/scripts/whoami.mjs --verbose
```
You should see your Figma user info if the token is valid.
## Available Scripts
| Script | Description |
|---|---|
| `whoami.mjs` | Verify API token authentication |
| `get-design-context.mjs` | Extract layout, spacing, colors, typography |
| `get-metadata.mjs` | Get node hierarchy and constraints |
| `get-screenshot.mjs` | Generate visual screenshots from designs |
| `get-code-connect-map.mjs` | Check which components are linked to code |
| `get-variable-definitions.mjs` | Extract design tokens (colors, spacing, typography) |
## Usage
See `SKILL.md` for the full workflow on how these tools are used together.
+119
View File
@@ -0,0 +1,119 @@
---
name: use-figma
description: >
Fetch Figma design specs for pixel-perfect implementation. Triggers - Figma URL provided,
match the design, implement this Figma, from the mockup, design specs, pixel-perfect,
exact spacing/typography/colors needed.
---
# Figma Design Tools
This skill ships with Figma helper scripts under `use-figma/scripts/`.
## Prerequisites
- Set `FIGMA_ACCESS_TOKEN` in a `.env.tools` file at the project root (see `use-figma/README.md`).
- Use the scripts from this skill directory (do not assume a `js/bin` folder).
## When to use this skill
Use when:
- The user provides a **Figma URL** (design / node / section link)
- The request says "match Figma" / "implement this design" / "pixel-perfect"
- You need **exact spacing/typography/colors/states** (not "close enough")
## Workflow
### When a Figma URL is provided
1. **Extract EXACT Specifications** (MANDATORY)
Run the tools in sequence:
```bash
# 1. Verify token works
node use-figma/scripts/whoami.mjs --verbose
# 2. Get layout, spacing, colors, typography
node use-figma/scripts/get-design-context.mjs \
--url "https://www.figma.com/design/..." \
--include-images \
--verbose
# 3. Get node hierarchy and constraints
node use-figma/scripts/get-metadata.mjs \
--url "https://www.figma.com/design/..." \
--verbose
# 4. Get a visual screenshot for reference
node use-figma/scripts/get-screenshot.mjs \
--url "https://www.figma.com/design/..." \
--format png \
--scale 2 \
--verbose
```
**Output handling (required)**
- If the output includes an `errors` array, it must be empty before using the data.
- Capture a short "design spec note" before coding:
- typography (fontSize/fontWeight/lineHeight)
- spacing (padding/margins/gaps)
- colors (tokens/variables or exact values)
- border radius, shadows
- states (hover/focus/active/disabled/empty/loading)
2. **Document ALL Measurements Before Writing Code**
Extract and note:
- **Typography**: `fontSize`, `fontWeight`, `lineHeight` for EVERY text element
- **Spacing**: Exact margins, paddings, gaps from auto-layout values
- **Colors**: Hex/RGB values — no approximations
- **Dimensions**: Precise width/height/aspect-ratio values
- **Border radius**: `cornerRadius` values
- **Shadows**: `effects` array for box shadows
- **States**: Document hover, focus, active, disabled, empty states
3. **Check Existing Patterns**
Before implementing, check if similar components exist:
```bash
# Check which Figma components are already linked to code
node use-figma/scripts/get-code-connect-map.mjs \
--file-key <FILE_KEY> \
--verbose
```
4. **Implement with EXACT Values**
- Use exact Figma values, not approximations
- Prefer existing design tokens; if no token exists, use the exact value and leave a short comment referencing the Figma node / measurement
- Implement ALL interactive states from the design
5. **Validate**
Before finishing:
- [ ] Typography matches Figma exactly (font size, weight, line height)
- [ ] Spacing matches Figma exactly (margins, padding, gaps)
- [ ] Colors match Figma exactly (use hex values from design)
- [ ] All interactive states implemented (hover, focus, active, disabled)
- [ ] Responsive behavior matches design intent
## Additional Commands
```bash
# Get design tokens (colors, spacing, typography variables)
node use-figma/scripts/get-variable-definitions.mjs \
--file-key <FILE_KEY> \
--include-styles true \
--verbose
```
## Rules
- **NEVER approximate** — use exact values from Figma
- **ALWAYS document measurements** before writing any code
- **Check `errors` array** is empty before using response data
- **Ask for clarification** if the design is ambiguous or states are missing
- **Reference existing patterns** before creating new components
+390
View File
@@ -0,0 +1,390 @@
#!/usr/bin/env node
// coding-tools/figma-tools/js/src/get-code-connect-map.ts
import { readFile } from "node:fs/promises";
import path from "node:path";
// coding-tools/figma-tools/js/src/_utils/cli-args.ts
function parseArgs(argv = process.argv.slice(2)) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("-") || arg === "-") {
args._.push(arg);
continue;
}
if (arg === "--") {
const remaining = argv.slice(i + 1);
args._.push(...remaining);
break;
}
const [rawKey, inlineValue] = arg.split("=", 2);
const normalisedKey = rawKey.replace(/^-+/, "");
let value;
if (inlineValue !== void 0) {
value = inlineValue;
} else {
const next = argv[i + 1];
if (next !== void 0 && !next.startsWith("-")) {
value = next;
i += 1;
} else {
value = true;
}
}
args[normalisedKey] = value;
}
return args;
}
// coding-tools/figma-tools/js/src/_utils/url-parse.ts
var FILE_KEY_REGEX = /figma\.com\/(?:file|design)\/([A-Za-z0-9]+)\//i;
function parseFigmaUrl(input) {
if (!input) return { fileKey: null, nodeId: null };
try {
const url = new URL(input);
const match = url.href.match(FILE_KEY_REGEX);
const fileKey = match ? match[1] : null;
const nodeParam = url.searchParams.get("node-id");
const nodeId = nodeParam ? ensureNodeId(nodeParam) : null;
return { fileKey, nodeId };
} catch {
return { fileKey: null, nodeId: null };
}
}
function ensureNodeId(value) {
if (!value) return null;
const decoded = decodeURIComponent(value);
if (decoded.includes(":")) return decoded;
if (/^[0-9]+-[0-9]+$/.test(decoded)) {
const [left, right] = decoded.split("-", 2);
return `${left}:${right}`;
}
return decoded;
}
// coding-tools/figma-tools/js/src/_utils/config.ts
var config_default = {
schemaVersion: "1.0.0",
source: "agentic-coding-templates/figma-tools",
http: {
maxAttempts: 5,
initialDelayMs: 250
}
};
// coding-tools/figma-tools/js/src/_utils/envelope.ts
function buildRateLimitMeta(rateLimit = {}) {
return {
remaining: rateLimit.remaining ?? null,
resetAt: rateLimit.resetAt ?? null,
attempts: rateLimit.attempts ?? 1,
lastWaitMs: rateLimit.lastWaitMs ?? 0
};
}
function createEnvelope({
tool,
input = {},
data = {},
warnings = [],
errors = [],
rateLimit,
schemaVersion
}) {
return {
schemaVersion: schemaVersion ?? config_default.schemaVersion,
tool,
input,
meta: {
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
source: config_default.source,
rateLimit: buildRateLimitMeta(rateLimit)
},
data,
warnings,
errors
};
}
// coding-tools/figma-tools/js/src/_utils/errors.ts
var ERROR_EXIT_CODES = {
INPUT_INVALID: 1,
CONFIG_INVALID: 1,
FIGMA_AUTH: 1,
FIGMA_NOT_FOUND: 2,
FIGMA_RATE_LIMIT: 2,
NETWORK: 2,
INTERNAL: 3
};
function createError(code, message, detail) {
return {
code,
message,
detail: detail ?? null
};
}
function getExitCode(errors = []) {
if (!errors.length) {
return 0;
}
return errors.reduce((max, error) => {
const exitCode = ERROR_EXIT_CODES[error.code] ?? 1;
return Math.max(max, exitCode);
}, 0);
}
// coding-tools/figma-tools/js/src/_utils/http-client.ts
var BASE_URL = "https://api.figma.com";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseJsonSafely(text) {
try {
return text ? JSON.parse(text) : {};
} catch {
return { raw: text };
}
}
function parseRateLimit(headers, attempts, lastWaitMs) {
const remainingHeader = headers.get("x-ratelimit-remaining");
const resetHeader = headers.get("x-ratelimit-reset");
let remaining = null;
if (remainingHeader !== null && remainingHeader !== void 0) {
const parsed = Number(remainingHeader);
remaining = Number.isNaN(parsed) ? null : parsed;
}
let resetAt = null;
if (resetHeader) {
const numericReset = Number(resetHeader);
if (!Number.isNaN(numericReset)) {
resetAt = new Date(numericReset * 1e3).toISOString();
} else {
const date = new Date(resetHeader);
if (!Number.isNaN(date.valueOf())) {
resetAt = date.toISOString();
}
}
}
return {
remaining,
resetAt,
attempts,
lastWaitMs
};
}
function computeBackoffMs(attempt, initialDelayMs) {
return initialDelayMs * 2 ** (attempt - 1);
}
async function figmaRequest(options) {
const {
path: path2,
method = "GET",
token,
headers = {},
body,
searchParams,
maxAttempts = config_default.http?.maxAttempts ?? 5,
initialDelayMs = config_default.http?.initialDelayMs ?? 250
} = options;
if (!token) {
return {
ok: false,
error: createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is missing from the environment."),
status: null,
rateLimit: null
};
}
const url = new URL(path2, BASE_URL);
if (searchParams) {
Object.entries(searchParams).forEach(([key, value]) => {
if (value === void 0 || value === null) return;
url.searchParams.append(key, String(value));
});
}
let attempt = 0;
let lastWaitMs = 0;
while (attempt < maxAttempts) {
attempt += 1;
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
"X-Figma-Token": token,
...headers
},
body: body ? JSON.stringify(body) : void 0
});
const text = await response.text();
const payload = parseJsonSafely(text);
const rateLimit = parseRateLimit(response.headers, attempt, lastWaitMs);
if (response.ok) {
return { ok: true, data: payload, rateLimit };
}
const status = response.status;
if (status === 401 || status === 403) {
return { ok: false, error: createError("FIGMA_AUTH", payload?.message ?? "Figma token is unauthorized.", { status }), status, rateLimit };
}
if (status === 404) {
return { ok: false, error: createError("FIGMA_NOT_FOUND", payload?.message ?? "Resource not found.", { status }), status, rateLimit };
}
if (status === 429 || status >= 500) {
if (attempt >= maxAttempts) {
return {
ok: false,
error: createError(status === 429 ? "FIGMA_RATE_LIMIT" : "NETWORK", payload?.message ?? "Figma request failed after maximum retries.", { status }),
status,
rateLimit
};
}
let waitMs = computeBackoffMs(attempt, initialDelayMs);
const resetHeader = response.headers.get("x-ratelimit-reset");
if (resetHeader) {
const asNumber = Number(resetHeader);
if (!Number.isNaN(asNumber)) {
const resetMs = asNumber * 1e3;
const delta = resetMs - Date.now();
if (delta > 0) waitMs = Math.max(waitMs, delta);
}
}
const jitter = Math.floor(Math.random() * 100);
lastWaitMs = waitMs + jitter;
await sleep(lastWaitMs);
continue;
}
return { ok: false, error: createError("INTERNAL", payload?.message ?? "Unexpected error from Figma API.", { status }), status, rateLimit };
}
return {
ok: false,
error: createError("NETWORK", "Unable to reach Figma API."),
status: null,
rateLimit: { remaining: null, resetAt: null, attempts: maxAttempts, lastWaitMs }
};
}
// coding-tools/figma-tools/js/src/get-code-connect-map.ts
var TOOL_NAME = "get-code-connect-map";
function log(message, verbose) {
if (verbose) process.stderr.write(`[${TOOL_NAME}] ${message}
`);
}
function toOptionalString(value) {
return typeof value === "string" && value.length > 0 ? value : null;
}
function exitWithEnvelope(envelope, errors = []) {
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
async function readRepoConfig() {
try {
const configPath = path.resolve("config/code-connect-map.json");
const content = await readFile(configPath, "utf8");
const parsed = JSON.parse(content);
if (parsed && Array.isArray(parsed.components)) return parsed;
return { version: "0.1", components: [] };
} catch {
return { version: "0.1", components: [] };
}
}
async function main() {
const args = parseArgs();
const verbose = Boolean(args.verbose ?? args.v);
const schemaVersion = toOptionalString(args["schema-version"]) ?? void 0;
const warnings = [];
const errors = [];
let repoConfig = { version: "0.1", components: [] };
try {
repoConfig = await readRepoConfig();
} catch (error) {
warnings.push(error instanceof Error ? error.message : String(error));
}
const token = process.env.FIGMA_ACCESS_TOKEN;
if (!token || !token.trim()) {
errors.push(createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is required but was not provided."));
const envelope2 = createEnvelope({ tool: TOOL_NAME, input: { fileKey: null, nodeId: null }, warnings, errors, schemaVersion, data: {} });
exitWithEnvelope(envelope2, errors);
}
const urlInput = toOptionalString(args.url) ?? toOptionalString(args.u);
let fileKey = toOptionalString(args["file-key"]) ?? void 0;
const nodeIdInput = ensureNodeId(toOptionalString(args["node-id"]));
if (urlInput) {
const parsed = parseFigmaUrl(urlInput);
fileKey = fileKey || parsed.fileKey || void 0;
}
const input = { fileKey: fileKey ?? null, nodeId: nodeIdInput ?? null };
if (!fileKey) errors.push(createError("INPUT_INVALID", "A valid Figma file key is required (--file-key or --url)."));
if (errors.length) {
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
const resolvedFileKey = fileKey;
log("Fetching dev resources", verbose);
const devResourcesResponse = await figmaRequest({ path: `/v1/files/${resolvedFileKey}/devresources`, token });
log("Fetching components", verbose);
const componentsResponse = await figmaRequest({ path: `/v1/files/${resolvedFileKey}/components`, token });
if (!devResourcesResponse.ok) {
errors.push(devResourcesResponse.error ?? createError("INTERNAL", "Failed to fetch dev resources."));
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, rateLimit: devResourcesResponse.rateLimit ?? void 0, schemaVersion, data: {} });
exitWithEnvelope(envelope2, errors);
}
if (!componentsResponse.ok) warnings.push(componentsResponse.error?.message ?? "Failed to fetch components.");
const devResources = devResourcesResponse.data?.dev_resources ?? [];
const componentsMap = componentsResponse.ok ? componentsResponse.data?.components ?? {} : {};
const repoMappings = repoConfig.components ?? [];
const normalisedResources = devResources.map((resource) => ({
id: resource.id,
name: resource.name,
description: resource.description ?? null,
url: resource.url ?? null,
nodeId: resource.node_id ?? null,
componentId: resource.component_id ?? null,
fileKey: resource.file_key ?? resolvedFileKey,
status: resource.status ?? null,
createdAt: resource.created_at ?? null,
updatedAt: resource.updated_at ?? null
}));
const normalisedComponents = Object.entries(componentsMap).map(([componentId, component]) => ({
id: componentId,
key: component.key,
name: component.name,
description: component.description ?? null,
fileKey: component.file_key ?? resolvedFileKey,
nodeId: component.node_id ?? null
}));
const findRepoMapping = (name) => {
if (!name) return null;
return repoMappings.find((m) => m.name === name || m.component === name) ?? null;
};
const mappings = normalisedResources.map((resource) => {
const component = resource.componentId ? normalisedComponents.find((entry) => entry.id === resource.componentId) : null;
const repoMapping = findRepoMapping(component?.name ?? resource.name);
if (!repoMapping) {
warnings.push(`Node ${resource.nodeId ?? component?.nodeId ?? "unknown"} (${resource.name ?? component?.name ?? "unnamed"}) has no mapping in config/code-connect-map.json.`);
}
return {
nodeId: resource.nodeId ?? component?.nodeId ?? null,
componentId: resource.componentId ?? component?.id ?? null,
componentKey: component?.key ?? null,
componentName: component?.name ?? resource.name ?? null,
repoComponent: repoMapping?.component ?? null,
repoPath: repoMapping?.path ?? null,
props: repoMapping?.props ?? null,
description: component?.description ?? resource.description ?? null,
status: resource.status ?? null,
sourceUrl: resource.url ?? null
};
});
const data = { file: { key: resolvedFileKey }, mappings, components: normalisedComponents, devResources: normalisedResources };
const envelope = createEnvelope({ tool: TOOL_NAME, input, data, warnings, errors, rateLimit: devResourcesResponse.rateLimit ?? void 0, schemaVersion });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
main().catch((error) => {
const message = error instanceof Error ? error.message : "Unknown error";
const envelope = createEnvelope({ tool: TOOL_NAME, input: { fileKey: null, nodeId: null }, errors: [createError("INTERNAL", message, { stack: error instanceof Error ? error.stack : void 0 })], data: {} });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(3);
});
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL2dldC1jb2RlLWNvbm5lY3QtbWFwLnRzIiwgIi4uL3NyYy9fdXRpbHMvY2xpLWFyZ3MudHMiLCAiLi4vc3JjL191dGlscy91cmwtcGFyc2UudHMiLCAiLi4vc3JjL191dGlscy9jb25maWcudHMiLCAiLi4vc3JjL191dGlscy9lbnZlbG9wZS50cyIsICIuLi9zcmMvX3V0aWxzL2Vycm9ycy50cyIsICIuLi9zcmMvX3V0aWxzL2h0dHAtY2xpZW50LnRzIl0sCiAgInNvdXJjZXNDb250ZW50IjogWyIjIS91c3IvYmluL2VudiBub2RlXG5cbmltcG9ydCB7IHJlYWRGaWxlIH0gZnJvbSAnbm9kZTpmcy9wcm9taXNlcydcbmltcG9ydCBwYXRoIGZy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HZlcnNpb246ICcwLjEnLCBjb21wb25lbnRzOiBbXSB9XG4gIHRyeSB7IHJlcG9Db25maWcgPSBhd2FpdCByZWFkUmVwb0NvbmZpZygpIH0gY2F0Y2ggKGVyc Line truncated
+484
View File
@@ -0,0 +1,484 @@
#!/usr/bin/env node
// coding-tools/figma-tools/js/src/get-design-context.ts
import { createHash } from "node:crypto";
// coding-tools/figma-tools/js/src/_utils/cli-args.ts
function parseArgs(argv = process.argv.slice(2)) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("-") || arg === "-") {
args._.push(arg);
continue;
}
if (arg === "--") {
const remaining = argv.slice(i + 1);
args._.push(...remaining);
break;
}
const [rawKey, inlineValue] = arg.split("=", 2);
const normalisedKey = rawKey.replace(/^-+/, "");
let value;
if (inlineValue !== void 0) {
value = inlineValue;
} else {
const next = argv[i + 1];
if (next !== void 0 && !next.startsWith("-")) {
value = next;
i += 1;
} else {
value = true;
}
}
args[normalisedKey] = value;
}
return args;
}
// coding-tools/figma-tools/js/src/_utils/config.ts
var config_default = {
schemaVersion: "1.0.0",
source: "agentic-coding-templates/figma-tools",
http: {
maxAttempts: 5,
initialDelayMs: 250
}
};
// coding-tools/figma-tools/js/src/_utils/envelope.ts
function buildRateLimitMeta(rateLimit = {}) {
return {
remaining: rateLimit.remaining ?? null,
resetAt: rateLimit.resetAt ?? null,
attempts: rateLimit.attempts ?? 1,
lastWaitMs: rateLimit.lastWaitMs ?? 0
};
}
function createEnvelope({
tool,
input = {},
data = {},
warnings = [],
errors = [],
rateLimit,
schemaVersion
}) {
return {
schemaVersion: schemaVersion ?? config_default.schemaVersion,
tool,
input,
meta: {
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
source: config_default.source,
rateLimit: buildRateLimitMeta(rateLimit)
},
data,
warnings,
errors
};
}
// coding-tools/figma-tools/js/src/_utils/errors.ts
var ERROR_EXIT_CODES = {
INPUT_INVALID: 1,
CONFIG_INVALID: 1,
FIGMA_AUTH: 1,
FIGMA_NOT_FOUND: 2,
FIGMA_RATE_LIMIT: 2,
NETWORK: 2,
INTERNAL: 3
};
function createError(code, message, detail) {
return {
code,
message,
detail: detail ?? null
};
}
function getExitCode(errors = []) {
if (!errors.length) {
return 0;
}
return errors.reduce((max, error) => {
const exitCode = ERROR_EXIT_CODES[error.code] ?? 1;
return Math.max(max, exitCode);
}, 0);
}
// coding-tools/figma-tools/js/src/_utils/http-client.ts
var BASE_URL = "https://api.figma.com";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseJsonSafely(text) {
try {
return text ? JSON.parse(text) : {};
} catch {
return { raw: text };
}
}
function parseRateLimit(headers, attempts, lastWaitMs) {
const remainingHeader = headers.get("x-ratelimit-remaining");
const resetHeader = headers.get("x-ratelimit-reset");
let remaining = null;
if (remainingHeader !== null && remainingHeader !== void 0) {
const parsed = Number(remainingHeader);
remaining = Number.isNaN(parsed) ? null : parsed;
}
let resetAt = null;
if (resetHeader) {
const numericReset = Number(resetHeader);
if (!Number.isNaN(numericReset)) {
resetAt = new Date(numericReset * 1e3).toISOString();
} else {
const date = new Date(resetHeader);
if (!Number.isNaN(date.valueOf())) {
resetAt = date.toISOString();
}
}
}
return {
remaining,
resetAt,
attempts,
lastWaitMs
};
}
function computeBackoffMs(attempt, initialDelayMs) {
return initialDelayMs * 2 ** (attempt - 1);
}
async function figmaRequest(options) {
const {
path,
method = "GET",
token,
headers = {},
body,
searchParams,
maxAttempts = config_default.http?.maxAttempts ?? 5,
initialDelayMs = config_default.http?.initialDelayMs ?? 250
} = options;
if (!token) {
return {
ok: false,
error: createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is missing from the environment."),
status: null,
rateLimit: null
};
}
const url = new URL(path, BASE_URL);
if (searchParams) {
Object.entries(searchParams).forEach(([key, value]) => {
if (value === void 0 || value === null) return;
url.searchParams.append(key, String(value));
});
}
let attempt = 0;
let lastWaitMs = 0;
while (attempt < maxAttempts) {
attempt += 1;
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
"X-Figma-Token": token,
...headers
},
body: body ? JSON.stringify(body) : void 0
});
const text = await response.text();
const payload = parseJsonSafely(text);
const rateLimit = parseRateLimit(response.headers, attempt, lastWaitMs);
if (response.ok) {
return { ok: true, data: payload, rateLimit };
}
const status = response.status;
if (status === 401 || status === 403) {
return { ok: false, error: createError("FIGMA_AUTH", payload?.message ?? "Figma token is unauthorized.", { status }), status, rateLimit };
}
if (status === 404) {
return { ok: false, error: createError("FIGMA_NOT_FOUND", payload?.message ?? "Resource not found.", { status }), status, rateLimit };
}
if (status === 429 || status >= 500) {
if (attempt >= maxAttempts) {
return {
ok: false,
error: createError(status === 429 ? "FIGMA_RATE_LIMIT" : "NETWORK", payload?.message ?? "Figma request failed after maximum retries.", { status }),
status,
rateLimit
};
}
let waitMs = computeBackoffMs(attempt, initialDelayMs);
const resetHeader = response.headers.get("x-ratelimit-reset");
if (resetHeader) {
const asNumber = Number(resetHeader);
if (!Number.isNaN(asNumber)) {
const resetMs = asNumber * 1e3;
const delta = resetMs - Date.now();
if (delta > 0) waitMs = Math.max(waitMs, delta);
}
}
const jitter = Math.floor(Math.random() * 100);
lastWaitMs = waitMs + jitter;
await sleep(lastWaitMs);
continue;
}
return { ok: false, error: createError("INTERNAL", payload?.message ?? "Unexpected error from Figma API.", { status }), status, rateLimit };
}
return {
ok: false,
error: createError("NETWORK", "Unable to reach Figma API."),
status: null,
rateLimit: { remaining: null, resetAt: null, attempts: maxAttempts, lastWaitMs }
};
}
// coding-tools/figma-tools/js/src/_utils/url-parse.ts
var FILE_KEY_REGEX = /figma\.com\/(?:file|design)\/([A-Za-z0-9]+)\//i;
function parseFigmaUrl(input) {
if (!input) return { fileKey: null, nodeId: null };
try {
const url = new URL(input);
const match = url.href.match(FILE_KEY_REGEX);
const fileKey = match ? match[1] : null;
const nodeParam = url.searchParams.get("node-id");
const nodeId = nodeParam ? ensureNodeId(nodeParam) : null;
return { fileKey, nodeId };
} catch {
return { fileKey: null, nodeId: null };
}
}
function ensureNodeId(value) {
if (!value) return null;
const decoded = decodeURIComponent(value);
if (decoded.includes(":")) return decoded;
if (/^[0-9]+-[0-9]+$/.test(decoded)) {
const [left, right] = decoded.split("-", 2);
return `${left}:${right}`;
}
return decoded;
}
// coding-tools/figma-tools/js/src/get-design-context.ts
var TOOL_NAME = "get-design-context";
var VALID_IMAGE_FORMATS = ["png", "jpg", "jpeg", "svg"];
function log(message, verbose) {
if (verbose) {
process.stderr.write(`[${TOOL_NAME}] ${message}
`);
}
}
function toOptionalString(value) {
return typeof value === "string" && value.length > 0 ? value : null;
}
function exitWithEnvelope(envelope, errors = []) {
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
function mapLayoutNode(node) {
const children = Array.isArray(node.children) ? node.children.map(mapLayoutNode) : [];
const bbox = node.absoluteBoundingBox;
const layout = bbox ? { x: bbox.x ?? 0, y: bbox.y ?? 0, width: bbox.width ?? 0, height: bbox.height ?? 0 } : null;
return {
id: node.id,
name: node.name,
type: node.type,
visible: node.visible ?? true,
layout,
rotation: node.rotation ?? 0,
clipsContent: node.clipsContent ?? false,
characters: node.characters ?? null,
fills: node.fills ?? [],
strokes: node.strokes ?? [],
effects: node.effects ?? [],
tailwindSuggestion: null,
children
};
}
function buildStyleTokens(node) {
const cornerRadius = Array.isArray(node.rectangleCornerRadii) && node.rectangleCornerRadii.length > 0 ? node.rectangleCornerRadii : node.cornerRadius ?? null;
return {
fills: node.fills ?? [],
strokes: node.strokes ?? [],
effects: node.effects ?? [],
backgroundColor: node.backgroundColor ?? null,
textStyle: node.style ?? null,
styles: node.styles ?? {},
cornerRadius
};
}
function buildSelectionSummary(node, components, componentSets) {
const componentId = node.componentId ?? null;
const componentSetId = node.componentSetId ?? null;
const componentMeta = componentId ? components[componentId] ?? null : null;
const componentSetMeta = componentSetId ? componentSets[componentSetId] ?? null : null;
return {
id: node.id,
name: node.name,
type: node.type,
componentId,
componentKey: componentMeta?.key ?? null,
componentName: componentMeta?.name ?? null,
componentSetId,
componentSetName: componentSetMeta?.name ?? null,
variantProperties: node.variantProperties ?? null
};
}
function computeLayoutHash(layoutTree) {
const json = JSON.stringify(layoutTree);
return createHash("sha1").update(json).digest("hex");
}
async function fetchPreviewImage(fileKey, nodeId, token, imageFormat, scale, warnings, verbose) {
const format = VALID_IMAGE_FORMATS.includes(imageFormat) ? imageFormat : "png";
const scaleClamped = Number.isFinite(scale) && scale > 0 ? scale : 1;
log(`Requesting preview image format=${format}, scale=${scaleClamped}`, verbose);
const imageResponse = await figmaRequest({
path: `/v1/images/${fileKey}`,
token,
searchParams: { ids: nodeId, format, scale: scaleClamped }
});
if (!imageResponse.ok) {
warnings.push(imageResponse.error?.message ?? "Failed to request preview image.");
return null;
}
const url = imageResponse.data?.images?.[nodeId];
if (!url) return null;
return { url, format, size: `${scaleClamped}x` };
}
async function main() {
const args = parseArgs();
const verbose = Boolean(args.verbose ?? args.v);
const schemaVersion = toOptionalString(args["schema-version"]) ?? void 0;
const warnings = [];
const errors = [];
const token = process.env.FIGMA_ACCESS_TOKEN;
if (!token || !token.trim()) {
errors.push(createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is required but was not provided."));
const envelope2 = createEnvelope({
tool: TOOL_NAME,
input: { fileKey: null, nodeId: null, includeImages: false, imageFormat: "png", scale: 1 },
warnings,
errors,
schemaVersion,
data: {}
});
exitWithEnvelope(envelope2, errors);
}
const urlInput = toOptionalString(args.url) ?? toOptionalString(args.u);
let fileKey = toOptionalString(args["file-key"]) ?? void 0;
let nodeId = ensureNodeId(toOptionalString(args["node-id"]));
if (urlInput) {
const parsed = parseFigmaUrl(urlInput);
fileKey = fileKey || parsed.fileKey || void 0;
nodeId = nodeId || parsed.nodeId;
}
const includeImages = args["include-images"] !== "false";
const imageFormatInput = String(args["image-format"] ?? "png").toLowerCase();
const imageFormat = VALID_IMAGE_FORMATS.includes(imageFormatInput) ? imageFormatInput : "png";
const scaleInput = Number(args.scale ?? 1);
const imageScale = Number.isFinite(scaleInput) && scaleInput > 0 ? scaleInput : 1;
const input = {
fileKey: fileKey ?? null,
nodeId: nodeId ?? null,
includeImages,
imageFormat,
scale: imageScale
};
if (!fileKey) {
errors.push(createError("INPUT_INVALID", "A valid Figma file key is required (--file-key or --url)."));
}
if (!nodeId) {
errors.push(createError("INPUT_INVALID", "A valid Figma node id is required (--node-id or --url with node-id)."));
}
if (errors.length) {
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
const resolvedFileKey = fileKey;
const resolvedNodeId = nodeId;
log(`Fetching node ${resolvedNodeId} from file ${resolvedFileKey}`, verbose);
const nodeResponse = await figmaRequest({
path: `/v1/files/${resolvedFileKey}/nodes`,
token,
searchParams: { ids: resolvedNodeId }
});
if (!nodeResponse.ok) {
errors.push(nodeResponse.error ?? createError("INTERNAL", "Failed to fetch node data."));
const envelope2 = createEnvelope({
tool: TOOL_NAME,
input,
warnings,
errors,
rateLimit: nodeResponse.rateLimit ?? void 0,
data: {},
schemaVersion
});
exitWithEnvelope(envelope2, errors);
}
const nodePayload = nodeResponse.data ?? {};
const nodesMap = nodePayload.nodes ?? {};
const nodeWrapper = nodesMap[resolvedNodeId];
if (!nodeWrapper || !nodeWrapper.document) {
errors.push(createError("FIGMA_NOT_FOUND", `Node ${resolvedNodeId} was not found in file ${resolvedFileKey}.`));
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, rateLimit: nodeResponse.rateLimit ?? void 0, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
const node = nodeWrapper.document;
const components = nodeWrapper.components ?? {};
const componentSets = nodeWrapper.componentSets ?? {};
const selectionSummary = buildSelectionSummary(node, components, componentSets);
const layoutTree = mapLayoutNode(node);
const styleTokens = buildStyleTokens(node);
const layoutHash = computeLayoutHash(layoutTree);
let preview = null;
if (includeImages) {
preview = await fetchPreviewImage(
resolvedFileKey,
resolvedNodeId,
token,
imageFormat,
imageScale,
warnings,
verbose
);
}
const data = {
file: {
key: resolvedFileKey,
name: nodePayload?.name ?? null,
lastModified: nodePayload?.lastModified ?? null
},
selectionSummary,
layoutTree,
styleTokens,
layoutHash,
images: preview ? { preview } : null
};
const envelope = createEnvelope({
tool: TOOL_NAME,
input,
data,
warnings,
errors,
rateLimit: nodeResponse.rateLimit ?? void 0,
schemaVersion
});
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
main().catch((error) => {
const message = error instanceof Error ? error.message : "Unknown error";
const envelope = createEnvelope({
tool: TOOL_NAME,
input: { fileKey: null, nodeId: null, includeImages: false, imageFormat: "png", scale: 1 },
errors: [createError("INTERNAL", message, { stack: error instanceof Error ? error.stack : void 0 })],
data: {}
});
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(3);
});
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL2dldC1kZXNpZ24tY29udGV4dC50cyIsICIuLi9zcmMvX3V0aWxzL2NsaS1hcmdzLnRzIiwgIi4uL3NyYy9fdXRpbHMvY29uZmlnLnRzIiwgIi4uL3NyYy9fdXRpbHMvZW52ZWxvcGUudHMiLCAiLi4vc3JjL191dGlscy9lcnJvcnMudHMiLCAiLi4vc3JjL191dGlscy9odHRwLWNsaWVudC50cyIsICIuLi9zcmMvX3V0aWxzL3VybC1wYXJzZS50cyJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiIyEvdXNyL2Jpbi9lbnYgbm9kZVxuXG5pbXBvcnQgeyBjcmVhdGVIYXNoIH0gZnJvbSAnbm9kZTpjcnlwdG8nXG5pbXBvcnQgeyBwYXJzZUFyZ3MsIHR5cGUgQ2xpQXJncyB9IGZyb20gJy4vX3V0aWxzL2NsaS1hcmdzLnRzJ1xuaW1wb3J0IHsgY3JlYXRlRW52ZWxvcGUsIHR5cGUgVG9vbEV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dmFsd Line truncated
+469
View File
@@ -0,0 +1,469 @@
#!/usr/bin/env node
// coding-tools/figma-tools/js/src/_utils/cli-args.ts
function parseArgs(argv = process.argv.slice(2)) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("-") || arg === "-") {
args._.push(arg);
continue;
}
if (arg === "--") {
const remaining = argv.slice(i + 1);
args._.push(...remaining);
break;
}
const [rawKey, inlineValue] = arg.split("=", 2);
const normalisedKey = rawKey.replace(/^-+/, "");
let value;
if (inlineValue !== void 0) {
value = inlineValue;
} else {
const next = argv[i + 1];
if (next !== void 0 && !next.startsWith("-")) {
value = next;
i += 1;
} else {
value = true;
}
}
args[normalisedKey] = value;
}
return args;
}
// coding-tools/figma-tools/js/src/_utils/url-parse.ts
var FILE_KEY_REGEX = /figma\.com\/(?:file|design)\/([A-Za-z0-9]+)\//i;
function parseFigmaUrl(input) {
if (!input) return { fileKey: null, nodeId: null };
try {
const url = new URL(input);
const match = url.href.match(FILE_KEY_REGEX);
const fileKey = match ? match[1] : null;
const nodeParam = url.searchParams.get("node-id");
const nodeId = nodeParam ? ensureNodeId(nodeParam) : null;
return { fileKey, nodeId };
} catch {
return { fileKey: null, nodeId: null };
}
}
function ensureNodeId(value) {
if (!value) return null;
const decoded = decodeURIComponent(value);
if (decoded.includes(":")) return decoded;
if (/^[0-9]+-[0-9]+$/.test(decoded)) {
const [left, right] = decoded.split("-", 2);
return `${left}:${right}`;
}
return decoded;
}
// coding-tools/figma-tools/js/src/_utils/config.ts
var config_default = {
schemaVersion: "1.0.0",
source: "agentic-coding-templates/figma-tools",
http: {
maxAttempts: 5,
initialDelayMs: 250
}
};
// coding-tools/figma-tools/js/src/_utils/envelope.ts
function buildRateLimitMeta(rateLimit = {}) {
return {
remaining: rateLimit.remaining ?? null,
resetAt: rateLimit.resetAt ?? null,
attempts: rateLimit.attempts ?? 1,
lastWaitMs: rateLimit.lastWaitMs ?? 0
};
}
function createEnvelope({
tool,
input = {},
data = {},
warnings = [],
errors = [],
rateLimit,
schemaVersion
}) {
return {
schemaVersion: schemaVersion ?? config_default.schemaVersion,
tool,
input,
meta: {
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
source: config_default.source,
rateLimit: buildRateLimitMeta(rateLimit)
},
data,
warnings,
errors
};
}
// coding-tools/figma-tools/js/src/_utils/errors.ts
var ERROR_EXIT_CODES = {
INPUT_INVALID: 1,
CONFIG_INVALID: 1,
FIGMA_AUTH: 1,
FIGMA_NOT_FOUND: 2,
FIGMA_RATE_LIMIT: 2,
NETWORK: 2,
INTERNAL: 3
};
function createError(code, message, detail) {
return {
code,
message,
detail: detail ?? null
};
}
function getExitCode(errors = []) {
if (!errors.length) {
return 0;
}
return errors.reduce((max, error) => {
const exitCode = ERROR_EXIT_CODES[error.code] ?? 1;
return Math.max(max, exitCode);
}, 0);
}
// coding-tools/figma-tools/js/src/_utils/http-client.ts
var BASE_URL = "https://api.figma.com";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseJsonSafely(text) {
try {
return text ? JSON.parse(text) : {};
} catch {
return { raw: text };
}
}
function parseRateLimit(headers, attempts, lastWaitMs) {
const remainingHeader = headers.get("x-ratelimit-remaining");
const resetHeader = headers.get("x-ratelimit-reset");
let remaining = null;
if (remainingHeader !== null && remainingHeader !== void 0) {
const parsed = Number(remainingHeader);
remaining = Number.isNaN(parsed) ? null : parsed;
}
let resetAt = null;
if (resetHeader) {
const numericReset = Number(resetHeader);
if (!Number.isNaN(numericReset)) {
resetAt = new Date(numericReset * 1e3).toISOString();
} else {
const date = new Date(resetHeader);
if (!Number.isNaN(date.valueOf())) {
resetAt = date.toISOString();
}
}
}
return {
remaining,
resetAt,
attempts,
lastWaitMs
};
}
function computeBackoffMs(attempt, initialDelayMs) {
return initialDelayMs * 2 ** (attempt - 1);
}
async function figmaRequest(options) {
const {
path,
method = "GET",
token,
headers = {},
body,
searchParams,
maxAttempts = config_default.http?.maxAttempts ?? 5,
initialDelayMs = config_default.http?.initialDelayMs ?? 250
} = options;
if (!token) {
return {
ok: false,
error: createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is missing from the environment."),
status: null,
rateLimit: null
};
}
const url = new URL(path, BASE_URL);
if (searchParams) {
Object.entries(searchParams).forEach(([key, value]) => {
if (value === void 0 || value === null) return;
url.searchParams.append(key, String(value));
});
}
let attempt = 0;
let lastWaitMs = 0;
while (attempt < maxAttempts) {
attempt += 1;
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
"X-Figma-Token": token,
...headers
},
body: body ? JSON.stringify(body) : void 0
});
const text = await response.text();
const payload = parseJsonSafely(text);
const rateLimit = parseRateLimit(response.headers, attempt, lastWaitMs);
if (response.ok) {
return { ok: true, data: payload, rateLimit };
}
const status = response.status;
if (status === 401 || status === 403) {
return { ok: false, error: createError("FIGMA_AUTH", payload?.message ?? "Figma token is unauthorized.", { status }), status, rateLimit };
}
if (status === 404) {
return { ok: false, error: createError("FIGMA_NOT_FOUND", payload?.message ?? "Resource not found.", { status }), status, rateLimit };
}
if (status === 429 || status >= 500) {
if (attempt >= maxAttempts) {
return {
ok: false,
error: createError(status === 429 ? "FIGMA_RATE_LIMIT" : "NETWORK", payload?.message ?? "Figma request failed after maximum retries.", { status }),
status,
rateLimit
};
}
let waitMs = computeBackoffMs(attempt, initialDelayMs);
const resetHeader = response.headers.get("x-ratelimit-reset");
if (resetHeader) {
const asNumber = Number(resetHeader);
if (!Number.isNaN(asNumber)) {
const resetMs = asNumber * 1e3;
const delta = resetMs - Date.now();
if (delta > 0) waitMs = Math.max(waitMs, delta);
}
}
const jitter = Math.floor(Math.random() * 100);
lastWaitMs = waitMs + jitter;
await sleep(lastWaitMs);
continue;
}
return { ok: false, error: createError("INTERNAL", payload?.message ?? "Unexpected error from Figma API.", { status }), status, rateLimit };
}
return {
ok: false,
error: createError("NETWORK", "Unable to reach Figma API."),
status: null,
rateLimit: { remaining: null, resetAt: null, attempts: maxAttempts, lastWaitMs }
};
}
// coding-tools/figma-tools/js/src/get-metadata.ts
var TOOL_NAME = "get-metadata";
function log(message, verbose) {
if (verbose) {
process.stderr.write(`[${TOOL_NAME}] ${message}
`);
}
}
function toOptionalString(value) {
return typeof value === "string" && value.length > 0 ? value : null;
}
function exitWithEnvelope(envelope, errors = []) {
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
function mapNode(node, index = 0, parentId = null) {
const children = Array.isArray(node.children) ? node.children.map((child, idx) => mapNode(child, idx, node.id)) : [];
return {
id: node.id,
name: node.name,
type: node.type,
visible: node.visible ?? true,
locked: node.locked ?? false,
index,
parentId,
characters: node.characters ?? null,
blendMode: node.blendMode ?? null,
opacity: node.opacity ?? 1,
isMask: node.isMask ?? false,
relativeTransform: node.relativeTransform ?? null,
absoluteBoundingBox: node.absoluteBoundingBox ?? null,
size: node.size ?? null,
fills: node.fills ?? [],
strokes: node.strokes ?? [],
strokeWeight: node.strokeWeight ?? null,
strokeAlign: node.strokeAlign ?? null,
effects: node.effects ?? [],
constraints: node.constraints ?? null,
layoutAlign: node.layoutAlign ?? null,
layoutGrow: node.layoutGrow ?? null,
layoutMode: node.layoutMode ?? null,
primaryAxisSizingMode: node.primaryAxisSizingMode ?? null,
counterAxisSizingMode: node.counterAxisSizingMode ?? null,
primaryAxisAlignItems: node.primaryAxisAlignItems ?? null,
counterAxisAlignItems: node.counterAxisAlignItems ?? null,
itemSpacing: node.itemSpacing ?? null,
paddingLeft: node.paddingLeft ?? null,
paddingRight: node.paddingRight ?? null,
paddingTop: node.paddingTop ?? null,
paddingBottom: node.paddingBottom ?? null,
clipsContent: node.clipsContent ?? false,
layoutGrids: node.layoutGrids ?? [],
exportSettings: node.exportSettings ?? [],
transitionNodeID: node.transitionNodeID ?? null,
overlayPositionType: node.overlayPositionType ?? null,
overlayRelativePosition: node.overlayRelativePosition ?? null,
children
};
}
function escapeXml(value) {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;").replace(/'/g, "&apos;");
}
function nodeToXml(node) {
const attrs = [
`id="${escapeXml(node.id)}"`,
node.type ? `type="${escapeXml(node.type)}"` : null,
node.name ? `name="${escapeXml(node.name)}"` : null,
node.visible === false ? 'visible="false"' : null,
node.locked ? 'locked="true"' : null,
node.parentId ? `parentId="${escapeXml(node.parentId)}"` : null,
node.absoluteBoundingBox ? `x="${node.absoluteBoundingBox.x ?? 0}" y="${node.absoluteBoundingBox.y ?? 0}" width="${node.absoluteBoundingBox.width ?? 0}" height="${node.absoluteBoundingBox.height ?? 0}"` : null
].filter(Boolean);
const childXml = node.children.map(nodeToXml).join("");
return `<node ${attrs.join(" ")}>${childXml}</node>`;
}
async function main() {
const args = parseArgs();
const verbose = Boolean(args.verbose ?? args.v);
const schemaVersion = toOptionalString(args["schema-version"]) ?? void 0;
const warnings = [];
const errors = [];
const token = process.env.FIGMA_ACCESS_TOKEN;
if (!token || !token.trim()) {
errors.push(createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is required but was not provided."));
const envelope2 = createEnvelope({
tool: TOOL_NAME,
input: { fileKey: null, nodeId: null, format: "json" },
warnings,
errors,
schemaVersion,
data: {}
});
exitWithEnvelope(envelope2, errors);
}
const urlInput = toOptionalString(args.url) ?? toOptionalString(args.u);
let fileKey = toOptionalString(args["file-key"]) ?? void 0;
let nodeId = ensureNodeId(toOptionalString(args["node-id"]));
if (urlInput) {
const parsed = parseFigmaUrl(urlInput);
fileKey = fileKey || parsed.fileKey || void 0;
nodeId = nodeId || parsed.nodeId;
}
let format = String(args.format ?? "json").toLowerCase();
let outputMode;
if (format === "json" || format === "xml" || format === "both") {
outputMode = format;
} else {
warnings.push(`Unknown format "${format}". Defaulting to json.`);
outputMode = "json";
}
const input = {
fileKey: fileKey ?? null,
nodeId: nodeId ?? null,
format: outputMode
};
if (!fileKey) {
errors.push(createError("INPUT_INVALID", "A valid Figma file key is required (--file-key or --url)."));
}
if (!nodeId) {
errors.push(createError("INPUT_INVALID", "A valid Figma node id is required (--node-id or --url with node-id)."));
}
if (errors.length) {
const envelope2 = createEnvelope({
tool: TOOL_NAME,
input,
warnings,
errors,
data: {},
schemaVersion
});
exitWithEnvelope(envelope2, errors);
}
const resolvedFileKey = fileKey;
const resolvedNodeId = nodeId;
log(`Fetching metadata for node ${resolvedNodeId} in file ${resolvedFileKey}`, verbose);
const nodeResponse = await figmaRequest({
path: `/v1/files/${resolvedFileKey}/nodes`,
token,
searchParams: { ids: resolvedNodeId }
});
if (!nodeResponse.ok) {
errors.push(nodeResponse.error ?? createError("INTERNAL", "Failed to fetch node metadata."));
const envelope2 = createEnvelope({
tool: TOOL_NAME,
input,
warnings,
errors,
rateLimit: nodeResponse.rateLimit ?? void 0,
data: {},
schemaVersion
});
exitWithEnvelope(envelope2, errors);
}
const nodesMap = nodeResponse.data?.nodes ?? {};
const nodeWrapper = nodesMap[resolvedNodeId];
if (!nodeWrapper || !nodeWrapper.document) {
errors.push(createError("FIGMA_NOT_FOUND", `Node ${resolvedNodeId} was not found in file ${resolvedFileKey}.`));
const envelope2 = createEnvelope({
tool: TOOL_NAME,
input,
warnings,
errors,
rateLimit: nodeResponse.rateLimit ?? void 0,
data: {},
schemaVersion
});
exitWithEnvelope(envelope2, errors);
}
const rootNode = nodeWrapper.document;
const metadataTree = mapNode(rootNode);
let xmlDocument;
if (outputMode === "xml" || outputMode === "both") {
xmlDocument = `<figmaMetadata version="1.0">${nodeToXml(metadataTree)}</figmaMetadata>`;
}
const data = {
file: {
key: resolvedFileKey,
name: nodeResponse.data?.name ?? null,
lastModified: nodeResponse.data?.lastModified ?? null
},
metadata: metadataTree,
xml: xmlDocument
};
const envelope = createEnvelope({
tool: TOOL_NAME,
input,
data,
warnings,
errors,
rateLimit: nodeResponse.rateLimit ?? void 0,
schemaVersion
});
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
main().catch((error) => {
const message = error instanceof Error ? error.message : "Unknown error";
const envelope = createEnvelope({
tool: TOOL_NAME,
input: { fileKey: null, nodeId: null, format: "json" },
errors: [createError("INTERNAL", message, { stack: error instanceof Error ? error.stack : void 0 })],
data: {}
});
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(3);
});
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL191dGlscy9jbGktYXJncy50cyIsICIuLi9zcmMvX3V0aWxzL3VybC1wYXJzZS50cyIsICIuLi9zcmMvX3V0aWxzL2NvbmZpZy50cyIsICIuLi9zcmMvX3V0aWxzL2VudmVsb3BlLnRzIiwgIi4uL3NyYy9fdXRpbHMvZXJyb3JzLnRzIiwgIi4uL3NyYy9fdXRpbHMvaHR0cC1jbGllbnQudHMiLCAiLi4vc3JjL2dldC1tZXRhZGF0YS50cyJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiZXhwb3J0IHR5cGUgQ2xpQXJnVmFsdWUgPSBzdHJpbmcgfCBib29sZWFuO1xuXG5leHBvcnQgaW50ZXJmYWNlIENsaUFyZ3Mge1xuICBfOiBzdHJpbmdbXTtcbiAgW2tleTogc3RyaW5nXTogQ2xpQXJnVmFsdWUgfCBzdHJpbmdbXTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIHBhcnNlQXJncyhhcmd2OiBzdHJpbmdbXSA9IHByb2Nlc3MuYXJndi5zbGljZSgyKSk6IENsaUFyZ3Mge1xuICBjb25zdCBhcmdzOiBDbGlBcmdzID0geyBfOiBbXSB9O1xuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgYXJndi5sZW5ndGg7IGkgKz0gMSkge1xuICAgIGNvbnN0IGFyZyA9IGFyZ3ZbaV07XG5cbiAgICBpZiAoIWFyZy5zdGFydHNXaXRoKCctJykgfHwgYXJnID09PSAnLScpIHtcbiAgICAgIGFyZ3MuXy5wdXNoKGFyZyk7XG4gICAgICBjb250aW51ZTtcbiAgICB9XG5cbiAgICBpZ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IFJlY29yZDxzdHJpbmcsIHVua25vd24+LFxuICBURGF0YSA9IHVua25vd25cbj4ge1xuICB0b29sOiBzdHJpbmc7XG4gIGlucHV0PzogVElucHV0O1xuICBkYXRhPzogVERhdGE7XG4gIHdhcm5pbmdzPzogc3RyaW5nW107XG4gIGVycm9ycz86IFRvb2xFcnJvcltdO1xuICByYXRlTGltaXQ/OiBQYXJ0aWFsPFJhdGVMaW1pdE1ldGE+O1xuICBzY2hlbWFWZXJzaW9uPzogc3RyaW5nO1xufVxuXG5mdW5jdGlvbiBidWlsZFJhdGVMaW1pdE1ldGEocmF0ZUxpbWl0OiBQYXJ0aWFsPFJhdGVMaW1pdE1ldGE+ID0ge30pOiBSYXRlTGltaXRNZXRhIHtcbiAgcmV0dXJuIHtcbiAgICByZW1haW5pbmc6IHJhdGVMaW1pdC5yZW1haW5pbmcgPz8gbnVsbCxcbiAgICByZXNldEF0OiByYXRlTGltaXQucmVzZXRBdCA/PyBudWxsLFxuICAgIGF0dGVtcHRzOiByYXRlTGltaXQuYXR0ZW1wdHMgPz8gMSxcbiAgICBsYXN0V2FpdE1zOiByYXRlTGltaXQubGFzdFdhaXRNcyA/PyAwLFxuICB9O1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlRW52ZWxvcGU8XG4gIFRJbnB1dCBleHRlbmRzIFJlY29yZDxzdHJpbmcsI Line truncated
+387
View File
@@ -0,0 +1,387 @@
#!/usr/bin/env node
// coding-tools/figma-tools/js/src/get-screenshot.ts
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
// coding-tools/figma-tools/js/src/_utils/cli-args.ts
function parseArgs(argv = process.argv.slice(2)) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("-") || arg === "-") {
args._.push(arg);
continue;
}
if (arg === "--") {
const remaining = argv.slice(i + 1);
args._.push(...remaining);
break;
}
const [rawKey, inlineValue] = arg.split("=", 2);
const normalisedKey = rawKey.replace(/^-+/, "");
let value;
if (inlineValue !== void 0) {
value = inlineValue;
} else {
const next = argv[i + 1];
if (next !== void 0 && !next.startsWith("-")) {
value = next;
i += 1;
} else {
value = true;
}
}
args[normalisedKey] = value;
}
return args;
}
// coding-tools/figma-tools/js/src/_utils/url-parse.ts
var FILE_KEY_REGEX = /figma\.com\/(?:file|design)\/([A-Za-z0-9]+)\//i;
function parseFigmaUrl(input) {
if (!input) return { fileKey: null, nodeId: null };
try {
const url = new URL(input);
const match = url.href.match(FILE_KEY_REGEX);
const fileKey = match ? match[1] : null;
const nodeParam = url.searchParams.get("node-id");
const nodeId = nodeParam ? ensureNodeId(nodeParam) : null;
return { fileKey, nodeId };
} catch {
return { fileKey: null, nodeId: null };
}
}
function ensureNodeId(value) {
if (!value) return null;
const decoded = decodeURIComponent(value);
if (decoded.includes(":")) return decoded;
if (/^[0-9]+-[0-9]+$/.test(decoded)) {
const [left, right] = decoded.split("-", 2);
return `${left}:${right}`;
}
return decoded;
}
// coding-tools/figma-tools/js/src/_utils/config.ts
var config_default = {
schemaVersion: "1.0.0",
source: "agentic-coding-templates/figma-tools",
http: {
maxAttempts: 5,
initialDelayMs: 250
}
};
// coding-tools/figma-tools/js/src/_utils/envelope.ts
function buildRateLimitMeta(rateLimit = {}) {
return {
remaining: rateLimit.remaining ?? null,
resetAt: rateLimit.resetAt ?? null,
attempts: rateLimit.attempts ?? 1,
lastWaitMs: rateLimit.lastWaitMs ?? 0
};
}
function createEnvelope({
tool,
input = {},
data = {},
warnings = [],
errors = [],
rateLimit,
schemaVersion
}) {
return {
schemaVersion: schemaVersion ?? config_default.schemaVersion,
tool,
input,
meta: {
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
source: config_default.source,
rateLimit: buildRateLimitMeta(rateLimit)
},
data,
warnings,
errors
};
}
// coding-tools/figma-tools/js/src/_utils/errors.ts
var ERROR_EXIT_CODES = {
INPUT_INVALID: 1,
CONFIG_INVALID: 1,
FIGMA_AUTH: 1,
FIGMA_NOT_FOUND: 2,
FIGMA_RATE_LIMIT: 2,
NETWORK: 2,
INTERNAL: 3
};
function createError(code, message, detail) {
return {
code,
message,
detail: detail ?? null
};
}
function getExitCode(errors = []) {
if (!errors.length) {
return 0;
}
return errors.reduce((max, error) => {
const exitCode = ERROR_EXIT_CODES[error.code] ?? 1;
return Math.max(max, exitCode);
}, 0);
}
// coding-tools/figma-tools/js/src/_utils/http-client.ts
var BASE_URL = "https://api.figma.com";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseJsonSafely(text) {
try {
return text ? JSON.parse(text) : {};
} catch {
return { raw: text };
}
}
function parseRateLimit(headers, attempts, lastWaitMs) {
const remainingHeader = headers.get("x-ratelimit-remaining");
const resetHeader = headers.get("x-ratelimit-reset");
let remaining = null;
if (remainingHeader !== null && remainingHeader !== void 0) {
const parsed = Number(remainingHeader);
remaining = Number.isNaN(parsed) ? null : parsed;
}
let resetAt = null;
if (resetHeader) {
const numericReset = Number(resetHeader);
if (!Number.isNaN(numericReset)) {
resetAt = new Date(numericReset * 1e3).toISOString();
} else {
const date = new Date(resetHeader);
if (!Number.isNaN(date.valueOf())) {
resetAt = date.toISOString();
}
}
}
return {
remaining,
resetAt,
attempts,
lastWaitMs
};
}
function computeBackoffMs(attempt, initialDelayMs) {
return initialDelayMs * 2 ** (attempt - 1);
}
async function figmaRequest(options) {
const {
path: path2,
method = "GET",
token,
headers = {},
body,
searchParams,
maxAttempts = config_default.http?.maxAttempts ?? 5,
initialDelayMs = config_default.http?.initialDelayMs ?? 250
} = options;
if (!token) {
return {
ok: false,
error: createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is missing from the environment."),
status: null,
rateLimit: null
};
}
const url = new URL(path2, BASE_URL);
if (searchParams) {
Object.entries(searchParams).forEach(([key, value]) => {
if (value === void 0 || value === null) return;
url.searchParams.append(key, String(value));
});
}
let attempt = 0;
let lastWaitMs = 0;
while (attempt < maxAttempts) {
attempt += 1;
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
"X-Figma-Token": token,
...headers
},
body: body ? JSON.stringify(body) : void 0
});
const text = await response.text();
const payload = parseJsonSafely(text);
const rateLimit = parseRateLimit(response.headers, attempt, lastWaitMs);
if (response.ok) {
return { ok: true, data: payload, rateLimit };
}
const status = response.status;
if (status === 401 || status === 403) {
return { ok: false, error: createError("FIGMA_AUTH", payload?.message ?? "Figma token is unauthorized.", { status }), status, rateLimit };
}
if (status === 404) {
return { ok: false, error: createError("FIGMA_NOT_FOUND", payload?.message ?? "Resource not found.", { status }), status, rateLimit };
}
if (status === 429 || status >= 500) {
if (attempt >= maxAttempts) {
return {
ok: false,
error: createError(status === 429 ? "FIGMA_RATE_LIMIT" : "NETWORK", payload?.message ?? "Figma request failed after maximum retries.", { status }),
status,
rateLimit
};
}
let waitMs = computeBackoffMs(attempt, initialDelayMs);
const resetHeader = response.headers.get("x-ratelimit-reset");
if (resetHeader) {
const asNumber = Number(resetHeader);
if (!Number.isNaN(asNumber)) {
const resetMs = asNumber * 1e3;
const delta = resetMs - Date.now();
if (delta > 0) waitMs = Math.max(waitMs, delta);
}
}
const jitter = Math.floor(Math.random() * 100);
lastWaitMs = waitMs + jitter;
await sleep(lastWaitMs);
continue;
}
return { ok: false, error: createError("INTERNAL", payload?.message ?? "Unexpected error from Figma API.", { status }), status, rateLimit };
}
return {
ok: false,
error: createError("NETWORK", "Unable to reach Figma API."),
status: null,
rateLimit: { remaining: null, resetAt: null, attempts: maxAttempts, lastWaitMs }
};
}
// coding-tools/figma-tools/js/src/get-screenshot.ts
var TOOL_NAME = "get-screenshot";
var SUPPORTED_FORMATS = ["png", "jpg", "jpeg", "svg"];
var SCREENSHOT_DIR = ".tmp/figma-tools/screenshots";
function log(message, verbose) {
if (verbose) process.stderr.write(`[${TOOL_NAME}] ${message}
`);
}
function toOptionalString(value) {
return typeof value === "string" && value.length > 0 ? value : null;
}
function exitWithEnvelope(envelope, errors = []) {
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
async function ensureDirExists(dirPath) {
await mkdir(dirPath, { recursive: true });
}
async function main() {
const args = parseArgs();
const verbose = Boolean(args.verbose ?? args.v);
const schemaVersion = toOptionalString(args["schema-version"]) ?? void 0;
const warnings = [];
const errors = [];
const token = process.env.FIGMA_ACCESS_TOKEN;
if (!token || !token.trim()) {
errors.push(createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is required but was not provided."));
const envelope2 = createEnvelope({ tool: TOOL_NAME, input: { fileKey: null, nodeId: null, format: "jpg", scale: 1, bounds: "selection", background: "canvas" }, warnings, errors, schemaVersion, data: {} });
exitWithEnvelope(envelope2, errors);
}
const urlInput = toOptionalString(args.url) ?? toOptionalString(args.u);
let fileKey = toOptionalString(args["file-key"]) ?? void 0;
let nodeId = ensureNodeId(toOptionalString(args["node-id"]));
if (urlInput) {
const parsed = parseFigmaUrl(urlInput);
fileKey = fileKey || parsed.fileKey || void 0;
nodeId = nodeId || parsed.nodeId;
}
if (!fileKey) errors.push(createError("INPUT_INVALID", "A valid Figma file key is required (--file-key or --url)."));
if (!nodeId) errors.push(createError("INPUT_INVALID", "A valid Figma node id is required (--node-id or --url with node-id)."));
let format = String(args.format ?? "jpg").toLowerCase();
if (!SUPPORTED_FORMATS.includes(format)) {
warnings.push(`Unsupported format "${format}". Falling back to jpg.`);
format = "jpg";
}
if (format === "jpeg") format = "jpg";
const scaleInput = Number(args.scale ?? 1);
const scale = Number.isFinite(scaleInput) ? Math.min(Math.max(scaleInput, 0.01), 1) : 1;
const boundsInput = String(args.bounds ?? "selection").toLowerCase();
const bounds = ["selection", "frame", "node"].includes(boundsInput) ? boundsInput : "selection";
const useAbsoluteBounds = bounds === "frame";
const backgroundInput = String(args.background ?? "canvas").toLowerCase();
let backgroundParam;
if (backgroundInput === "transparent") backgroundParam = "00000000";
else if (/^[0-9a-f]{6,8}$/i.test(backgroundInput)) {
const value = backgroundInput.toUpperCase();
backgroundParam = value.length >= 6 ? value.slice(0, 8).padEnd(8, "F") : void 0;
} else if (backgroundInput.startsWith("#")) backgroundParam = backgroundInput.replace("#", "").slice(0, 8).padEnd(8, "F");
const input = { fileKey: fileKey ?? null, nodeId: nodeId ?? null, format, scale, bounds, background: backgroundInput };
if (errors.length) {
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
const resolvedFileKey = fileKey;
const resolvedNodeId = nodeId;
log(`Requesting image for ${resolvedNodeId} (${format}, scale ${scale})`, verbose);
const imageResponse = await figmaRequest({
path: `/v1/images/${resolvedFileKey}`,
token,
searchParams: { ids: resolvedNodeId, format, scale, use_absolute_bounds: useAbsoluteBounds ? "true" : void 0, background: backgroundParam }
});
if (!imageResponse.ok) {
errors.push(imageResponse.error ?? createError("INTERNAL", "Failed to request image export."));
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, rateLimit: imageResponse.rateLimit ?? void 0, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
const imageUrl = imageResponse.data?.images?.[resolvedNodeId];
if (!imageUrl) {
errors.push(createError("FIGMA_NOT_FOUND", "Figma did not return an image URL for the requested node."));
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, rateLimit: imageResponse.rateLimit ?? void 0, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
log("Downloading image", verbose);
let buffer = null;
let contentType = null;
try {
const res = await fetch(imageUrl);
if (!res.ok) errors.push(createError("NETWORK", `Unable to download image (status ${res.status}).`));
else {
contentType = res.headers.get("content-type");
buffer = format === "svg" ? Buffer.from(await res.text()) : Buffer.from(await res.arrayBuffer());
}
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown download error";
errors.push(createError("NETWORK", `Unable to download image: ${message}`));
}
if (!buffer || errors.length) {
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, rateLimit: imageResponse.rateLimit ?? void 0, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
const sanitizedNodeId = resolvedNodeId.replace(/[^a-zA-Z0-9-_]/g, "_");
const baseDir = path.resolve(SCREENSHOT_DIR, resolvedFileKey);
await ensureDirExists(baseDir);
const extension = format === "jpg" ? "jpg" : format;
const filePath = path.join(baseDir, `${sanitizedNodeId}.${extension}`);
await writeFile(filePath, buffer);
const data = {
file: { key: resolvedFileKey, nodeId: resolvedNodeId },
screenshot: { path: filePath, url: imageUrl, format: extension, scale, bounds, background: backgroundInput, contentType }
};
const envelope = createEnvelope({ tool: TOOL_NAME, input, data, warnings, errors, rateLimit: imageResponse.rateLimit ?? void 0, schemaVersion });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
main().catch((error) => {
const message = error instanceof Error ? error.message : "Unknown error";
const envelope = createEnvelope({ tool: TOOL_NAME, input: { fileKey: null, nodeId: null, format: "jpg", scale: 1, bounds: "selection", background: "canvas" }, errors: [createError("INTERNAL", message, { stack: error instanceof Error ? error.stack : void 0 })], data: {} });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(3);
});
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL2dldC1zY3JlZW5zaG90LnRzIiwgIi4uL3NyYy9fdXRpbHMvY2xpLWFyZ3MudHMiLCAiLi4vc3JjL191dGlscy91cmwtcGFyc2UudHMiLCAiLi4vc3JjL191dGlscy9jb25maWcudHMiLCAiLi4vc3JjL191dGlscy9lbnZlbG9wZS50cyIsICIuLi9zcmMvX3V0aWxzL2Vycm9ycy50cyIsICIuLi9zcmMvX3V0aWxzL2h0dHAtY2xpZW50LnRzIl0sCiAgInNvdXJjZXNDb250ZW50IjogWyIjIS91c3IvYmluL2VudiBub2RlXG5cbmltcG9ydCB7IG1rZGlyLCB3cml0ZUZpbGUgfSBmcm9tICdub2RlOmZzL3Byb21pc2VzJ1xuaW1wb3J0IHBhdGggZnJvbSAnbm9kZTpwYXRo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GcnIH1cbiAgaWYgKGZvcm1hdCA9PT0gJ2pwZWcnKSBmb3JtYXQgPSAnanBnJ1xuXG4gIGNvbnN0IHNjYWxlSW5wdXQgPSBOdW1iZXIoYXJncy5zY2FsZSA/PyAxKVxuICBjb25zdCBzY2FsZSA9IE51bWJlci5pc0Zpbml0ZShzY2FsZUluc Line truncated
+404
View File
@@ -0,0 +1,404 @@
#!/usr/bin/env node
// coding-tools/figma-tools/js/src/_utils/cli-args.ts
function parseArgs(argv = process.argv.slice(2)) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("-") || arg === "-") {
args._.push(arg);
continue;
}
if (arg === "--") {
const remaining = argv.slice(i + 1);
args._.push(...remaining);
break;
}
const [rawKey, inlineValue] = arg.split("=", 2);
const normalisedKey = rawKey.replace(/^-+/, "");
let value;
if (inlineValue !== void 0) {
value = inlineValue;
} else {
const next = argv[i + 1];
if (next !== void 0 && !next.startsWith("-")) {
value = next;
i += 1;
} else {
value = true;
}
}
args[normalisedKey] = value;
}
return args;
}
// coding-tools/figma-tools/js/src/_utils/url-parse.ts
var FILE_KEY_REGEX = /figma\.com\/(?:file|design)\/([A-Za-z0-9]+)\//i;
function parseFigmaUrl(input) {
if (!input) return { fileKey: null, nodeId: null };
try {
const url = new URL(input);
const match = url.href.match(FILE_KEY_REGEX);
const fileKey = match ? match[1] : null;
const nodeParam = url.searchParams.get("node-id");
const nodeId = nodeParam ? ensureNodeId(nodeParam) : null;
return { fileKey, nodeId };
} catch {
return { fileKey: null, nodeId: null };
}
}
function ensureNodeId(value) {
if (!value) return null;
const decoded = decodeURIComponent(value);
if (decoded.includes(":")) return decoded;
if (/^[0-9]+-[0-9]+$/.test(decoded)) {
const [left, right] = decoded.split("-", 2);
return `${left}:${right}`;
}
return decoded;
}
// coding-tools/figma-tools/js/src/_utils/config.ts
var config_default = {
schemaVersion: "1.0.0",
source: "agentic-coding-templates/figma-tools",
http: {
maxAttempts: 5,
initialDelayMs: 250
}
};
// coding-tools/figma-tools/js/src/_utils/envelope.ts
function buildRateLimitMeta(rateLimit = {}) {
return {
remaining: rateLimit.remaining ?? null,
resetAt: rateLimit.resetAt ?? null,
attempts: rateLimit.attempts ?? 1,
lastWaitMs: rateLimit.lastWaitMs ?? 0
};
}
function createEnvelope({
tool,
input = {},
data = {},
warnings = [],
errors = [],
rateLimit,
schemaVersion
}) {
return {
schemaVersion: schemaVersion ?? config_default.schemaVersion,
tool,
input,
meta: {
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
source: config_default.source,
rateLimit: buildRateLimitMeta(rateLimit)
},
data,
warnings,
errors
};
}
// coding-tools/figma-tools/js/src/_utils/errors.ts
var ERROR_EXIT_CODES = {
INPUT_INVALID: 1,
CONFIG_INVALID: 1,
FIGMA_AUTH: 1,
FIGMA_NOT_FOUND: 2,
FIGMA_RATE_LIMIT: 2,
NETWORK: 2,
INTERNAL: 3
};
function createError(code, message, detail) {
return {
code,
message,
detail: detail ?? null
};
}
function getExitCode(errors = []) {
if (!errors.length) {
return 0;
}
return errors.reduce((max, error) => {
const exitCode = ERROR_EXIT_CODES[error.code] ?? 1;
return Math.max(max, exitCode);
}, 0);
}
// coding-tools/figma-tools/js/src/_utils/http-client.ts
var BASE_URL = "https://api.figma.com";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseJsonSafely(text) {
try {
return text ? JSON.parse(text) : {};
} catch {
return { raw: text };
}
}
function parseRateLimit(headers, attempts, lastWaitMs) {
const remainingHeader = headers.get("x-ratelimit-remaining");
const resetHeader = headers.get("x-ratelimit-reset");
let remaining = null;
if (remainingHeader !== null && remainingHeader !== void 0) {
const parsed = Number(remainingHeader);
remaining = Number.isNaN(parsed) ? null : parsed;
}
let resetAt = null;
if (resetHeader) {
const numericReset = Number(resetHeader);
if (!Number.isNaN(numericReset)) {
resetAt = new Date(numericReset * 1e3).toISOString();
} else {
const date = new Date(resetHeader);
if (!Number.isNaN(date.valueOf())) {
resetAt = date.toISOString();
}
}
}
return {
remaining,
resetAt,
attempts,
lastWaitMs
};
}
function computeBackoffMs(attempt, initialDelayMs) {
return initialDelayMs * 2 ** (attempt - 1);
}
async function figmaRequest(options) {
const {
path,
method = "GET",
token,
headers = {},
body,
searchParams,
maxAttempts = config_default.http?.maxAttempts ?? 5,
initialDelayMs = config_default.http?.initialDelayMs ?? 250
} = options;
if (!token) {
return {
ok: false,
error: createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is missing from the environment."),
status: null,
rateLimit: null
};
}
const url = new URL(path, BASE_URL);
if (searchParams) {
Object.entries(searchParams).forEach(([key, value]) => {
if (value === void 0 || value === null) return;
url.searchParams.append(key, String(value));
});
}
let attempt = 0;
let lastWaitMs = 0;
while (attempt < maxAttempts) {
attempt += 1;
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
"X-Figma-Token": token,
...headers
},
body: body ? JSON.stringify(body) : void 0
});
const text = await response.text();
const payload = parseJsonSafely(text);
const rateLimit = parseRateLimit(response.headers, attempt, lastWaitMs);
if (response.ok) {
return { ok: true, data: payload, rateLimit };
}
const status = response.status;
if (status === 401 || status === 403) {
return { ok: false, error: createError("FIGMA_AUTH", payload?.message ?? "Figma token is unauthorized.", { status }), status, rateLimit };
}
if (status === 404) {
return { ok: false, error: createError("FIGMA_NOT_FOUND", payload?.message ?? "Resource not found.", { status }), status, rateLimit };
}
if (status === 429 || status >= 500) {
if (attempt >= maxAttempts) {
return {
ok: false,
error: createError(status === 429 ? "FIGMA_RATE_LIMIT" : "NETWORK", payload?.message ?? "Figma request failed after maximum retries.", { status }),
status,
rateLimit
};
}
let waitMs = computeBackoffMs(attempt, initialDelayMs);
const resetHeader = response.headers.get("x-ratelimit-reset");
if (resetHeader) {
const asNumber = Number(resetHeader);
if (!Number.isNaN(asNumber)) {
const resetMs = asNumber * 1e3;
const delta = resetMs - Date.now();
if (delta > 0) waitMs = Math.max(waitMs, delta);
}
}
const jitter = Math.floor(Math.random() * 100);
lastWaitMs = waitMs + jitter;
await sleep(lastWaitMs);
continue;
}
return { ok: false, error: createError("INTERNAL", payload?.message ?? "Unexpected error from Figma API.", { status }), status, rateLimit };
}
return {
ok: false,
error: createError("NETWORK", "Unable to reach Figma API."),
status: null,
rateLimit: { remaining: null, resetAt: null, attempts: maxAttempts, lastWaitMs }
};
}
// coding-tools/figma-tools/js/src/get-variable-definitions.ts
var TOOL_NAME = "get-variable-definitions";
function log(message, verbose) {
if (verbose) process.stderr.write(`[${TOOL_NAME}] ${message}
`);
}
function toOptionalString(value) {
return typeof value === "string" && value.length > 0 ? value : null;
}
function exitWithEnvelope(envelope, errors = []) {
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
function resolveCollectionName(id, collections) {
if (!id) return null;
const entry = collections.find((c) => c.id === id);
return entry?.name ?? null;
}
function buildVariableEntry(variable, collections, sets) {
return {
id: variable.id,
name: variable.name,
key: variable.key,
resolvedType: variable.resolvedType,
collectionId: variable.collectionId ?? variable.variableCollectionId ?? null,
collectionName: resolveCollectionName(variable.collectionId ?? variable.variableCollectionId, collections),
variableSetId: variable.variableSetId ?? null,
variableSetName: resolveCollectionName(variable.variableSetId, sets),
scopes: variable.scopes ?? [],
description: variable.description ?? null,
defaultValue: variable.valuesByMode?.[variable.defaultModeId ?? ""] ?? null,
valuesByMode: variable.valuesByMode ?? {}
};
}
function partitionVariables(list) {
const colors = [];
const spacing = [];
const typography = [];
const others = [];
for (const entry of list) {
switch (entry.resolvedType) {
case "COLOR":
colors.push(entry);
break;
case "FLOAT":
spacing.push(entry);
break;
case "STRING":
case "BOOLEAN":
typography.push(entry);
break;
default:
others.push(entry);
}
}
return { colors, spacing, typography, others };
}
function extractStyles(payload) {
if (!payload) return [];
if (Array.isArray(payload.styles)) return payload.styles;
if (payload.meta?.styles) return Object.values(payload.meta.styles);
return [];
}
async function main() {
const args = parseArgs();
const verbose = Boolean(args.verbose ?? args.v);
const schemaVersion = toOptionalString(args["schema-version"]) ?? void 0;
const warnings = [];
const errors = [];
const token = process.env.FIGMA_ACCESS_TOKEN;
if (!token || !token.trim()) {
errors.push(createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is required but was not provided."));
const envelope2 = createEnvelope({
tool: TOOL_NAME,
input: { fileKey: null, includeStyles: false },
warnings,
errors,
schemaVersion,
data: {}
});
exitWithEnvelope(envelope2, errors);
}
const urlInput = toOptionalString(args.url) ?? toOptionalString(args.u);
let fileKey = toOptionalString(args["file-key"]) ?? void 0;
if (urlInput) {
const parsed = parseFigmaUrl(urlInput);
fileKey = fileKey || parsed.fileKey || void 0;
}
const includeStyles = args["include-styles"] !== "false";
const input = { fileKey: fileKey ?? null, includeStyles };
if (!fileKey) {
errors.push(createError("INPUT_INVALID", "A valid Figma file key is required (--file-key or --url)."));
}
if (errors.length) {
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, data: {}, schemaVersion });
exitWithEnvelope(envelope2, errors);
}
const resolvedFileKey = fileKey;
log("Fetching variables", verbose);
const variablesResponse = await figmaRequest({
path: `/v1/files/${resolvedFileKey}/variables/local`,
token
});
let stylesResponse;
if (includeStyles) {
log("Fetching styles", verbose);
stylesResponse = await figmaRequest({ path: `/v1/files/${resolvedFileKey}/styles`, token });
} else {
stylesResponse = { ok: true, data: { styles: [] }, rateLimit: null };
}
if (!variablesResponse.ok) {
errors.push(variablesResponse.error ?? createError("INTERNAL", "Failed to fetch variables."));
const envelope2 = createEnvelope({ tool: TOOL_NAME, input, warnings, errors, rateLimit: variablesResponse.rateLimit ?? void 0, schemaVersion, data: {} });
exitWithEnvelope(envelope2, errors);
}
if (!stylesResponse.ok) {
warnings.push(stylesResponse.error?.message ?? "Failed to fetch styles.");
}
const variablesPayload = variablesResponse.data ?? {};
const variableCollections = variablesPayload.collections ?? [];
const variableSets = variablesPayload.variableCollections ?? [];
const variables = variablesPayload.variables ?? [];
const normalisedVariables = variables.map((v) => buildVariableEntry(v, variableCollections, variableSets));
const partitions = partitionVariables(normalisedVariables);
const styles = stylesResponse.ok ? extractStyles(stylesResponse.data) : [];
const data = {
file: { key: resolvedFileKey },
variables: partitions,
rawVariables: normalisedVariables,
styles
};
const envelope = createEnvelope({ tool: TOOL_NAME, input, data, warnings, errors, rateLimit: variablesResponse.rateLimit ?? void 0, schemaVersion });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
main().catch((error) => {
const message = error instanceof Error ? error.message : "Unknown error";
const envelope = createEnvelope({ tool: TOOL_NAME, input: { fileKey: null, includeStyles: false }, errors: [createError("INTERNAL", message, { stack: error instanceof Error ? error.stack : void 0 })], data: {} });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(3);
});
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL191dGlscy9jbGktYXJncy50cyIsICIuLi9zcmMvX3V0aWxzL3VybC1wYXJzZS50cyIsICIuLi9zcmMvX3V0aWxzL2NvbmZpZy50cyIsICIuLi9zcmMvX3V0aWxzL2VudmVsb3BlLnRzIiwgIi4uL3NyYy9fdXRpbHMvZXJyb3JzLnRzIiwgIi4uL3NyYy9fdXRpbHMvaHR0cC1jbGllbnQudHMiLCAiLi4vc3JjL2dldC12YXJpYWJsZS1kZWZpbml0aW9ucy50cyJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiZXhwb3J0IHR5cGUgQ2xpQXJnVmFsdWUgPSBzdHJpbmcgfCBib29sZWFuO1xuXG5leHBvcnQgaW50ZXJmYWNlIENsaUFyZ3Mge1xuICBfOiBzdHJpbmdbXTtcbiAgW2tleTogc3RyaW5nXTogQ2xpQXJnVmFsdWUgfCBzdHJpbmdbXTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIHBhcnNlQXJncyhhcmd2OiBzdHJpbmdbXSA9IHByb2Nlc3MuYXJndi5zbGljZSgyKSk6IENsaUFyZ3Mge1xuICBjb25zdCBhcmdzO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b3VyY2U6IHN0cmluZztcbiAgICByYXRlTGltaXQ6IFJhdGVMaW1pdE1ldGE7XG4gIH07XG4gIGRhdGE6IFREYXRhO1xuICB3YXJuaW5nczogc3RyaW5nW107XG4gIGVycm9yczogVG9vbEVycm9yW107XG59XG5cbmV4cG9ydCBpbnRlcmZhY2UgQ3JlYXRlRW52ZWxvcGVPcHRpb25zPFxuICBUSW5wdXQgZXh0ZW5kcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiA9IFJlY29yZDxzdHJpbmcsIHVua25vd24+LFxuICBURGF0YSA9IHVua25vd25cbj4ge1xuICB0b29sOiBzdHJpbmc7XG4gIGlucHV0PzogVElucHV0O1xuICBkYXRhPzogVERhdGE7XG4gIHdhcm5pbmdzPzogc3RyaW5nW107XG4gIGVycm9ycz86IFRvb2xFcnJvcltdO1xuICByYXRlTGltaXQ/OiBQYXJ0aWFsPFJhdGVMaW1pdE1ldGE+O1xuICBzY2hlbWFWZXJzaW9uPzogc3RyaW5nO1xufVxuXG5mdW5jdGlvbiBidWlsZFJhdGVMaW1pdE1ldGEocmF0ZUxpbWl0OiBQYXJ0aWFsPFJhdGVMaW1pdE1ldGE+ID0ge30pOiBSYXRlTGltaXRNZXRhIHtcbiAgcmV0dXJuIHtcbiAgICByZW1haW5pbmc6IHJhdGVMaW1pdC5yZW1haW5pbmcgPz8gbnVsbCxcbiAgICByZXNldEF0OiByYXRlTGltaXQucmVzZXRBdCA/PyBudWxsLFxuICAgIGF0dGVtcHRzOiByYXRlTGltaXQuYXR0ZW1wdHMgPz8gMSxcbiAgICBsYXN0V2FpdE1zOiByYXRlTGltaXQubGFzdFdhaXRNcyA/PyAwLFxuICB9O1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlRW52ZWxvcGU8XG4gIFRJbnB1dCBleHRlbmRzIFJlY Line truncated
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env node
// coding-tools/figma-tools/js/src/_utils/cli-args.ts
function parseArgs(argv = process.argv.slice(2)) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("-") || arg === "-") {
args._.push(arg);
continue;
}
if (arg === "--") {
const remaining = argv.slice(i + 1);
args._.push(...remaining);
break;
}
const [rawKey, inlineValue] = arg.split("=", 2);
const normalisedKey = rawKey.replace(/^-+/, "");
let value;
if (inlineValue !== void 0) {
value = inlineValue;
} else {
const next = argv[i + 1];
if (next !== void 0 && !next.startsWith("-")) {
value = next;
i += 1;
} else {
value = true;
}
}
args[normalisedKey] = value;
}
return args;
}
// coding-tools/figma-tools/js/src/_utils/config.ts
var config_default = {
schemaVersion: "1.0.0",
source: "agentic-coding-templates/figma-tools",
http: {
maxAttempts: 5,
initialDelayMs: 250
}
};
// coding-tools/figma-tools/js/src/_utils/envelope.ts
function buildRateLimitMeta(rateLimit = {}) {
return {
remaining: rateLimit.remaining ?? null,
resetAt: rateLimit.resetAt ?? null,
attempts: rateLimit.attempts ?? 1,
lastWaitMs: rateLimit.lastWaitMs ?? 0
};
}
function createEnvelope({
tool,
input = {},
data = {},
warnings = [],
errors = [],
rateLimit,
schemaVersion
}) {
return {
schemaVersion: schemaVersion ?? config_default.schemaVersion,
tool,
input,
meta: {
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
source: config_default.source,
rateLimit: buildRateLimitMeta(rateLimit)
},
data,
warnings,
errors
};
}
// coding-tools/figma-tools/js/src/_utils/errors.ts
var ERROR_EXIT_CODES = {
INPUT_INVALID: 1,
CONFIG_INVALID: 1,
FIGMA_AUTH: 1,
FIGMA_NOT_FOUND: 2,
FIGMA_RATE_LIMIT: 2,
NETWORK: 2,
INTERNAL: 3
};
function createError(code, message, detail) {
return {
code,
message,
detail: detail ?? null
};
}
function getExitCode(errors = []) {
if (!errors.length) {
return 0;
}
return errors.reduce((max, error) => {
const exitCode = ERROR_EXIT_CODES[error.code] ?? 1;
return Math.max(max, exitCode);
}, 0);
}
// coding-tools/figma-tools/js/src/_utils/http-client.ts
var BASE_URL = "https://api.figma.com";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseJsonSafely(text) {
try {
return text ? JSON.parse(text) : {};
} catch {
return { raw: text };
}
}
function parseRateLimit(headers, attempts, lastWaitMs) {
const remainingHeader = headers.get("x-ratelimit-remaining");
const resetHeader = headers.get("x-ratelimit-reset");
let remaining = null;
if (remainingHeader !== null && remainingHeader !== void 0) {
const parsed = Number(remainingHeader);
remaining = Number.isNaN(parsed) ? null : parsed;
}
let resetAt = null;
if (resetHeader) {
const numericReset = Number(resetHeader);
if (!Number.isNaN(numericReset)) {
resetAt = new Date(numericReset * 1e3).toISOString();
} else {
const date = new Date(resetHeader);
if (!Number.isNaN(date.valueOf())) {
resetAt = date.toISOString();
}
}
}
return {
remaining,
resetAt,
attempts,
lastWaitMs
};
}
function computeBackoffMs(attempt, initialDelayMs) {
return initialDelayMs * 2 ** (attempt - 1);
}
async function figmaRequest(options) {
const {
path,
method = "GET",
token,
headers = {},
body,
searchParams,
maxAttempts = config_default.http?.maxAttempts ?? 5,
initialDelayMs = config_default.http?.initialDelayMs ?? 250
} = options;
if (!token) {
return {
ok: false,
error: createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN is missing from the environment."),
status: null,
rateLimit: null
};
}
const url = new URL(path, BASE_URL);
if (searchParams) {
Object.entries(searchParams).forEach(([key, value]) => {
if (value === void 0 || value === null) return;
url.searchParams.append(key, String(value));
});
}
let attempt = 0;
let lastWaitMs = 0;
while (attempt < maxAttempts) {
attempt += 1;
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
"X-Figma-Token": token,
...headers
},
body: body ? JSON.stringify(body) : void 0
});
const text = await response.text();
const payload = parseJsonSafely(text);
const rateLimit = parseRateLimit(response.headers, attempt, lastWaitMs);
if (response.ok) {
return { ok: true, data: payload, rateLimit };
}
const status = response.status;
if (status === 401 || status === 403) {
return { ok: false, error: createError("FIGMA_AUTH", payload?.message ?? "Figma token is unauthorized.", { status }), status, rateLimit };
}
if (status === 404) {
return { ok: false, error: createError("FIGMA_NOT_FOUND", payload?.message ?? "Resource not found.", { status }), status, rateLimit };
}
if (status === 429 || status >= 500) {
if (attempt >= maxAttempts) {
return {
ok: false,
error: createError(status === 429 ? "FIGMA_RATE_LIMIT" : "NETWORK", payload?.message ?? "Figma request failed after maximum retries.", { status }),
status,
rateLimit
};
}
let waitMs = computeBackoffMs(attempt, initialDelayMs);
const resetHeader = response.headers.get("x-ratelimit-reset");
if (resetHeader) {
const asNumber = Number(resetHeader);
if (!Number.isNaN(asNumber)) {
const resetMs = asNumber * 1e3;
const delta = resetMs - Date.now();
if (delta > 0) waitMs = Math.max(waitMs, delta);
}
}
const jitter = Math.floor(Math.random() * 100);
lastWaitMs = waitMs + jitter;
await sleep(lastWaitMs);
continue;
}
return { ok: false, error: createError("INTERNAL", payload?.message ?? "Unexpected error from Figma API.", { status }), status, rateLimit };
}
return {
ok: false,
error: createError("NETWORK", "Unable to reach Figma API."),
status: null,
rateLimit: { remaining: null, resetAt: null, attempts: maxAttempts, lastWaitMs }
};
}
// coding-tools/figma-tools/js/src/whoami.ts
var TOOL_NAME = "whoami";
function log(message, verbose) {
if (verbose) process.stderr.write(`[${TOOL_NAME}] ${message}
`);
}
async function main() {
const args = parseArgs();
const verbose = Boolean(args.verbose ?? args.v);
log("Starting...", verbose);
const warnings = [];
const errors = [];
const token = process.env.FIGMA_ACCESS_TOKEN;
if (!token || !token.trim()) {
errors.push(createError("FIGMA_AUTH", "FIGMA_ACCESS_TOKEN must be set in environment."));
}
let envelope = createEnvelope({ tool: TOOL_NAME, warnings, errors });
if (errors.length > 0) {
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
const result = await figmaRequest({ path: "/v1/me", token });
if (!result.ok) {
errors.push(result.error);
envelope = createEnvelope({ tool: TOOL_NAME, warnings, errors, rateLimit: result.rateLimit ?? void 0 });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(getExitCode(errors));
}
envelope = createEnvelope({ tool: TOOL_NAME, data: result.data, warnings, errors, rateLimit: result.rateLimit });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(0);
}
main().catch((error) => {
const message = error instanceof Error ? error.message : "Unknown error";
const envelope = createEnvelope({ tool: TOOL_NAME, input: {}, errors: [createError("INTERNAL", message)] });
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
`);
process.exit(3);
});
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL191dGlscy9jbGktYXJncy50cyIsICIuLi9zcmMvX3V0aWxzL2NvbmZpZy50cyIsICIuLi9zcmMvX3V0aWxzL2VudmVsb3BlLnRzIiwgIi4uL3NyYy9fdXRpbHMvZXJyb3JzLnRzIiwgIi4uL3NyYy9fdXRpbHMvaHR0cC1jbGllbnQudHMiLCAiLi4vc3JjL3dob2FtaS50cyJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiZXhwb3J0IHR5cGUgQ2xpQXJnVmFsdWUgPSBzdHJpbmcgfCBib29sZWFuO1xuXG5leHBvcnQgaW50ZXJmYWNlIENsaUFyZ3Mge1xuICBfOiBzdHJpbmdbXTtcbiAgW2tleTogc3RyaW5nXTogQ2xpQXJnVmFsdWUgfCBzdHJpbmdbXTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIHBhcnNlQXJncyhhcmd2OiBzdHJpbmdbXSA9IHByb2Nlc3MuYXJndi5zbGljZSgyKSk6IENsaUFyZ3Mge1xuICBjb25zdCBhcmdzOiBDbGlBcmdzID0geyBfOiBbXSB9O1xuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgYXJndi5sZW5ndGg7IGkgKz0gMSkge1xuICAgIGNvbnN0IGFyZyA9IGFyZ3ZbaV07XG5cbiAgICBpZiAoIWFyZy5zdGFydHNXaXRoKCctJykgfHwgYXJnID09PSAnLScpIHtcbiAgICAgIGFyZ3MuXy5wdXNo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