figma-code-agent 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +133 -0
  2. package/bin/install.js +328 -0
  3. package/knowledge/README.md +62 -0
  4. package/knowledge/css-strategy.md +973 -0
  5. package/knowledge/design-to-code-assets.md +855 -0
  6. package/knowledge/design-to-code-layout.md +929 -0
  7. package/knowledge/design-to-code-semantic.md +1085 -0
  8. package/knowledge/design-to-code-typography.md +1003 -0
  9. package/knowledge/design-to-code-visual.md +1145 -0
  10. package/knowledge/design-tokens-variables.md +1261 -0
  11. package/knowledge/design-tokens.md +960 -0
  12. package/knowledge/figma-api-devmode.md +894 -0
  13. package/knowledge/figma-api-plugin.md +920 -0
  14. package/knowledge/figma-api-rest.md +742 -0
  15. package/knowledge/figma-api-variables.md +848 -0
  16. package/knowledge/figma-api-webhooks.md +876 -0
  17. package/knowledge/payload-blocks.md +1184 -0
  18. package/knowledge/payload-figma-mapping.md +1210 -0
  19. package/knowledge/payload-visual-builder.md +1004 -0
  20. package/knowledge/plugin-architecture.md +1176 -0
  21. package/knowledge/plugin-best-practices.md +1206 -0
  22. package/knowledge/plugin-codegen.md +1313 -0
  23. package/package.json +31 -0
  24. package/skills/README.md +103 -0
  25. package/skills/audit-plugin/SKILL.md +244 -0
  26. package/skills/build-codegen-plugin/SKILL.md +279 -0
  27. package/skills/build-importer/SKILL.md +320 -0
  28. package/skills/build-plugin/SKILL.md +199 -0
  29. package/skills/build-token-pipeline/SKILL.md +363 -0
  30. package/skills/ref-html/SKILL.md +290 -0
  31. package/skills/ref-layout/SKILL.md +150 -0
  32. package/skills/ref-payload-block/SKILL.md +415 -0
  33. package/skills/ref-react/SKILL.md +222 -0
  34. package/skills/ref-tokens/SKILL.md +347 -0
