anima-pack
Anima design-to-code operator pack with 18 Grade-A skills
Installation
Open Claude Code and run this command:
/plugin install anima-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
What It Does
> Validated Anima workflows for authorized Figma, website, and prompt-to-code operations (18 skills)
These skills use @animaapp/anima-sdk 0.27.0 and its current backend contract. They cover Figma generation, public website conversion, early-preview prompt generation, secure deployment, reliability, and governed output review. Current framework targets are React and HTML; Vue is not advertised by this SDK version.
Skills (18) plugin-local skills
Configure CI/CD pipeline for automated Figma-to-code generation with Anima.
Anima CI Integration
Overview
This workflow turns explicitly approved Figma nodes into a reviewable generated code change. The CI identity receives design credentials only at runtime and must never merge or deploy generated output without the repository’s normal quality and ownership controls.
Prerequisites
- A read-only Anima/Figma integration token stored as CI secrets and limited to the intended design file.
- An allowlisted component/node registry, deterministic output directory, and generated-code ownership/review policy.
- A branch workflow that validates generated output before any human-approved merge; scheduled generation alone is not release authorization.
Instructions
Step 1: GitHub Actions Workflow
# .github/workflows/design-sync.yml
name: Design-to-Code Sync
on:
schedule:
- cron: '0 9 * * 1-5' # Weekdays at 9am
workflow_dispatch: # Manual trigger
jobs:
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '20' }
- run: npm ci
- name: Generate components from Figma
env:
ANIMA_TOKEN: ${{ secrets.ANIMA_TOKEN }}
FIGMA_TOKEN: ${{ secrets.FIGMA_TOKEN }}
FIGMA_FILE_KEY: ${{ secrets.FIGMA_FILE_KEY }}
run: npx tsx scripts/generate-components.ts
- name: Lint generated code
run: npx eslint src/components/generated/ --fix
- name: Check for changes
id: changes
run: |
if git diff --quiet src/components/generated/; then
echo "changed=false" >> $GITHUB_OUTPUT
else
echo "changed=true" >> $GITHUB_OUTPUT
fi
- name: Create PR with generated components
if: steps.changes.outputs.changed == 'true'
run: |
git checkout -b design-sync/$(date +%Y%m%d)
git add src/components/generated/
git commit -m "chore: sync generated components from Figma"
git push -u origin HEAD
gh pr create --title "Design sync: updated generated components" \
--body "Auto-generated from Figma via Anima SDK"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Step 2: Generation Script for CI
// scripts/generate-components.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
import path from 'path';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
const COMPONENTS = [
{ nodeId: '1:2', name: 'Hero' },
{ nodeId: '3:4', name: 'Card' },
{ nodeId: '5:6', name: 'Navigation' },
];
async function main() {
const outputDir = 'src/components/generated';
f…Diagnose and fix common Anima SDK design-to-code errors.
Anima Common Errors
Overview
Use this guide to diagnose design-to-code failures without widening design-file access or leaking tokens. Start from a reproducible file/node/settings tuple and use a least-privilege development credential for all verification.
Prerequisites
- A sanitized error record with the design file identifier, node identifier, selected generation settings, timestamp, and request ID where available.
- Scoped Anima and Figma credentials held in a secret store; never paste a personal access token into a ticket, source file, or shared diagnostic log.
- A staging or disposable design fixture so fixes can be reproduced without mutating a production design file.
Instructions
- Classify the failure as authentication, file/node resolution, generator configuration, timeout/rate limit, or rendered-output quality.
- Reproduce it with the smallest approved frame/component and the diagnostic commands, capturing only sanitized results.
- Correct the matching design input, entitlement, or generation configuration and rerun only that fixture.
- Validate the generated file location, lint/build result, and visual review before updating a broader component set.
Error Reference
Authentication Errors
| Error | Root Cause | Fix |
|---|---|---|
Invalid Anima token |
Token not provisioned or expired | Request new token from Anima team |
Invalid Figma token |
PAT expired or revoked | Generate new PAT: Figma > Settings > Access Tokens |
Unauthorized |
Token lacks file access | Ensure Figma PAT has file read permission |
File & Node Errors
| Error | Root Cause | Fix |
|---|---|---|
File not found |
Wrong file key | Extract from Figma URL: figma.com/file/{KEY}/... |
Node not found |
Invalid node ID | Copy node link from Figma: right-click > Copy link |
No renderable content |
Selected a page or group | Select a frame, component, or component set |
Empty files record |
Node is empty or hidden | Unhide layers; ensure node has visible content |
Code Generation Errors
// Classify without printing provider messages, which can contain source details.
async function safeGenerate(anima: Anima, params: Parameters<Anima['generateCode']>[0]) {
try {
return await anima.generateCode(params);
} catch (error: unknown) {
const status = typeof error === 'object' && error !== null …Build automated Figma-to-React pipeline with the Anima SDK.
Anima Core Workflow A — Figma-to-React Pipeline
Overview
Build a review-driven Figma-to-React pipeline. Detect an approved source revision, generate only allowlisted nodes, contain the output, and open a review change; never turn a Figma change directly into merged or deployed application code.
Prerequisites
- Completed
anima-install-authsetup - Figma file with organized components (auto-layout recommended)
- React project (Next.js, Vite, or CRA)
Authentication
Create the Anima client only on the backend with ANIMA_TOKEN; pass a managed FIGMA_TOKEN for the allowlisted file to generateCode. Stop on either token's 401/403 result and correct access without widening the source allowlist.
Instructions
Step 1: Design System Scanner
// src/pipeline/figma-scanner.ts
import { Anima } from '@animaapp/anima-sdk';
interface FigmaComponent {
nodeId: string;
name: string;
type: 'COMPONENT' | 'FRAME' | 'COMPONENT_SET';
}
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
// Fetch all top-level components from a Figma page
async function scanFigmaComponents(fileKey: string) {
const response = await fetch(
`https://api.figma.com/v1/files/${fileKey}/components`,
{ headers: { 'X-Figma-Token': process.env.FIGMA_TOKEN! } }
);
const data = await response.json();
return data.meta.components.map((comp: any) => ({
nodeId: comp.node_id,
name: comp.name,
type: comp.containing_frame?.type || 'COMPONENT',
}));
}
Step 2: Batch Code Generator
// src/pipeline/batch-generator.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
import path from 'path';
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
interface GenerationConfig {
fileKey: string;
outputDir: string;
settings: {
language: 'typescript' | 'javascript';
framework: 'react' | 'html';
styling: 'plain_css' | 'tailwind' | 'inline_styles';
uiLibrary?: 'mui' | 'antd' | 'radix' | 'shadcn' | 'clean_react' | 'custom_design_system';
};
}
async function generateComponentBatch(
config: GenerationConfig,
nodeIds: string[],
): Promise<{ generated: number; failed: string[] }> {
const failed: string[] = [];
let generated = 0;
fs.mkdirSync(config.outputDir, { recursive: true });
// Generate each component (Anima processes one node at a time)
for (const nodeId of nodeIds) {
try {
const { files } = await anima.generateCode({
fileKey: config.fileKey,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: [nodeId],…Clone websites to React/HTML code and customize Anima output with AI.
Anima Core Workflow B — Website-to-Code & AI Customization
Overview
Convert an authorized public website with the current backend SDK, then review the result against rights, asset, dependency, accessibility, and output-containment policies. Use prompt generation only as an explicitly accepted early-preview path.
Prerequisites
- Completed
anima-install-authsetup - Written authority to reproduce the source site and its assets
- An allowlisted public URL; private sites require the licensed MHTML path and a separate sensitive-capture handling policy
Authentication
Instantiate the backend Anima client with a managed Anima token. Website and prompt requests do not use a browser-exposed credential; reject unauthorized callers and non-allowlisted source URLs before calling the SDK.
Instructions
Step 1: Website-to-Code Conversion
// src/workflows/website-to-code.ts
// Generate from an allowlisted public website you are authorized to reproduce.
import { Anima } from '@animaapp/anima-sdk';
import crypto from 'node:crypto';
const APPROVED_HOSTS = new Set(['docs.example.com']);
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
async function cloneWebsiteToReact(url: string) {
const source = new URL(url);
if (source.protocol !== 'https:' || !APPROVED_HOSTS.has(source.hostname)) {
throw new Error('Source URL is not approved');
}
return anima.generateCodeFromWebsite({
url: source.href,
settings: {
framework: 'react',
language: 'typescript',
styling: 'tailwind',
uiLibrary: 'shadcn',
},
tracking: { externalId: crypto.randomUUID() },
});
}
async function generateFromApprovedPrompt(prompt: string) {
if (prompt.length < 20 || prompt.length > 2_000) {
throw new Error('Prompt length is outside the approved range');
}
return anima.generateCodeFromPrompt({
prompt,
settings: {
framework: 'react',
language: 'typescript',
styling: 'tailwind',
uiLibrary: 'shadcn',
},
tracking: { externalId: crypto.randomUUID() },
});
}
Step 2: Post-Generation Customization
// src/workflows/customize-output.ts
interface CustomizationRule {
pattern: RegExp;
replacement: string;
description: string;
}
// Apply project-specific customizations to Anima output
function customizeGeneratedCode(
files: Record<string, { content: string; isBinary: boolean }>,
rules: CustomizationRule[],
): Record<string, { content: string; isBinary: boolean }> {
return Object.fromEntries(Object.entries(files).map(([fileName, file]) => {
if (file.isBinary) return [fileName, file];
let content = file.co…Optimize Anima API costs through caching, incremental generation, and tier selection.
Anima Cost Tuning
Overview
Optimize design-to-code generation by measuring approved usage, avoiding duplicate work, and retaining only reusable outputs. Treat cost projections as planning inputs until the account owner confirms current contractual terms.
Pricing Context
Do not infer price units from the SDK or marketing site. Obtain the current account agreement or usage report from the authorized owner and label every projection with its source date, currency, unit, and included allowance.
Prerequisites
- A current agreement or account report from the authorized Anima owner; do not infer consumption limits from the illustrative optimization table.
- Aggregate generation telemetry that records file/node identifiers, generation version, cache state, and duration without exposing design tokens or content.
- An explicit cache freshness and invalidation policy agreed by design and code owners so cached output cannot silently lag an approved design change.
Cost Optimization Strategies
| Strategy | Measure | Guardrail |
|---|---|---|
| Content-addressed reuse | Avoided duplicate generations | Bind source revision, node, SDK version, and settings |
| Incremental generation | Changed versus unchanged nodes | Regenerate when change state is unknown |
| Asset policy | Hosted versus external transfer | Follow security, retention, and licensing policy |
| Output reuse | Accepted reusable components | Revalidate after source or dependency changes |
Authentication
Read usage only through the account owner's authorized report or integration. Keep Anima and Figma credentials in the backend secret manager and aggregate telemetry before analysis so this workflow never receives token or design data.
Instructions
Step 1: Usage Tracker
// src/cost/usage-tracker.ts
interface GenerationRecord {
timestamp: string;
fileKey: string;
nodeId: string;
cached: boolean;
durationMs: number;
}
class AnimaUsageTracker {
private records: GenerationRecord[] = [];
record(entry: GenerationRecord): void { this.records.push(entry); }
getReport(): { total: number; cached: number; cacheHitRate: number | null } {
const total = this.records.length;
const cached = this.records.filter(r => r.cached).length;
return {
total,
cached,
cacheHitRate: total > 0 ? cached / total : null,
};
}
}
Step 2: Smart Generation Policy
// Only generate when:
// 1. Figma file version changed (check via Figma API)
// 2. The repository's reviewed cache-retention policy requires refresh
// 3. Settings changed (new framework/styling)
// 4. F…Collect Anima SDK debug evidence for support tickets and troubleshooting.
Anima Debug Bundle
Overview
Collect a narrowly scoped, redactable diagnostic artifact for a reproducible Anima or Figma integration failure. Review the file locally before sharing it: token-presence indicators are acceptable; credential values, private design content, and personal identity data are not.
Prerequisites
- A scoped development credential and a disposable/staging design fixture that reproduces the issue without exposing a customer or private production file.
- The expected file/node/settings tuple, timestamp, and sanitized error or request ID to correlate the bundle with the reported issue.
- A support-sharing review process and an owner able to rotate credentials if a diagnostic artifact is found to contain sensitive material.
Instructions
Build the bundle locally, inspect its exact fields, run a secret scan, and share it only after the support owner confirms that every value is safe.
Step 1: Generate Debug Bundle
// src/debug/anima-debug.ts
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
function errorClass(error: unknown): string {
return error instanceof Error ? error.name : 'UnknownError';
}
async function generateDebugBundle() {
const bundle = {
timestamp: new Date().toISOString(),
environment: {
nodeVersion: process.version,
sdkVersion: require('@animaapp/anima-sdk/package.json').version,
animaToken: process.env.ANIMA_TOKEN ? 'SET (redacted)' : 'NOT SET',
figmaToken: process.env.FIGMA_TOKEN ? 'SET (redacted)' : 'NOT SET',
},
figmaAccess: await testFigmaAccess(),
sdkLoad: await testSdkLoad(),
};
const outputDir = path.resolve(process.env.DEBUG_OUTPUT_DIR || '.private-debug');
fs.mkdirSync(outputDir, { recursive: true, mode: 0o700 });
const filename = path.join(outputDir, `anima-debug-${Date.now()}.json`);
fs.writeFileSync(filename, JSON.stringify(bundle, null, 2), { mode: 0o600, flag: 'wx' });
console.log({ debugBundleCreated: true, outputDir });
return bundle;
}
async function testFigmaAccess() {
try {
const res = await fetch('https://api.figma.com/v1/me', {
headers: { 'X-Figma-Token': process.env.FIGMA_TOKEN! },
});
return { status: res.ok ? 'ok' : 'failed', httpStatus: res.status };
} catch (error: unknown) {
return { status: 'failed', errorClass: errorClass(error) };
}
}
async function testSdkLoad() {
try {
const { Anima } = await import('@animaapp/anima-sdk');
new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
return { status: 'sdk_loaded', version: 'check package.json' };
} catch (error: unknown) {
return { status: …Deploy Anima design-to-code service as a backend API endpoint.
Anima Deploy Integration
Overview
Deploy the Anima SDK as a backend service. The SDK is server-side only, so deploy it behind an API endpoint that accepts Figma file/node references and returns generated code.
Prerequisites
- A private or authenticated service boundary with an allowlisted design-file registry; do not expose arbitrary
fileKeyandnodesIdgeneration to the public internet. - Managed Anima and Figma secrets, separate staging/production credentials, request limits, and an audit trail that excludes token values and design content.
- An approved generated-output path, validation pipeline, and rollback target for every deployment revision.
Instructions
Step 1: Express API Wrapper
// src/server.ts
import express from 'express';
import { Anima } from '@animaapp/anima-sdk';
const app = express();
app.use(express.json());
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
app.post('/api/generate', async (req, res) => {
const { fileKey, nodesId, settings } = req.body;
if (!fileKey || !nodesId?.length) {
return res.status(400).json({ error: 'fileKey and nodesId required' });
}
try {
const { files } = await anima.generateCode({
fileKey,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId,
settings: settings || { language: 'typescript', framework: 'react', styling: 'tailwind' },
});
res.json({ files, count: Object.keys(files).length });
} catch (err: any) {
res.status(502).json({ error: 'Generation failed', requestId: req.id });
}
});
app.get('/health', (_req, res) => res.json({ status: 'ok' }));
app.listen(3000, () => console.log('Anima service on :3000'));
Step 2: Vercel Serverless Function
// api/generate.ts
import { Anima } from '@animaapp/anima-sdk';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
export default async function handler(req: any, res: any) {
if (req.method !== 'POST') return res.status(405).end();
const { fileKey, nodesId, settings } = req.body;
const { files } = await anima.generateCode({
fileKey, figmaToken: process.env.FIGMA_TOKEN!, nodesId,
settings: settings || { language: 'typescript', framework: 'react', styling: 'tailwind' },
});
res.json({ files });
}
Step 3: Deploy Commands
# Vercel
vercel secrets add anima_token "$ANIMA_TOKEN"
vercel secrets add figma_token "$FIGMA_TOKEN"
vercel --prod
# Cloud Run
gcloud run deploy anima-service \
--source . \
--set-secrets=ANIMA_TOKEN=anima-token:latest,FIGMA_TOKEN=figma-token:latest \
--region us-central1 --no-allow-unauthenticated
…Generate reviewable React or HTML code from a Figma design using the Anima SDK.
Anima Hello World
Overview
Generate reviewable React or HTML from one approved Figma node with the backend-only @animaapp/anima-sdk. Keep credentials server-side and treat every generated file as untrusted output until its path, dependencies, build, and visual result pass review.
Prerequisites
- Completed
anima-install-authsetup - A Figma file with at least one frame/component
- Know your file key and node ID
Instructions
Step 1: Generate React + Tailwind Code
// src/hello-world.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
import path from 'path';
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
async function generateReactComponent() {
const { files } = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!, // From Figma URL
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: [process.env.FIGMA_NODE_ID!], // e.g., '1:2'
settings: {
language: 'typescript',
framework: 'react',
styling: 'tailwind',
// Omit uiLibrary for vanilla React, or select a supported library.
},
});
// Write generated files to disk
const outputDir = './generated';
fs.mkdirSync(outputDir, { recursive: true });
for (const [fileName, file] of Object.entries(files)) {
const filePath = path.resolve(outputDir, fileName);
if (!filePath.startsWith(`${path.resolve(outputDir)}${path.sep}`)) {
throw new Error(`Refusing output path: ${fileName}`);
}
if (file.isBinary) throw new Error(`Handle binary output separately: ${fileName}`);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, file.content, { flag: 'wx' });
console.log(`Generated: ${fileName} (${file.content.length} chars)`);
}
return files;
}
generateReactComponent().catch(() => {
console.error({ failureClass: 'generation-failed' });
process.exitCode = 1;
});
Step 2: Try Supported Output Settings
// Generate HTML with the SDK's plain_css setting.
const htmlFiles = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2'],
settings: {
language: 'javascript',
framework: 'html',
styling: 'plain_css',
},
});
// Generate React + shadcn/ui
const shadcnFiles = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2'],
settings: {
language: 'typescript',
framework: 'react',
styling: 'tailwind',
uiLibrary: 'shadcn',
},
});
Step 3: Inspect Generated Output
…
Install the Anima SDK and configure authentication for Figma-to-code generation.
Anima Install & Auth
Overview
Install the backend-only @animaapp/anima-sdk, bind managed Anima and Figma credentials, and prove one authorized React or HTML generation without exposing either token.
Prerequisites
- Node.js 20+ (SDK is server-side only)
- Figma account with API access
- Anima API token (request at animaapp.com)
- Figma Personal Access Token
Instructions
Step 1: Install the Anima SDK
npm install @animaapp/anima-sdk
Step 2: Get Your Tokens
# 1. Figma Personal Access Token:
# Figma > Settings > Account > Personal Access Tokens > Generate
# 2. Anima API Token:
# Request from Anima team (currently limited partner access)
# https://docs.animaapp.com/docs/anima-api
# Bind ANIMA_TOKEN and FIGMA_TOKEN with the runtime secret manager.
# Check presence without printing values.
test -n "$ANIMA_TOKEN" && test -n "$FIGMA_TOKEN"
Step 3: Initialize and Verify
// src/anima-client.ts
import { Anima } from '@animaapp/anima-sdk';
const anima = new Anima({
auth: {
token: process.env.ANIMA_TOKEN!,
},
});
// Verify connection by generating code from a known Figma file
async function verifySetup() {
try {
const { files } = await anima.generateCode({
fileKey: 'your-figma-file-key', // From Figma URL: figma.com/file/{fileKey}/...
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2'], // Specific node to convert
settings: {
language: 'typescript',
framework: 'react',
styling: 'tailwind',
},
});
console.log(`Generated ${Object.keys(files).length} files`);
for (const [fileName, file] of Object.entries(files)) {
console.log(` ${fileName} (${file.content.length} chars; binary=${file.isBinary})`);
}
return true;
} catch {
console.error({ failureClass: 'setup-verification-failed' });
return false;
}
}
verifySetup();
Step 4: Get Your Figma File Key
Figma URL format:
https://www.figma.com/file/ABC123xyz/My-Design?node-id=1:2
File Key: ABC123xyz
Node ID: 1:2 (from the URL query parameter)
Tool Discipline
Use Read and Grep to inspect the existing integration and generated diff before changing anything. Use Write or Edit only inside the approved generated-code, test, or configuration paths. Use the declared Bash commands only for the explicit install, validation, or diagnostic steps in this workflow; never print tokens, source designs, generated source, or private website captures.
Output
@animaapp/anima-sdkinstalled- Anima and Figma t…
Set up iterative design-to-code development loop with Anima SDK.
Anima Local Dev Loop
Overview
Iterate on one approved Figma node with supported React or HTML settings. Preserve the source revision and settings for each run, preview locally, and accept a result only after deterministic code and visual checks.
Prerequisites
- A staging Figma file and allowlisted node IDs, with scoped credentials loaded from an ignored local environment file or development secret store.
- A disposable generated-output directory that is not imported by the production application until code and visual review pass.
- Agreed comparison criteria for accessibility, design-token use, responsive behavior, dependencies, and generation settings.
Instructions
Step 1: Project Setup
mkdir anima-dev && cd anima-dev
npm init -y
npm install @animaapp/anima-sdk dotenv
npm install -D vite @vitejs/plugin-react typescript
Step 2: Generate and Preview Script
// scripts/generate-preview.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
import path from 'path';
import 'dotenv/config';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
const SETTINGS_PRESETS = {
'react-tailwind': { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const },
'react-shadcn': { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const, uiLibrary: 'shadcn' as const },
'react-plain-css': { language: 'typescript' as const, framework: 'react' as const, styling: 'plain_css' as const },
'html-plain-css': { language: 'javascript' as const, framework: 'html' as const, styling: 'plain_css' as const },
};
async function generateWithPreset(preset: keyof typeof SETTINGS_PRESETS, nodeId: string) {
const settings = SETTINGS_PRESETS[preset];
const outputDir = `./generated/${preset}`;
fs.mkdirSync(outputDir, { recursive: true });
const { files } = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: [nodeId],
settings,
});
for (const [fileName, file] of Object.entries(files)) {
if (file.isBinary) throw new Error(`Handle binary output separately: ${fileName}`);
const root = path.resolve(outputDir);
const target = path.resolve(root, fileName);
if (!target.startsWith(`${root}${path.sep}`)) throw new Error('Unsafe output path');
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, file.content);
}
console.log(`${preset}: ${Object.keys(files).length} files generated`);
}
// Compare all presets
async function compareOutputs(nodeId: string) {
for (const preset of Object.…Optimize Anima code generation performance with caching, parallelism, and output tuning.
Anima Performance Tuning
Overview
Improve design-to-code throughput without treating cache hits or smaller output as success unless the result still matches the approved design version, accessibility expectations, and project build contract.
Measurement Contract
Record source-fetch, queue, generation, asset, validation, and review durations separately. Establish targets from the team's own representative fixtures and provider agreement; do not present illustrative latency or quota numbers as an Anima service-level objective.
Prerequisites
- A representative staging fixture and a baseline measurement of generation duration, cache hit rate, failure rate, and generated-code validation result.
- A version-aware cache key and retention policy that ties each artifact to Figma source version, node ID, and generation settings.
- Review gates for generated output so performance changes cannot automatically replace approved components or strip required licenses/accessibility content.
Authentication
Load ANIMA_TOKEN and the source-scoped FIGMA_TOKEN only in the backend worker. Performance tests use synthetic allowlisted sources; do not broaden credentials or retry authorization failures to make a benchmark complete.
Instructions
Step 1: File-Based Generation Cache
// src/performance/cache.ts
import crypto from 'crypto';
import fs from 'fs';
import { Anima } from '@animaapp/anima-sdk';
class GenerationCache {
private dir: string;
constructor(cacheDir = '.anima-cache') {
this.dir = cacheDir;
fs.mkdirSync(cacheDir, { recursive: true });
}
private hash(fileKey: string, sourceRevision: string, nodeId: string, settings: object): string {
return crypto.createHash('sha256').update(`${fileKey}:${sourceRevision}:${nodeId}:${JSON.stringify(settings)}`).digest('hex');
}
async getOrGenerate(
anima: Anima,
params: Parameters<Anima['generateCode']>[0],
sourceRevision: string,
maxAgeMs: number = 3600000, // 1 hour
): Promise<Awaited<ReturnType<Anima['generateCode']>>> {
const key = this.hash(params.fileKey, sourceRevision, params.nodesId[0], params.settings);
const path = `${this.dir}/${key}.json`;
if (fs.existsSync(path)) {
const stat = fs.statSync(path);
if (Date.now() - stat.mtimeMs < maxAgeMs) {
return JSON.parse(fs.readFileSync(path, 'utf8'));
}
}
const result = await anima.generateCode(params);
fs.writeFileSync(path, JSON.stringify(result));
return result;
}
clearOlderThan(maxAgeMs: number): number {
let cleared = 0;
for (const file of fs.readdirSync(this.dir)) {
const path = `${this.dir}/${file}`;
if (Date.now() - fs.statSync(path).mtimeMs > maxAgeMs…Production readiness checklist for Anima design-to-code pipelines.
Anima Production Checklist
Overview
Decide whether a React/HTML design-to-code pipeline is safe to launch by checking source authorization, backend isolation, output quality, review, observability, and rollback evidence.
Prerequisites
- Named design, engineering, security, and operations owners who can make a go/no-go decision and own the rollback path.
- A staging environment using separate managed Anima/Figma credentials, an allowlisted design registry, and a reproducible generated-code fixture.
- Defined output quality gates: source-version traceability, lint/type/build, visual/accessibility review, and no secrets in artifacts or logs.
Instructions
- Assign an owner and evidence link to every required checklist item.
- Run the readiness script with the deployment identity in staging and retain only its redacted result.
- Exercise a generation and rollback/disable path with an approved design component, then verify downstream code-quality and visual gates.
- Approve progressive release only when all required checks pass; any failed security, credential, output, or fallback control is a no-go condition.
Authentication & Secrets
- [ ]
ANIMA_TOKENstored in the backend secret manager (never in source) - [ ] Figma token uses only endpoint-required granular read scopes and an approved expiration
- [ ] Separate credentials for development, staging, and production environments
- [ ] Rotation and revocation owners plus tested procedures are documented
- [ ] Tokens excluded from client bundles and build artifacts
API Integration
- [ ] Pinned SDK uses its documented default API origin unless an approved contract says otherwise
- [ ] Figma rate limiting uses
FigmaRestApisignals and bounded wait; Anima quotas come from the account contract - [ ] Generation cache prevents redundant API calls for unchanged screens
- [ ] Figma file version polling detects design changes automatically
- [ ] Optional SDK SSE/job attachment or Figma event queue is authenticated and resumable
- [ ] Component mapping rules are tested for supported React or HTML output
Error Handling & Resilience
- [ ] Circuit breaker configured for Anima API outages
- [ ] Retry policy distinguishes Figma structured rate limits from bounded transient generation failures
- [ ] Graceful fallback when Figma PAT expires mid-pipeline
- [ ] Generated code validated against ESLint/Prettier before merge
- [ ] Design token mismatches flagged before component output
- [ ] Empty generation results handled (missing layers, unsupported elements)
Monitoring & Alerting
- [ ] API latency tracked per generation request
- [ ] Error-rate and latency objectiv…
Implement rate limiting for Anima API code generation requests.
Anima Rate Limits
Overview
Handle Figma rate limits from the current SDK's structured callback and treat any Anima generation quota as account-specific until the provider or agreement says otherwise. Never encode an invented requests-per-minute or concurrency allowance.
Documented Signals
| Surface | Signal | Required action |
|---|---|---|
FigmaRestApi.onRateLimited |
retryAfter, figmaPlanTier, figmaRateLimitType |
Retry only inside a bounded elapsed-time budget |
figmaRateLimitMaxWait |
1–180 seconds; default 60 | Set explicitly for the request's latency budget |
| Anima generation | Returned error/progress state and account contract | Stop or queue; do not infer a numeric quota |
Prerequisites
- Confirm the account's current generation and concurrency contract before choosing worker concurrency; absence of a published number means fail closed, not guess.
- Store
ANIMA_TOKEN,FIGMA_TOKEN, andFIGMA_FILE_KEYin the runtime secret manager or injected environment, and verify that the token has only the scopes required for the selected file. Never put tokens in source, fixtures, logs, generated receipts, or retry payloads. - Define an explicit allowlist of Figma files and node IDs, a bounded batch size, a maximum retry budget, and an approved output directory. Use synthetic or sandbox designs for load tests and confirm that generated output contains no customer data before persisting it.
- Install the pinned SDK and decide whether a generation is safe to repeat. Persist a redacted request fingerprint and resume only failed node IDs.
Instructions
Step 1: Configure Structured Figma Rate Handling
// src/anima/client.ts
import { Anima, FigmaRestApi } from '@animaapp/anima-sdk';
const figmaRestApi = new FigmaRestApi({
defaultOptions: {
token: process.env.FIGMA_TOKEN!,
onRateLimited: async ({ retryAfter, figmaPlanTier, figmaRateLimitType }) => {
console.warn({ retryAfter, figmaPlanTier, figmaRateLimitType });
return retryAfter > 0 && retryAfter <= 5; // Repository latency budget.
},
},
});
export const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
figmaRestApi,
});
Step 2: Bind Each Generation to a Maximum Wait
const result = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
nodesId: ['1:2'],
figmaRateLimitMaxWait: 5,
settings: { framework: 'react', language: 'typescript', styling: 'tailwind' },
});
console.log({ fileCount: Object.keys(result.files).length…Implement reference architecture for Anima design-to-code automation.
Anima Reference Architecture
Overview
This architecture separates design-source intake, authenticated code generation, deterministic post-processing, and reviewed delivery. It is intended for repeatable Figma-to-code pipelines where each run is bounded to approved files and nodes, produces inspectable artifacts, and can be stopped or rolled back without exposing design content or credentials.
Prerequisites
- Define the target framework, repository layout, supported Anima/Figma SDK versions, and the owner who approves generated changes. Pin dependencies and create a sandbox Figma file with synthetic components for pipeline tests.
- Obtain Figma and Anima credentials through the deployment secret manager, using least-privilege scopes and short-lived credentials where supported. Validate the configured Figma webhook passcode before accepting events; never commit, print, or place tokens in generated code, cache files, pull requests, or receipts.
- Establish allowlists for Figma file IDs, node IDs, webhook sources, output repositories, and branch names. Define retention and deletion rules for source snapshots, generated output, and logs before enabling automation.
- Prepare a dry-run mode, an artifact-diff gate, a staged canary environment, and a rollback reference to the last approved generated revision. Do not allow a webhook to publish directly to production.
System Architecture
┌────────────────┐ ┌──────────────┐ ┌─────────────────┐
│ Figma Design │────▶│ Figma API │────▶│ Anima SDK │
│ (Components) │ │ (Webhooks) │ │ (Code Gen) │
└────────────────┘ └──────────────┘ └────────┬────────┘
│
┌─────────▼────────┐
│ Post-Processing │
│ - Token mapping │
│ - Normalization │
│ - Lint/format │
└─────────┬────────┘
│
┌─────────▼────────┐
│ Output │
│ - React or HTML │
│ - PR creation │
│ - Storybook sync │
└──────────────────┘
Instructions
- Ingest and authorize. Use
Readto inspect the existing repository conventions and the signed event payload. Check the file/node allowlist, event freshness, source revision, and suppression/deletion rules before requesting any generation. - Generate in isolation. Run the pinned SDK in…
Apply production-ready patterns for the Anima SDK design-to-code pipeline.
Anima SDK Patterns
Overview
Build a backend @animaapp/anima-sdk wrapper with a pinned client, supported settings, source-bound caching, contained output normalization, and bounded error recovery. Reject unsupported framework values and ambiguous cache entries.
Prerequisites
- Pin the Anima SDK and TypeScript runtime versions, define the supported framework presets, and provide a sandbox Figma file containing synthetic components for tests and examples.
- Inject
ANIMA_TOKENand any Figma credentials from a secret manager at runtime. Authentication failures must be distinguishable from generation failures; never hard-code, log, cache, or include credentials in generated output or receipts. - Make
.anima-cacheprivate to the worker, exclude it from version control and artifact uploads, and define a retention/deletion policy. Cache keys may identify a request, but cached design source and generated content must not be sent to telemetry. - Set an allowlist for input file/node IDs and output paths, a maximum cache size, a bounded retry count, and an owner-approved normalization configuration before enabling the wrapper in CI or production.
Instructions
Step 1: Singleton Client with Configuration
// src/anima/client.ts
import { Anima } from '@animaapp/anima-sdk';
let instance: Anima | null = null;
export function getAnimaClient(): Anima {
if (!instance) {
if (!process.env.ANIMA_TOKEN) throw new Error('ANIMA_TOKEN not set');
instance = new Anima({ auth: { token: process.env.ANIMA_TOKEN } });
}
return instance;
}
// Preset configurations for different project needs
export const PRESETS = {
nextjs: { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const, uiLibrary: 'shadcn' as const },
vite: { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const },
reactPlainCss: { language: 'typescript' as const, framework: 'react' as const, styling: 'plain_css' as const },
static: { language: 'javascript' as const, framework: 'html' as const, styling: 'plain_css' as const },
} as const;
Step 2: Generation Cache
// src/anima/cache.ts
import crypto from 'crypto';
import fs from 'fs';
interface CacheEntry {
files: Record<string, { content: string; isBinary: boolean }>;
generatedAt: string;
settingsHash: string;
}
class AnimaCache {
private cacheDir: string;
constructor(cacheDir: string = '.anima-cache') {
this.cacheDir = cacheDir;
fs.mkdirSync(cacheDir, { recursive: true });
}
private getKey(fileKey: string, sourceRevision: string, nodeId: string, settings: object): stri…Audit and harden Anima and Figma tokens for design-to-code pipelines.
Anima Security Basics
Overview
This workflow protects the Anima and Figma credentials used by a design-to-code pipeline while keeping generated output reviewable. It applies least privilege to the design source, keeps tokens on the server, and makes secret exposure or unexpected file access a fail-closed condition.
Prerequisites
- A managed secret store and separate development, staging, and production bindings for
ANIMA_TOKENandFIGMA_TOKEN. - An allowlist of Figma file keys and component node IDs, with an owner for each design source and a documented rotation/revocation contact.
- A non-production fixture and a disposable staging workspace for testing token scope, generated artifacts, and rollback behavior.
- Repository secret scanning and a deterministic generated-code directory; never use real customer or personal design data as the test fixture.
Security Checklist
- [ ] Anima token stored in secret manager (not .env in prod)
- [ ] Figma token uses only the endpoint-required granular read scopes
- [ ] SDK runs server-side only (never ship tokens to browser)
- [ ]
.envfiles gitignored and chmod 600 - [ ] CI secrets stored in GitHub Secrets, not workflow files
- [ ] Generated code reviewed before committing (no embedded tokens)
Instructions
Step 1: Figma Token Scope Restriction
# When creating a Figma Personal Access Token:
# - Start with file_content:read for file/node content.
# - Add file_metadata:read, file_versions:read, or library read scopes only
# when the selected endpoint requires them.
# - Do not use the deprecated broad files:read scope for new integrations.
# - Set an organization-approved expiration date.
# - Create separate tokens for dev vs CI environments
Step 2: Server-Side Only Enforcement
// src/anima/safety.ts
// Anima SDK is designed for server-side use only
function validateEnvironment(): void {
if (typeof window !== 'undefined') {
throw new Error('Anima SDK must run server-side only — never import in browser code');
}
if (!process.env.ANIMA_TOKEN) throw new Error('ANIMA_TOKEN not set');
if (!process.env.FIGMA_TOKEN) throw new Error('FIGMA_TOKEN not set');
}
// Call this at startup
validateEnvironment();
Error Handling
| Failure | Required response |
|---|---|
| Secret manager is unavailable or a required token is empty | Abort before any Figma or Anima request; emit only a redacted reason and retry through the deployment system. |
| A browser bundle imports the SDK or contains a token | Fail the build, remove the artifact, and rotate any credential that may have been expo… |
Analyze and execute @animaapp/anima-sdk upgrades with rollback evidence.
Anima Upgrade & Migration
Overview
This workflow moves an Anima integration between SDK versions or from manual Figma exports to automation while preserving a reviewable, reversible design source of truth. It uses a pinned dependency and a staging canary so API or generated-code changes are detected before production output is replaced.
Prerequisites
- A clean working tree, committed lockfile, current SDK version, and a reviewed changelog or release note for the proposed target version.
- A fixture registry containing synthetic or approved design nodes, expected output paths, and a baseline artifact digest for the current workflow.
- Separate staging credentials with read-only design access, an owner for generated-code review, and a rollback revision that can restore the prior SDK and generated output.
- CI gates for install, lint, type checking, tests, and secret scanning; do not test an upgrade against customer designs or live production writes.
Migration Paths
| From | To | Complexity |
|---|---|---|
| Figma plugin (manual) | SDK automation | Medium |
| Older pinned SDK | Explicit reviewed target | Depends on release/type/generated-output diff |
| Anima Playground | SDK API | Low |
Instructions
Step 1: Upgrade SDK
# Check current version
npm list @animaapp/anima-sdk
# Select and record a concrete target; 0.27.0 was current on 2026-09-12.
export APPROVED_ANIMA_VERSION="0.27.0"
npm install --save-exact "@animaapp/anima-sdk@${APPROVED_ANIMA_VERSION}"
# Check for breaking changes
npm view "@animaapp/anima-sdk@${APPROVED_ANIMA_VERSION}" version dist.integrity
Step 2: Migrate from Manual Plugin to SDK
// BEFORE: Manual Figma plugin workflow
// 1. Open Figma → Plugins → Anima
// 2. Select component → Export → React
// 3. Copy-paste generated code into project
// 4. Manually repeat for each component change
// AFTER: Automated SDK workflow
import { Anima } from '@animaapp/anima-sdk';
import fs from 'node:fs';
import path from 'node:path';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
// Automated: runs in CI on Figma file version change
async function syncDesignToCode() {
const { files } = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2', '3:4', '5:6'], // All design system components
settings: { language: 'typescript', framework: 'react', styling: 'tailwind' },
});
// Write to project, run through linter, create PR
const root = path.resolve('src/components/generated')…Use Figma webhooks to trigger automatic Anima code generation on design changes.
Anima Webhooks & Events
Overview
Use Figma Webhooks v2 to detect approved design changes and enqueue Anima generation. Figma supplies the event contract; this workflow does not invent an Anima webhook API.
Prerequisites
- Team-level Figma webhook permission, a publicly reachable HTTPS endpoint, and a webhook passcode stored in a secret manager rather than source or request logs.
- An allowlist mapping approved file keys and component node IDs to their generated output directories and responsible owners.
- A durable event-id/version store, queue with retry and dead-letter handling, and a staging workspace containing synthetic design data.
- A rate-limit budget, replay/duplicate policy, and an explicit approval gate before generated code can be merged or deployed.
Authentication
Register the webhook with an authorized Figma token and keep its passcode in the receiver's secret manager. The queued backend worker separately uses managed Anima and Figma credentials; neither credential belongs in the event payload.
Instructions
Step 1: Register Figma Webhook
# Figma Webhooks API (requires team-level access)
curl -X POST "https://api.figma.com/v2/webhooks" \
-H "X-Figma-Token: ${FIGMA_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"event_type": "FILE_VERSION_UPDATE",
"context": "team",
"context_id": "YOUR_TEAM_ID",
"endpoint": "https://your-server.com/webhooks/figma",
"passcode": "your-webhook-secret",
"description": "Trigger Anima code generation on design changes"
}'
Step 2: Webhook Handler
// src/webhooks/figma-handler.ts
import express from 'express';
import crypto from 'node:crypto';
const router = express.Router();
declare const generationQueue: {
enqueue(job: { fileKey: string; eventTimestamp: string }): Promise<void>;
};
interface FigmaWebhookEvent {
event_type: 'FILE_VERSION_UPDATE' | 'FILE_UPDATE' | 'FILE_DELETE';
file_key: string;
timestamp: string;
passcode: string;
}
router.post('/webhooks/figma', express.json(), async (req, res) => {
const event = req.body as FigmaWebhookEvent;
// Verify passcode
const supplied = Buffer.from(event.passcode || '');
const expected = Buffer.from(process.env.FIGMA_WEBHOOK_SECRET || '');
if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) {
return res.status(400).json({ error: 'Invalid passcode' });
}
// Only process file version updates
if (event.event_type !== 'FILE_VERSION_UPDATE') {
return res.status(200).json({ skipped: true…Ready to use anima-pack?
Related Plugins
supabase-pack
Complete Supabase integration skill pack with 30 skills covering authentication, database, storage, realtime, edge functions, and production operations. Flagship+ tier vendor pack.
/plugin install supabase-pack@claude-code-plugins-plus
vercel-pack
Complete Vercel integration skill pack with 30 skills covering deployments, edge functions, preview environments, performance optimization, and production operations. Flagship+ tier vendor pack.
/plugin install vercel-pack@claude-code-plugins-plus
clay-pack
Complete Clay integration skill pack with 30 skills covering data enrichment, waterfall workflows, AI agents, and GTM automation. Flagship+ tier vendor pack.
/plugin install clay-pack@claude-code-plugins-plus
cursor-pack
Complete Cursor integration skill pack with 30 skills covering AI code editing, composer workflows, codebase indexing, and productivity features. Flagship+ tier vendor pack.
/plugin install cursor-pack@claude-code-plugins-plus
exa-pack
Governed Exa operator pack with 30 workflows for Search, Contents, Agent, Monitors, Websets, access, reliability, cost, and security.
/plugin install exa-pack@claude-code-plugins-plus
firecrawl-pack
Operator-grade Firecrawl v2 skill pack with 30 governed acquisition, security, reliability, and production workflows
/plugin install firecrawl-pack@claude-code-plugins-plus