@@ -0,0 +1,320 @@
1
+ ---
2
+ name: build-importer
3
+ description: Build a service that fetches Figma designs and renders them in a CMS or React application. Use this skill when the user needs an API route or service that reads Figma data via the REST API and transforms it into components or blocks for a target platform.
4
+ ---
5
+
6
+ @knowledge/figma-api-rest.md
7
+ @knowledge/figma-api-variables.md
8
+ @knowledge/design-to-code-layout.md
9
+ @knowledge/design-to-code-visual.md
10
+ @knowledge/design-to-code-typography.md
11
+ @knowledge/design-to-code-assets.md
12
+ @knowledge/design-to-code-semantic.md
13
+ @knowledge/css-strategy.md
14
+ @knowledge/design-tokens.md
15
+ @knowledge/payload-figma-mapping.md
16
+ @knowledge/payload-blocks.md
17
+
18
+ ## Objective
19
+
20
+ Help the user build a service or API route that fetches Figma designs via the REST API and transforms them into components or blocks for a target platform (PayloadCMS, WordPress, custom React app, or other). The skill covers the full import pipeline: authentication, API endpoint selection, node traversal, property extraction, platform-specific transformation, asset handling, and token extraction.
21
+
22
+ ## Input
23
+
24
+ The user provides their importer requirements as `$ARGUMENTS`. This may be:
25
+
26
+ - A description of what they want to import (e.g., "import Figma page designs into PayloadCMS blocks")
27
+ - A path to an existing importer to enhance
28
+ - Target platform details and specific transformation needs
29
+ - A Figma file URL to build an importer for
30
+
31
+ If the input is a path, read the project files before proceeding. If the input is a description, proceed directly to Phase 1.
32
+
33
+ ## Process
34
+
35
+ ### Phase 1 — Assess
36
+
37
+ Determine the importer's scope, target platform, and constraints.
38
+
39
+ **Target platform:**
40
+ - **PayloadCMS** — Deep knowledge available. Container-first block architecture, 18-type block catalog, field factories, confidence scoring. Consult `knowledge/payload-figma-mapping.md` and `knowledge/payload-blocks.md`.
41
+ - **WordPress** — Map to Gutenberg blocks. Less prescriptive — assess the user's theme/plugin structure.
42
+ - **Custom React app** — Map to React component props. User defines the component library.
43
+ - **Other** — Assess the target's data model and map accordingly.
44
+
45
+ **Authentication:**
46
+ - **Personal Access Token (PAT)** — Simple, single-user. Token passed as `X-Figma-Token` header. Suitable for internal tools, CLI commands, CI/CD jobs.
47
+ - **OAuth2** — Multi-user, requires app registration. Use when building a SaaS product or multi-tenant tool. Requires token refresh handling.
48
+ - Required scopes: `file_content` (read files), `file_variables:read` (Variables API, Enterprise only)
49
+
50
+ **Import scope:**
51
+ - **Full page import**: traverse entire page, map all top-level frames to blocks/components
52
+ - **Single component import**: fetch a specific node by ID, map to one block/component
53
+ - **Selective import**: user picks which frames/components to import
54
+ - **One-time vs automated sync**: manual trigger vs webhook-driven continuous sync
55
+
56
+ **Asset handling:**
57
+ - **Download locally**: fetch image exports via `/images/:key` endpoint, store in project's media directory or CMS media library
58
+ - **Proxy from Figma CDN**: use Figma's image URLs directly (temporary — URLs expire after 14 days)
59
+ - **Hybrid**: download and store, with Figma CDN as fallback during import
60
+
61
+ Report the assessment to the user before proceeding.
62
+
63
+ ### Phase 2 — Recommend
64
+
65
+ Based on the assessment, recommend the import pipeline architecture.
66
+
67
+ **API endpoints to use:**
68
+
69
+ | Endpoint | Purpose | When to Use |
70
+ |----------|---------|-------------|
71
+ | `GET /v1/files/:key` | Full file metadata | Initial file structure discovery |
72
+ | `GET /v1/files/:key/nodes?ids=X,Y` | Targeted node fetch | Importing specific frames (preferred for performance) |
73
+ | `GET /v1/images/:key?ids=X&scale=2&format=png` | Image export | Asset extraction at 2x for retina |
74
+ | `GET /v1/files/:key/variables/local` | Variables API | Design token extraction (Enterprise only) |
75
+ | `GET /v1/files/:key/styles` | Published styles | Token extraction fallback for non-Enterprise |
76
+
77
+ - **Always prefer `/files/:key/nodes`** over `/files/:key` for targeted imports — fetching the full file is expensive and often unnecessary
78
+ - **Export images at 2x scale** minimum for retina displays
79
+ - **Use `format=png` for raster, `format=svg` for vectors** in image export
80
+
81
+ **Node traversal strategy:**
82
+ - Recursive depth-first traversal with a **depth limit of 30** to prevent stack overflow on deeply nested designs
83
+ - Filter out invisible nodes (`visible: false`) early — skip their entire subtree
84
+ - Skip `SLICE` nodes (selection helpers, not visual content)
85
+ - Track traversal depth and warn if approaching the limit
86
+
87
+ **Transform pipeline — 4 independent stages:**
88
+
89
+ ```
90
+ Fetch → Extract → Transform → Render
91
+ ```
92
+
93
+ 1. **Fetch**: API client calls Figma REST API, handles auth, rate limits, retries
94
+ 2. **Extract**: Node walker traverses the response, builds an intermediate data structure with all relevant properties extracted per the design-to-code knowledge modules
95
+ 3. **Transform**: Platform-specific mapper converts intermediate data to target format (PayloadCMS blocks, React props, WordPress blocks)
96
+ 4. **Render**: Assembles final output (JSON for CMS import, component files for React, CSS for tokens)
97
+
98
+ Each stage is independently testable — Fetch returns raw API data, Extract returns a serializable intermediate, Transform returns platform-specific data, Render returns files/strings.
99
+
100
+ **CMS field mapping (platform-specific):**
101
+
102
+ For **PayloadCMS**:
103
+ - Use confidence scoring from `knowledge/payload-figma-mapping.md` to match Figma components to the 18-type block catalog
104
+ - Map component properties to fields using the property-to-field table
105
+ - Container nesting limited to 2 levels
106
+ - Use field factories (`imageFields`, `linkGroup`, `layoutMeta`)
107
+
108
+ For **WordPress**:
109
+ - Map to Gutenberg block format (`<!-- wp:block-name {"attr":"value"} --><html><!-- /wp:block-name -->`)
110
+ - Map Figma properties to block attributes
111
+ - Handle inner blocks for nested content
112
+
113
+ For **Custom React**:
114
+ - Map to component props based on user-defined component library
115
+ - Generate TypeScript interfaces for prop types
116
+ - Map Figma variants to component prop enums
117
+
118
+ **Token bridging:**
119
+ - Extract design tokens during import (colors, spacing, typography, effects)
120
+ - Generate CSS Custom Properties following the three-layer architecture
121
+ - Link imported components/blocks to token references (`var(--token-name)`) rather than hardcoded values
122
+ - If Variables API is available (Enterprise), extract structured tokens; otherwise use threshold-based promotion from file traversal
123
+
124
+ **Error handling:**
125
+ - Rate limit compliance: respect `429` responses with `Retry-After` header, implement exponential backoff
126
+ - Partial success: if some nodes fail to import, continue with remaining nodes and report failures
127
+ - Structured error reporting: collect all warnings/errors during import and return a summary
128
+
129
+ Present the recommendations and confirm before implementing.
130
+
131
+ ### Phase 3 — Implement
132
+
133
+ Generate the importer code based on the agreed recommendations.
134
+
135
+ **1. API client module:**
136
+
137
+ ```typescript
138
+ // src/figma/client.ts
139
+ class FigmaClient {
140
+ constructor(private token: string) {}
141
+
142
+ async getFileNodes(fileKey: string, nodeIds: string[]): Promise<FileNodesResponse> {
143
+ // GET /v1/files/:key/nodes?ids=...
144
+ // Handles auth headers, rate limiting, retries
145
+ }
146
+
147
+ async getImages(fileKey: string, nodeIds: string[], options?: ImageOptions): Promise<ImageResponse> {
148
+ // GET /v1/images/:key?ids=...&scale=2&format=png
149
+ // Returns map of node ID -> image URL
150
+ }
151
+
152
+ async getVariables(fileKey: string): Promise<VariablesResponse> {
153
+ // GET /v1/files/:key/variables/local
154
+ // Enterprise only — caller should handle 403
155
+ }
156
+ }
157
+ ```
158
+
159
+ - Type-safe request/response interfaces matching the Figma REST API
160
+ - Automatic retry with exponential backoff on 429 (rate limit) and 5xx responses
161
+ - Request timeout handling
162
+ - Auth via `X-Figma-Token` header (PAT) or `Authorization: Bearer` (OAuth2)
163
+
164
+ **2. Extraction module:**
165
+
166
+ ```typescript
167
+ // src/figma/extractor.ts
168
+ interface ExtractedNode {
169
+ id: string;
170
+ name: string;
171
+ type: string;
172
+ layout: LayoutProperties; // From design-to-code-layout
173
+ visual: VisualProperties; // From design-to-code-visual
174
+ typography?: TypographyProperties; // From design-to-code-typography
175
+ assets: AssetReference[]; // From design-to-code-assets
176
+ children: ExtractedNode[];
177
+ boundVariables: VariableBinding[];
178
+ }
179
+
180
+ function extractNode(node: FigmaNode, depth: number, maxDepth: number): ExtractedNode {
181
+ // Recursive DFS with depth limit
182
+ // Filter invisible nodes
183
+ // Extract properties per design-to-code knowledge modules
184
+ }
185
+ ```
186
+
187
+ - Recursive node walker with configurable depth limit (default: 30)
188
+ - Property extraction following all 5 design-to-code knowledge modules:
189
+ - **Layout**: `layoutMode`, sizing modes, gap, padding, wrap, constraints, absolute positioning
190
+ - **Visual**: fills, strokes (INSIDE → box-shadow), effects, corners, opacity, gradients
191
+ - **Typography**: font mapping, line height (unitless ratio), letter spacing, styled segments
192
+ - **Assets**: vector container detection, image hash deduplication, export format decision
193
+ - **Semantic**: layer name → HTML element heuristics, ARIA requirements
194
+ - All output is JSON-serializable (no Figma API object references)
195
+
196
+ **3. Transform module (platform-specific):**
197
+
198
+ For PayloadCMS:
199
+ ```typescript
200
+ // src/transforms/payload.ts
201
+ function transformToPayloadBlock(node: ExtractedNode): PayloadBlockData {
202
+ // Apply confidence scoring to determine block type
203
+ // Map properties to PayloadCMS fields
204
+ // Handle container nesting (max 2 levels)
205
+ // Generate field configuration
206
+ }
207
+ ```
208
+
209
+ For custom React:
210
+ ```typescript
211
+ // src/transforms/react.ts
212
+ function transformToComponentProps(node: ExtractedNode): ComponentData {
213
+ // Map node properties to component props
214
+ // Generate TypeScript interface
215
+ // Map variants to prop enums
216
+ }
217
+ ```
218
+
219
+ **4. API route / service entry point:**
220
+
221
+ ```typescript
222
+ // src/api/import.ts (or pages/api/import.ts for Next.js)
223
+ export async function importFromFigma(request: ImportRequest): Promise<ImportResult> {
224
+ // 1. Parse Figma URL to extract file key and node IDs
225
+ // 2. Fetch nodes via FigmaClient
226
+ // 3. Extract properties via extractor
227
+ // 4. Transform to target platform format
228
+ // 5. Download and store assets (images at 2x)
229
+ // 6. Extract design tokens
230
+ // 7. Return structured result with success/failure per node
231
+ }
232
+ ```
233
+
234
+ **5. Token extraction during import:**
235
+
236
+ ```typescript
237
+ // src/figma/tokens.ts
238
+ function extractTokens(nodes: ExtractedNode[], variables?: VariablesResponse): TokenOutput {
239
+ // If Variables API data available: structured token extraction
240
+ // Otherwise: threshold-based promotion from node property values
241
+ // Generate CSS Custom Properties following three-layer architecture
242
+ // Generate Tailwind config extension snippet
243
+ }
244
+ ```
245
+
246
+ **6. CSS output:**
247
+ - Token definitions in CSS Custom Properties (`:root` block)
248
+ - Three-layer architecture: Tailwind for layout, tokens for design values, component CSS for visual skin
249
+ - Mode-aware overrides if variable modes are detected
250
+
251
+ ### Phase 4 — Validate
252
+
253
+ Verify the importer meets quality standards.
254
+
255
+ **API correctness:**
256
+ - [ ] Correct REST API endpoints used (`/files/:key/nodes` not `/files/:key` for targeted fetch)
257
+ - [ ] Auth header format correct (`X-Figma-Token` for PAT, `Authorization: Bearer` for OAuth2)
258
+ - [ ] Rate limit handling with exponential backoff on 429 responses
259
+ - [ ] Image exports at 2x scale minimum
260
+
261
+ **Traversal safety:**
262
+ - [ ] Depth limit enforced on recursive traversal (default: 30)
263
+ - [ ] Invisible nodes filtered out early
264
+ - [ ] `SLICE` nodes skipped
265
+ - [ ] Traversal produces JSON-serializable intermediate data
266
+
267
+ **Data integrity:**
268
+ - [ ] All intermediate data structures are JSON-serializable
269
+ - [ ] Image hashes deduplicated (same `imageHash` → one export)
270
+ - [ ] Variable bindings preserved in extracted data
271
+ - [ ] Partial success handling: individual node failures don't abort the entire import
272
+
273
+ **Platform-specific validation:**
274
+
275
+ For PayloadCMS:
276
+ - [ ] Container nesting does not exceed 2 levels
277
+ - [ ] Block type confidence scores reported
278
+ - [ ] Field factories used for reusable patterns
279
+ - [ ] Settings fields use Tailwind utility class strings
280
+
281
+ For all platforms:
282
+ - [ ] CSS follows three-layer architecture
283
+ - [ ] Token values use `var()` references (no hardcoded colors/spacing in component CSS)
284
+ - [ ] Pipeline stages are independently testable
285
+
286
+ ## Output
287
+
288
+ Generate the importer module files:
289
+
290
+ ### Core Files
291
+
292
+ - **`src/figma/client.ts`** — API client with auth, retry, rate limit handling
293
+ - **`src/figma/extractor.ts`** — Node walker with depth-limited extraction
294
+ - **`src/figma/tokens.ts`** — Token extraction and CSS generation
295
+ - **`src/figma/types.ts`** — Figma API response types, intermediate data structures
296
+
297
+ ### Platform-Specific Files
298
+
299
+ - **`src/transforms/{platform}.ts`** — Platform-specific mapper (PayloadCMS, React, WordPress)
300
+ - **`src/api/import.ts`** — API route or service entry point
301
+
302
+ ### Supporting Files
303
+
304
+ - **`tokens.css`** — Extracted design tokens as CSS Custom Properties
305
+ - **`tailwind.config.ts`** — Token-referencing Tailwind extension (if applicable)
306
+
307
+ ### Output Checklist
308
+
309
+ Before returning the importer code, verify:
310
+
311
+ - [ ] Auth correctly configured (PAT or OAuth2 with proper headers)
312
+ - [ ] Node traversal is depth-limited (default: 30)
313
+ - [ ] All intermediate data is JSON-serializable
314
+ - [ ] Images exported at 2x for retina displays
315
+ - [ ] Rate limits respected with retry logic
316
+ - [ ] Pipeline stages are independently testable (Fetch → Extract → Transform → Render)
317
+ - [ ] CSS uses token variable references (three-layer architecture)
318
+ - [ ] Partial success handling: failures collected and reported, not thrown
319
+ - [ ] PayloadCMS: container nesting ≤ 2 levels, field factories used
320
+ - [ ] Token extraction works with both Variables API and file traversal fallback
@@ -0,0 +1,199 @@
1
+ ---
2
+ name: build-plugin
3
+ description: Build a Figma plugin from scratch or enhance an existing one. Use this skill when the user is developing a Figma plugin and needs architecture guidance, scaffolding, implementation help, or best-practice validation.
4
+ ---
5
+
6
+ @knowledge/plugin-architecture.md
7
+ @knowledge/plugin-best-practices.md
8
+ @knowledge/figma-api-plugin.md
9
+
10
+ ## Objective
11
+
12
+ Help the user build or enhance a Figma plugin by assessing their needs, recommending architecture and tooling, implementing the plugin code, and validating it against production best practices. This skill covers the full lifecycle: project scaffolding, manifest configuration, main thread + UI code, IPC event system, data flow pipeline, and build setup.
13
+
14
+ ## Input
15
+
16
+ The user provides their plugin requirements as `$ARGUMENTS`. This may be:
17
+
18
+ - A description of what the plugin should do (e.g., "export frames as React components")
19
+ - A path to an existing plugin project to enhance
20
+ - A specific feature to add to an existing plugin
21
+ - A technical question about plugin architecture
22
+
23
+ If the input is a path, read the project files (manifest, main.ts, ui.tsx, package.json) before proceeding. If the input is a description, proceed directly to Phase 1.
24
+
25
+ ## Process
26
+
27
+ ### Phase 1 — Assess
28
+
29
+ Determine the scope and constraints of the plugin project.
30
+
31
+ **New project assessment:**
32
+ - What does the plugin do? Classify the target functionality:
33
+ - **Extraction**: reads design data and exports it (HTML, CSS, JSON, tokens)
34
+ - **Generation**: creates or modifies Figma nodes programmatically
35
+ - **Manipulation**: transforms existing nodes (resize, restyle, reorganize)
36
+ - **Utility**: selection helpers, linting, naming conventions, search
37
+ - **Import/Export**: bridges Figma with external systems (CMS, code repos, APIs)
38
+ - Plugin type: standard (`editorType: ["figma"]`) or hybrid (standard + codegen)
39
+ - If the user wants a **codegen-only** plugin (runs exclusively in Dev Mode inspect panel), redirect them to `/fca:build-codegen-plugin` instead
40
+ - UI requirements: headless (no UI), modal dialog, or full sidebar panel
41
+ - Scope: single atomic operation vs multi-step pipeline with progress reporting
42
+
43
+ **Existing project assessment:**
44
+ - Read manifest/package.json to determine current plugin type and capabilities
45
+ - Read main thread and UI entry points to understand current architecture
46
+ - Identify gaps: missing error handling, performance issues, missing features
47
+ - Determine if the request is an enhancement, refactor, or bug fix
48
+
49
+ Report the assessment to the user before proceeding.
50
+
51
+ ### Phase 2 — Recommend
52
+
53
+ Based on the assessment, recommend the architecture and tooling.
54
+
55
+ **Toolchain:**
56
+ - **Recommended**: `@create-figma-plugin` — provides TypeScript, Preact UI, build tooling, IPC utilities, and optimized bundling out of the box
57
+ - **Alternative**: manual setup with esbuild/webpack — only when the user has specific reasons to avoid the framework
58
+
59
+ **UI framework:**
60
+ - Plugins with UI should use Preact + `@create-figma-plugin/ui` (NOT React — Preact is significantly smaller and is the standard for Figma plugins)
61
+ - Headless plugins skip UI entirely (`figma.showUI` not called)
62
+
63
+ **IPC (Inter-Process Communication):**
64
+ - Type-safe event system with centralized event name constants (never string literals scattered through code)
65
+ - Request/response correlation for async operations
66
+ - Structured error events emitted from main thread to UI
67
+ - Use `emit`/`on` from `@create-figma-plugin/utilities` or equivalent typed wrapper
68
+
69
+ **Data flow pipeline:**
70
+ - For extraction plugins: 3-stage pipeline — Extract (Figma API) → Generate (transform data) → Export (assemble output)
71
+ - For generation plugins: 2-stage pipeline — Parse (input data) → Create (Figma API calls)
72
+ - For utility plugins: single-pass processing
73
+ - Each stage should be independently testable with plain data input/output
74
+
75
+ **Manifest configuration:**
76
+ - `editorType: ["figma"]` for standard plugins
77
+ - `documentAccess: "dynamic-page"` for plugins that read document data
78
+ - Minimum required permissions — most plugins need zero `networkAccess` or `codegenPermissions`
79
+ - `relaunchButtons` if the plugin supports re-launch from specific nodes
80
+
81
+ **Async strategy:**
82
+ - All Figma API calls use async variants (`getNodeByIdAsync`, `loadFontAsync`, `exportAsync`)
83
+ - Font loading before any text modification with `figma.mixed` handling
84
+ - Timeout handling for long operations
85
+ - Cancellation support via `figma.on('close')` listener
86
+
87
+ **Project structure (recommended):**
88
+ ```
89
+ src/
90
+ main.ts # Main thread entry
91
+ ui.tsx # UI entry (if applicable)
92
+ types.ts # Shared types and event names
93
+ extraction/ # Figma API reading (extract stage)
94
+ generation/ # Data transformation (generate stage)
95
+ export/ # Output assembly (export stage)
96
+ utils/ # Shared utilities
97
+ ```
98
+
99
+ Present the recommendations to the user and confirm before implementing.
100
+
101
+ ### Phase 3 — Implement
102
+
103
+ Generate the plugin code based on the agreed recommendations.
104
+
105
+ **For new projects, scaffold:**
106
+
107
+ 1. **Manifest / package.json `figma-plugin` section:**
108
+ - Plugin name, id (placeholder), `editorType`, `documentAccess`
109
+ - Main and UI entry points
110
+ - Build scripts with `--typecheck` and `--minify`
111
+
112
+ 2. **`src/types.ts`** — Shared type definitions:
113
+ - IPC event name constants as a const object
114
+ - Event payload interfaces for each event
115
+ - Intermediate data structures (e.g., `ExtractedNode` for extraction plugins)
116
+
117
+ 3. **`src/main.ts`** — Main thread entry:
118
+ - IPC event handlers with top-level try/catch per handler
119
+ - Centralized error emission helper
120
+ - Async-first API usage throughout
121
+ - Progress reporting for operations over 100 nodes
122
+ - Cache initialization and cleanup
123
+
124
+ 4. **`src/ui.tsx`** — UI entry (if applicable):
125
+ - Preact functional components
126
+ - IPC event listeners for data and error events
127
+ - Loading states and error display with recovery hints
128
+ - `figma.notify()` integration for quick feedback
129
+
130
+ 5. **Build configuration:**
131
+ - TypeScript with strict mode
132
+ - esbuild or `@create-figma-plugin` build with minification
133
+ - `--typecheck` in build scripts
134
+
135
+ **For existing projects:**
136
+ - Identify specific gaps from the assessment
137
+ - Generate targeted modifications — new files, function additions, or refactored code
138
+ - Preserve existing patterns and naming conventions
139
+ - Add missing error handling, caching, or async patterns as needed
140
+
141
+ **All generated code includes:**
142
+ - Structured error handling with try/catch and error codes
143
+ - Async-first API patterns
144
+ - JSON-serializable intermediate data structures (never pass SceneNode across IPC)
145
+ - Comments explaining non-obvious Figma API behaviors
146
+ - Type-safe IPC with centralized event names
147
+
148
+ ### Phase 4 — Validate
149
+
150
+ Perform a lightweight validation pass on the generated code.
151
+
152
+ **Quick checks (always run):**
153
+ - [ ] All IPC handlers wrapped in try/catch
154
+ - [ ] Async APIs used (`getNodeByIdAsync` not `getNodeById`)
155
+ - [ ] No SceneNode objects passed across IPC (only serializable data)
156
+ - [ ] Manifest `editorType` and `documentAccess` correct
157
+ - [ ] Event names centralized as constants
158
+ - [ ] Permissions minimized in manifest
159
+
160
+ **Architecture checks:**
161
+ - [ ] Data flow follows staged pipeline pattern (extract → generate → export)
162
+ - [ ] Generation/transform logic is separable from Figma API calls (testable)
163
+ - [ ] IPC events have typed payloads
164
+
165
+ **Suggest deep audit:**
166
+ If the plugin is substantial (>500 lines or multi-file), suggest running `/fca:audit-plugin` for a comprehensive 9-category audit covering performance, memory, caching, testing, and distribution readiness.
167
+
168
+ ## Output
169
+
170
+ Generate the appropriate files based on new vs existing project:
171
+
172
+ ### New Project Output
173
+
174
+ - **`package.json`** or manifest with `figma-plugin` configuration
175
+ - **`src/types.ts`** — Event names, payload types, intermediate data structures
176
+ - **`src/main.ts`** — Main thread with handlers, error emission, async patterns
177
+ - **`src/ui.tsx`** — UI components (if applicable)
178
+ - **`tsconfig.json`** — TypeScript configuration
179
+ - **Build scripts** — With `--typecheck` and `--minify` flags
180
+
181
+ ### Existing Project Output
182
+
183
+ - Modified/new files addressing the identified gaps
184
+ - Explanation of what changed and why
185
+
186
+ ### Output Checklist
187
+
188
+ Before returning the plugin code, verify:
189
+
190
+ - [ ] Plugin type is correct for the use case (standard vs codegen vs hybrid)
191
+ - [ ] Manifest `editorType` and `documentAccess` are set correctly
192
+ - [ ] IPC event system is type-safe with centralized event name constants
193
+ - [ ] All IPC handlers have top-level try/catch with structured error emission
194
+ - [ ] Async APIs used throughout (`getNodeByIdAsync`, `loadFontAsync`, `exportAsync`)
195
+ - [ ] Permissions are minimized (no unnecessary `networkAccess`)
196
+ - [ ] Intermediate data structures are JSON-serializable (no SceneNode references)
197
+ - [ ] UI uses Preact (not React) if `@create-figma-plugin` toolchain is used
198
+ - [ ] Data flow follows staged pipeline pattern where applicable
199
+ - [ ] Build scripts include `--typecheck` and `--minify`