figma-handoff-kit 0.0.0-stage → 0.2.3

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ ## 0.2.3
4
+
5
+ - Move the npm package from `@viettran210/figma-handoff-kit` to `figma-handoff-kit`.
6
+
7
+ - Add `help [command]` and `--version`; simplify help and clarify one-way sync.
8
+
9
+ - Add GitHub Actions checks and npm trusted publishing after merges to main with a new version.
10
+ - Add `figma-handoff start` while retaining `serve`; update plugin copy commands and CLI documentation.
11
+
12
+ ## 0.2.2
13
+
14
+ - Preserve partial variant properties and unassigned labels when name recovery cannot determine a missing key.
15
+
16
+ - Infer a single missing variant key from a consistent sibling schema; reject ambiguous or conflicting combinations.
17
+
18
+ - Recover variant metadata from normalized main-component names when the native getter throws; retain warnings and explicit inferred provenance.
19
+
20
+ - Add `figma-handoff plugin`, `--path` and `--open` for local plugin discovery and member setup instructions.
21
+
22
+ ## 0.2.1
23
+
24
+ - Handle mixed Figma text properties without Symbol conversion failures; preserve styled text ranges.
25
+ - Continue exporting components whose variant getter fails, recording a metadata warning.
26
+ - Bound asset filenames by UTF-8 byte length with stable hash suffixes and bound new bridge folder names.
27
+
28
+ ## 0.2.0
29
+
30
+ - Download design bundles as ZIP without installing a CLI.
31
+ - Save to a project through the Node.js bridge, with stable ID-based folders and incremental screen checks.
32
+ - Run `figma-handoff sync` after explicitly enabling CLI sync in the connected plugin: all pages except Trash, 2×, unchanged screens skipped.
33
+ - Revoke pairing when disabling CLI sync; reject concurrent sessions and jobs.
34
+ - Fix hash calculation for Figma UI environments without WebCrypto and guard exports against unintended/stale events.
35
+ - Improve VI/EN interface, setup guidance, copy feedback, scope help and export logs.
36
+ - Add experimental macOS `open` command; automatic plugin launch still depends on macOS permissions and Figma UI behavior.
37
+ - Expand CLI help and installation, troubleshooting and release documentation.
38
+
39
+ ## 0.1.0
40
+
41
+ Initial npm CLI and local bridge release.
package/PUBLISHING.md ADDED
@@ -0,0 +1,86 @@
1
+ # Release 0.2.3
2
+
3
+ This document prepares the release; it does not mean npm 0.2.3 or a Figma Community listing has been published.
4
+
5
+ ## Validate the release
6
+
7
+ ```sh
8
+ npm ci
9
+ npm run check:release
10
+ npm pack
11
+ ```
12
+
13
+ Inspect the archive: it must contain `bin/`, `figma-exporter-plugin/`, README and release documentation, with no credentials, private exports or project registry. Test the packed package in a clean installation before publishing. Both `figma-handoff --help` and the compatibility alias `figma-export --help` must work.
14
+
15
+ Manual Figma Desktop checks using a disposable design copy:
16
+
17
+ - Import the updated manifest; opening the plugin must not export anything.
18
+ - Check English/Vietnamese labels, logs, help and copy feedback.
19
+ - Download ZIP for selected items; extract and inspect screenshots, specs and assets.
20
+ - Start bridge, choose Save to project and confirm project/output directory.
21
+ - Export once, export unchanged again, edit one screen and export again; confirm skipped/updated results.
22
+ - Enable CLI sync, run `figma-handoff sync`, confirm all-page 2× export and terminal counts.
23
+ - Disable CLI sync; a new sync request must fail. Re-enable and verify it works.
24
+ - Close plugin/restart bridge; verify disconnected errors and fresh opt-in.
25
+ - Confirm outputs survive updates and existing manifests retain stable paths.
26
+
27
+ Shared library/style changes, large-file memory use and Figma browser local-network/download behavior need real-environment checks. Automated tests do not replace these checks.
28
+
29
+ ## Publish npm through GitHub Actions
30
+
31
+ Configure the npm trusted publisher for `viettranvan/figma-handoff-kit`, workflow
32
+ `publish.yml`, environment `npm`, with direct `npm publish` allowed. The GitHub
33
+ Environment must allow only `main`; no reviewer gate is needed for automatic
34
+ publishing. No npm token or GitHub PAT is required.
35
+
36
+ 1. Update both package versions with `npm version patch --no-git-tag-version`
37
+ (or choose a minor/major version intentionally), then update CHANGELOG.md.
38
+ 2. Open a PR. CI runs tests, checks package contents and installs the archive in
39
+ a temporary directory to verify both CLI names and plugin discovery.
40
+ 3. Require the `Package checks` status in the main branch ruleset before merging.
41
+ 4. Merge the reviewed PR. `publish.yml` checks the merged commit again and
42
+ publishes the tested archive with OIDC. Manual dispatch is restricted to main.
43
+ 5. Check the Publish npm run and verify the registry version. Registry visibility
44
+ can lag; verification retries for about a minute.
45
+
46
+ Existing versions are skipped, allowing documentation-only merges and safe
47
+ re-runs. Registry errors fail the job. New versions must be stable x.y.z and
48
+ newer than all published stable versions. Do not reuse a published version.
49
+ Keep release merges sequential: GitHub concurrency retains only one pending
50
+ run, so rapid merges can replace a pending run. The running publish is not cancelled.
51
+
52
+ The package is now `figma-handoff-kit`. Bootstrap its first release manually
53
+ before configuring trusted publishing for this new package. The old scoped
54
+ package's trusted publisher does not apply to the new name. Keep the same GitHub
55
+ environment `npm`, repository and workflow filename.
56
+
57
+ Existing users: stop the bridge, uninstall `@viettran210/figma-handoff-kit`, install
58
+ `figma-handoff-kit`, then run `figma-handoff plugin --open` and import the new
59
+ manifest path in Figma Desktop. Project registration and exported files remain
60
+ outside the package installation and are preserved. Do not install both packages
61
+ at once because they provide the same CLI executable names.
62
+
63
+ This pipeline publishes npm only. Figma Desktop checks above remain manual;
64
+ it does not publish the Figma Community listing or create GitHub release tags.
65
+
66
+ ## Prepare Figma Community
67
+
68
+ The manifest currently has a development ID (`sit-figma-ai-exporter`). Create/register the plugin through Figma's plugin publishing workflow and use the real ID assigned by Figma; do not invent one. Preserve the assigned ID on future updates.
69
+
70
+ Upload/use the same `code.js` and `ui.html` tested for this npm release. The plugin has no build step. The manifest currently permits wildcard network access for the local bridge; review and narrow it to the supported loopback origin where accepted by Figma, and verify actual connection behavior before submission. Do not claim Community readiness until Figma has accepted the manifest and the listing has been reviewed.
71
+
72
+ Prepare a cover/icon, screenshots for both destinations, support/repository link and the following description. Add the real Community URL to README after the listing exists. Do not include internal SIT project screenshots or private design data in public assets.
73
+
74
+ ### Suggested listing description
75
+
76
+ Figma Handoff Kit exports design bundles for development and AI-assisted implementation: screenshots, JSON/Markdown specs, assets, tokens, font guides and component snippets.
77
+
78
+ **Download ZIP:** choose your selection, current page or all pages. No CLI needed. Extract the archive into your project.
79
+
80
+ **Save to project:** install Node.js 20+, run `npm install -g figma-handoff-kit`, then `figma-handoff start` on the same computer as Figma. Choose your project and output folder in the terminal; confirm them in the plugin. Exports are saved locally, with unchanged screens skipped.
81
+
82
+ **Sync from terminal:** choose Save to project and enable Allow CLI sync in the plugin. Keep Figma, plugin and bridge open, then run `figma-handoff sync` whenever you want an update. It checks all pages except Trash at 2× and exports new/changed screens. Disable the checkbox to revoke access. Sync does not open Figma or delete obsolete local folders.
83
+
84
+ English and Vietnamese interface. No hosted upload service. File permissions and organization plugin policies apply. ZIP exports render again each time and may use significant memory on large designs.
85
+
86
+ Support and source: https://github.com/viettranvan/figma-handoff-kit
package/README.md CHANGED
@@ -1,3 +1,205 @@
1
- # Temporary Holding Version
1
+ # Figma Handoff Kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Export Figma screens into developer-friendly design bundles: screenshots, SVG/PNG assets, JSON/Markdown specs, design tokens, font guides and component snippets.
4
+
5
+ Two export destinations are available in the Figma plugin:
6
+
7
+ - **Download ZIP** — no CLI, Node.js or local bridge required. Export a selection, page or file, then extract the archive into your project.
8
+ - **Save to project** — run the local CLI to write directly into a project folder and skip screens whose design and output files have not changed.
9
+
10
+ ## Install the CLI (for Save to project)
11
+
12
+ Requires **Node.js 20 or later** on macOS, Windows or Linux. Python is not required.
13
+
14
+ ```sh
15
+ npm install -g figma-handoff-kit
16
+ figma-handoff start
17
+ ```
18
+
19
+ Choose a registered project, or **Add a new project** and enter its folder and output directory. The default output is `figma/exports`; for an ignored docs folder, choose `docs/figma`.
20
+
21
+ Optional registration from a repository root:
22
+
23
+ ```sh
24
+ cd /path/to/project
25
+ figma-handoff init --output-dir docs/figma
26
+ figma-handoff start
27
+ ```
28
+
29
+ To choose a different project from anywhere:
30
+
31
+ ```sh
32
+ figma-handoff start --select
33
+ ```
34
+
35
+ `figma-export` remains a compatibility alias for `figma-handoff`.
36
+
37
+ ## Install the Figma plugin
38
+
39
+ The plugin is **not yet published to Figma Community**. For now, use Figma Desktop:
40
+
41
+ 1. Run `figma-handoff plugin --open` to show setup instructions and open the installed plugin folder. No clone or build is needed.
42
+ 2. Open an editable Design file in **Figma Desktop** (macOS/Windows). Choose **Plugins → Development → Import plugin from manifest…** and select the displayed `manifest.json`.
43
+ 3. On macOS press **Cmd+Shift+G** in the file picker and paste the full path. On Windows paste it into **File name**. `figma-handoff plugin --path` prints just that path.
44
+ 4. Run **Plugins → Development → Figma Handoff Kit**. Keep `manifest.json`, `code.js` and `ui.html` together.
45
+ 5. Choose Download ZIP, or run `figma-handoff start`, choose your project and select Save to project.
46
+
47
+ Development import is once per computer and requires Desktop; the browser does not import local manifests. If you only have Can view, use an editable file/copy or ask for edit access. Organization plugin policy may require administrator approval. After npm updates, restart the bridge and reopen the plugin. If a Node version manager changes the package location, import the manifest again from the new path.
48
+
49
+ Installing the CLI does not automatically install the Figma plugin. A Community installation link will be added after publication. Browser downloads and local-network access may behave differently across Figma Desktop and browsers; verify in your environment.
50
+
51
+ ## Export a ZIP
52
+
53
+ 1. Choose **Download ZIP** in the plugin (default).
54
+ 2. Choose selected items, the current page, or every page in the file.
55
+ 3. Select screenshot size: 1× for smaller files, 2× recommended, 3× for larger images.
56
+ 4. Export. If the automatic download does not start, click **Download ZIP file**.
57
+ 5. Extract into your project.
58
+
59
+ Every ZIP export renders the selected screens again. ZIP mode does not read local files, perform incremental skipping or generate the bridge's project-wide catalog/font summary. Screen-level component/font/token files are included. ZIP uses uncompressed storage and is assembled in memory; for large files export smaller selections or use the local bridge. A new ZIP contains the latest names; existing local folders are not synchronized or deleted.
60
+
61
+ ## Save directly into a project
62
+
63
+ 1. Run `figma-handoff start` on the **same computer** as Figma and leave the terminal open.
64
+ 2. Choose **Save to project** in the plugin.
65
+ 3. Check the displayed project and output directory before exporting.
66
+ 4. Choose scope and image size, then export. Stop the bridge with Ctrl+C when finished.
67
+
68
+ The bridge listens on loopback port 3055. If busy, the CLI offers Stop or Exit; it never force-kills a listener automatically. If a browser blocks local access, allow local-network access or use Figma Desktop. The plugin includes Retry and copyable setup commands.
69
+
70
+ ## Storage and incremental export
71
+
72
+ - Project registry: `~/.config/figma-export/projects.json` (outside your repositories).
73
+ - Export data: your selected project/output directory, not the npm installation directory or a cloud server.
74
+ - `export-manifest.json`: maps document/node IDs to stable folders, preserving paths after renames.
75
+ - `.export-checkpoint.json`: stores the screen design hash and output file hashes.
76
+
77
+ An unchanged screen is skipped only if its output files remain intact. Missing/modified output triggers another export. **Re-export all** bypasses skipping within the selected scope. Section notes are uploaded separately. Existing legacy root configs remain supported. Keep manifests/checkpoints when reusing an output folder.
78
+
79
+ Shared library/style change detection still needs live Figma verification. Component usage counts in the local catalog retain cumulative behavior on repeated exports. When no Figma file key is available, document identity falls back to plugin data; duplicated documents may copy that identity.
80
+
81
+ ## Help and updates
82
+
83
+ ```sh
84
+ figma-handoff --help
85
+ figma-handoff init --help
86
+ figma-handoff start --help
87
+ npm install -g figma-handoff-kit
88
+ ```
89
+
90
+ Restart the bridge and reload the development plugin after updating.
91
+
92
+ ## Development
93
+
94
+ ```sh
95
+ npm ci
96
+ npm test
97
+ npm pack --dry-run
98
+ npm install -g .
99
+ ```
100
+
101
+ The Node bridge and plugin live in this repository. Legacy Python scripts are reference-only and excluded from the npm package. The plugin and CLI are distributed together in npm; update Figma Community separately when published.
102
+
103
+ Source and issues: https://github.com/viettranvan/figma-handoff-kit
104
+
105
+ Version 0.2.0 adds ZIP downloads, CLI sync, updated setup guidance and export fixes. See [CHANGELOG.md](CHANGELOG.md).
106
+
107
+ ## Open a project in Figma Desktop (macOS, experimental)
108
+
109
+ ```sh
110
+ figma-handoff open --url "https://www.figma.com/design/FILE_KEY/Design?node-id=1-2"
111
+ figma-handoff open
112
+ figma-handoff open --select
113
+ ```
114
+
115
+ Stores the URL in the project's global registry, starts the bridge, and opens the file/section in Figma Desktop. The plugin must already be imported/installed. Quick Actions searches for Figma Handoff Kit and attempts to activate an exact accessible button/menu result. If the result cannot be identified, confirm it manually with Enter. No design is exported until you click Export in the plugin.
116
+
117
+ macOS may request Accessibility permission for the hosting terminal and Automation permission for System Events. File load speed, localization and Figma's accessibility structure can affect automatic plugin launch; this is not a supported Figma launch API. If it fails, launch the plugin manually. This command has not been verified end-to-end against Figma Desktop yet.
118
+
119
+ ## Sync changes with one command
120
+
121
+ 1. Run `figma-handoff start` in your registered project and leave this terminal open.
122
+ 2. Open the updated plugin in the target Figma file, select **Save to project** and enable **Allow CLI sync for this file (all pages, 2×)**.
123
+ 3. From another terminal inside the registered project, run `figma-handoff sync` (or `figma-handoff sync --select`).
124
+
125
+ Sync sends one explicit request to the paired plugin. It exports all pages except Trash at 2× with incremental skipping, then prints checked/saved/skipped counts. The bridge and plugin must remain running. Pairing is session-only and must be enabled again after restart; disabling the checkbox immediately revokes the pairing. Only one active document may pair with a bridge. A second sync is rejected while one is queued/running. Failed/disconnected syncs are reported; no export is triggered by merely opening the plugin. Ctrl+C only stops the CLI waiting, not a running Figma export. Runtime timeout is 15 minutes. Automated protocol tests cover pairing, dispatch and completion; verify the real Figma workflow before publishing.
126
+
127
+
128
+ ```sh
129
+ # Terminal 1 — leave running
130
+ cd /path/to/project
131
+ figma-handoff start
132
+
133
+ # Enable Allow CLI sync in the plugin, then use terminal 2 whenever needed
134
+ cd /path/to/project
135
+ figma-handoff sync
136
+ ```
137
+
138
+ Sync uses the plugin's full export pipeline, not the REST API. It always checks all pages except Trash at 2×; the manual scope, screenshot size and Re-export all controls do not change CLI sync. It does not launch Figma, open files, install plugins, or duplicate designs. No PAT, sudo, Accessibility or Automation permission is needed for this connected-plugin workflow. Keep the computer awake and Figma, plugin and bridge running.
139
+
140
+ Sync updates new/changed screens and recreates missing or modified outputs. It does **not** remove local folders when screens are deleted in Figma. An enabled plugin may still finish an export after you disable pairing or stop the CLI.
141
+
142
+ ## Permissions and troubleshooting
143
+
144
+ - **Can view on the original file:** this Design plugin needs permission to run in the file. Ask for edit access, have the designer export, or duplicate into your Drafts if the owner permits copying. A copy does not receive later changes from the original automatically.
145
+ - **Cannot reach bridge:** run `figma-handoff start` on the same computer, check port 3055 and local-network permissions, then Retry in the plugin.
146
+ - **Enable CLI sync first:** choose Save to project, verify the destination and enable Allow CLI sync. Repeat after restarting the bridge or plugin.
147
+ - **Different project:** stop the old bridge, run `figma-handoff start --select` and select the intended project. Reconnect the plugin before enabling sync.
148
+ - **Already paired/running:** only one plugin session and one sync job are supported per bridge. Disable pairing in the other plugin, or restart the bridge if that session is unavailable.
149
+ - **Plugin disconnected / timeout:** inspect Figma and its export log before retrying. Ctrl+C does not cancel the Figma export. Restart the bridge if an abandoned job blocks future requests.
150
+ - **Digest error or older behavior:** update the npm package, restart the bridge and reload the updated plugin. Update both parts together.
151
+ - **ZIP too large:** export a smaller selection or save through the bridge. ZIP assembly uses memory.
152
+
153
+ ## Release and privacy
154
+
155
+ The plugin sends design data to the local loopback bridge only when Save to project is selected. ZIP mode assembles the archive inside the plugin UI. This project has no hosted upload service or telemetry. Exported designs and the project registry remain on your computer; take care when sharing export folders.
156
+
157
+ The npm package includes the CLI and plugin source. Figma Community distributes the plugin separately; npm installation does not register it with Figma. For release instructions, the Community description and manual validation checklist, see [PUBLISHING.md](PUBLISHING.md).
158
+
159
+
160
+ ### Variant metadata recovery
161
+
162
+ If Figma throws while reading variant properties, the exporter tries the main component's name (not a renamed instance). It removes leading `=` characters and accepts only unique, nonempty `Property=Value` pairs. Recovered metadata is marked `variantMetadataSource: "normalized-name"`, with original/normalized names and the original `variantWarning`. For one unassigned value, the exporter can infer a missing key only if all other sibling components have a consistent, fully named schema, exactly one key is missing, and the result does not duplicate a sibling combination. Such results use `variantMetadataSource: "sibling-schema"`. If siblings only define Compare, `=Compare=Off, Nobody started` preserves Compare and stores Nobody started in `unassignedVariantLabels`, with `variantMetadataSource: "partial-name"`; the exporter does not invent State. This does not repair or rename anything in Figma. Re-export affected screens with Re-export all to refresh existing checkpoints after upgrading.
163
+
164
+
165
+ ### Quick import: manifest discovery
166
+
167
+ Use `figma-handoff plugin --open` to open the installed plugin folder and display import instructions, or `figma-handoff plugin --path` for the absolute manifest path. The CLI resolves the path relative to its own installed module, not the current project or a hardcoded npm root; this also works with Node version managers.
168
+
169
+ On macOS, copy the path with `figma-handoff plugin --path | pbcopy`. In Figma Desktop choose Plugins → Development → Import plugin from manifest, press Cmd+Shift+G, paste the path and select it. On Windows, paste the path into the file picker's File name field. Import is a manual Figma registration step; the CLI does not bypass it or request Accessibility access.
170
+
171
+ Keep using the files in the installed package rather than copying only manifest.json: code.js and ui.html must remain beside it. Updating that installation updates those files; restart the plugin and bridge. Switching Node installations changes the path and requires re-importing. A future Community release removes this local import step. The plugin command is available from npm 0.2.2.
172
+
173
+ `figma-handoff serve` remains available as a compatibility alias for `figma-handoff start`.
174
+
175
+ ### Everyday commands
176
+
177
+ ```sh
178
+ figma-handoff start # Start bridge; select or add a project
179
+ figma-handoff start --select # Choose another project
180
+ figma-handoff plugin # Show import instructions
181
+ figma-handoff plugin --open # Open the plugin folder
182
+ figma-handoff plugin --path # Print only the manifest path
183
+ figma-handoff sync # Export once from Figma; requires CLI sync opt-in
184
+ figma-handoff help start # Help for a command
185
+ figma-handoff --version # Installed package version
186
+ ```
187
+
188
+ Sync is one-way from Figma to local files, not a continuous watcher; it does not
189
+ delete obsolete export folders. `init` is optional for interactive onboarding:
190
+ `start` can register a project. `open` is an experimental macOS-only shortcut
191
+ that starts the bridge and opens Figma. Keep the terminal open; Ctrl+C stops it.
192
+
193
+ ### Migrating from the scoped package
194
+
195
+ Stop the bridge before switching:
196
+
197
+ ```sh
198
+ npm uninstall -g @viettran210/figma-handoff-kit
199
+ npm install -g figma-handoff-kit
200
+ figma-handoff plugin --open
201
+ ```
202
+
203
+ Import the new manifest path in Figma Desktop, then reopen the plugin and run
204
+ `figma-handoff start`. Existing project registration and exported files are
205
+ preserved. The old package does not automatically upgrade to the new name.
package/bin/bridge.js ADDED
@@ -0,0 +1,171 @@
1
+ import { createServer } from 'node:http';
2
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync, realpathSync, lstatSync } from 'node:fs';
3
+ import { resolve, relative, dirname, basename, isAbsolute, sep } from 'node:path';
4
+ import { randomUUID, createHash } from 'node:crypto';
5
+ const hash = data => createHash('sha256').update(data).digest('hex');
6
+ const sanitize = name => { const value = String(name).replace(/[\\/*?:"<>|]/g, '_').trim(); if (['', '.', '..'].includes(value)) return 'unnamed'; let prefix = ''; for (const char of value) { if (Buffer.byteLength(prefix + char) > 120) return prefix + '--' + hash(value).slice(0, 12); prefix += char; } return value; };
7
+ const load = (path, fallback) => existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : fallback;
8
+ const atomic = (path, value) => { writeFileSync(path + '.tmp', JSON.stringify(value, null, 2)); renameSync(path + '.tmp', path); };
9
+ export function createBridge({ output, projectId, root }) {
10
+ output = resolve(output);
11
+ mkdirSync(output, { recursive: true });
12
+ output = realpathSync(output);
13
+ function safe(base, path) {
14
+ const dest = resolve(base, path);
15
+ const rel = relative(base, dest);
16
+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith('..' + sep)) throw new Error('Invalid export path');
17
+ let cursor = base;
18
+ for (const part of rel.split(sep)) {
19
+ cursor = resolve(cursor, part);
20
+ if (existsSync(cursor) && lstatSync(cursor).isSymbolicLink()) throw new Error('Symlink export paths are not allowed');
21
+ }
22
+ return dest;
23
+ }
24
+ function target(payload) {
25
+ if (payload.project_id !== projectId) throw new Error('Project changed; reconnect plugin before exporting');
26
+ if (!payload.document?.id || !Array.isArray(payload.node_path) || !payload.node_path.length) throw new Error('Document identity and node_path are required');
27
+ const file = safe(output, 'export-manifest.json');
28
+ const manifest = load(file, { version: 1, projectId, documents: {} });
29
+ if (manifest.projectId !== projectId) throw new Error('Output belongs to another project');
30
+ const id = String(payload.document.id);
31
+ if (['__proto__', 'constructor', 'prototype'].includes(id)) throw new Error('Invalid document ID');
32
+ const doc = manifest.documents[id] ??= { path: `${sanitize(payload.document.name || 'Figma')}--${hash(id).slice(0, 12)}`, nodes: {} };
33
+ doc.name = payload.document.name;
34
+ let parts = [doc.path];
35
+ let parentId = null;
36
+ for (const node of payload.node_path) {
37
+ const nodeId = String(node.id);
38
+ if (!node.id || ['__proto__', 'constructor', 'prototype'].includes(nodeId)) throw new Error('Invalid node ID');
39
+ let entry = doc.nodes[nodeId];
40
+ if (!entry) {
41
+ parts.push(`${sanitize(node.name)}--${hash(nodeId).slice(0, 12)}`);
42
+ entry = doc.nodes[nodeId] = { path: parts.join('/') };
43
+ } else parts = entry.path.split('/');
44
+ Object.assign(entry, { name: node.name, parentId });
45
+ parentId = nodeId;
46
+ }
47
+ const dest = safe(output, parts.join('/'));
48
+ atomic(file, manifest);
49
+ return dest;
50
+ }
51
+ function unchanged(payload, dest) {
52
+ try {
53
+ const state = load(safe(dest, '.export-checkpoint.json'), null);
54
+ return Boolean(payload.content_hash && state?.hash === payload.content_hash && state.files?.length && state.files.every(f => hash(readFileSync(safe(dest, f.name))) === f.hash));
55
+ } catch { return false; }
56
+ }
57
+ function guides(dest, files) {
58
+ const components = files.find(f => f.name === 'components_used.json');
59
+ if (components) {
60
+ const path = safe(output, 'DESIGN_SYSTEM_CATALOG.json');
61
+ const catalog = load(path, {});
62
+ for (const [name, data] of Object.entries(JSON.parse(components.content))) {
63
+ if (['__proto__', 'constructor', 'prototype'].includes(name)) continue;
64
+ const entry = catalog[name] ??= { componentSet: name, description: data.description || 'Shared Design System Component', totalUsageCount: 0, variantsEncountered: [], screensUsedIn: [], sampleSnippets: [], reuseRules: data.reuseRules || `Always reuse <${name}>. Do not create duplicate markup.` };
65
+ entry.totalUsageCount += data.totalUsageCount ?? 1;
66
+ const screen = relative(output, dest).split(sep).join('/');
67
+ if (!entry.screensUsedIn.includes(screen)) entry.screensUsedIn.push(screen);
68
+ for (const variant of data.variantsEncountered || []) {
69
+ const prior = entry.variantsEncountered.find(v => JSON.stringify(v.properties) === JSON.stringify(variant.properties));
70
+ if (prior) prior.count = (prior.count || 0) + (variant.count || 1); else entry.variantsEncountered.push(variant);
71
+ }
72
+ for (const sample of data.sampleUsages || []) if (sample.recommendedSnippet && !entry.sampleSnippets.includes(sample.recommendedSnippet)) entry.sampleSnippets.push(sample.recommendedSnippet);
73
+ }
74
+ atomic(path, catalog);
75
+ const lines = ['# Project Design System & Component Reuse Guide', '', '> Consult this catalog and reuse existing components before implementing screens.', '', '| Component | Usage | Screens |', '| --- | --- | --- |'];
76
+ const entries = Object.entries(catalog).sort((a,b) => b[1].totalUsageCount - a[1].totalUsageCount);
77
+ for (const [name, item] of entries) lines.push(`| ${name} | ${item.totalUsageCount} | ${item.screensUsedIn.length} |`);
78
+ for (const [name, item] of entries) lines.push('', `## ${name}`, item.description, '', item.reuseRules, '', '### Screens', ...item.screensUsedIn.map(p => `- ${p}`), '', '### Variants', '```json', JSON.stringify(item.variantsEncountered, null, 2), '```', '', '### Recommended snippets', '```jsx', ...item.sampleSnippets.slice(0,3), '```');
79
+ writeFileSync(safe(output, 'DESIGN_SYSTEM_GUIDE.md'), lines.join('\n') + '\n');
80
+ }
81
+ const fonts = files.find(f => f.name === 'fonts_guide.json');
82
+ if (fonts) {
83
+ const f = JSON.parse(fonts.content);
84
+ writeFileSync(safe(output, 'FONTS_SETUP.md'), ['# Project Fonts & Typography Setup', '', ...(f.fonts || []).map(font => `- ${font.family}: ${(font.weights || []).join(', ')}`), '', '## HTML', '```html', f.htmlLinkTag || '', '```', '', '## CSS', '```css', f.cssImportRule || '', `:root { --font-sans: ${f.cssFontFamilyStack || 'sans-serif'}; }`, 'body { font-family: var(--font-sans); }', '```', '', '## Tailwind', '```javascript', `module.exports = { theme: { extend: { fontFamily: { sans: [${f.cssFontFamilyStack || '"sans-serif"'}] } } } };`, '```'].join('\n'));
85
+ }
86
+ }
87
+ let queue = Promise.resolve();
88
+ let session = null;
89
+ let job = null;
90
+ return createServer(async (req, res) => {
91
+ res.setHeader('Access-Control-Allow-Origin', '*');
92
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
93
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
94
+ res.setHeader('Content-Type', 'application/json');
95
+ const send = (status, value) => { res.writeHead(status); res.end(JSON.stringify(value)); };
96
+ if (req.method === 'OPTIONS') return send(204, {});
97
+ if (req.method === 'GET' && ['/', '/health'].includes(req.url)) return send(200, { status: 'ok', exports_dir: output, project_id: projectId, project_name: basename(root), project_root: root, runtime: 'node', protocol_version: 1 });
98
+ if (req.method === 'GET' && req.url === '/sync/status') return send(200, { job, connected: !!session && Date.now() - session.seen < 10000 });
99
+ if (req.method !== 'POST' || !['/check', '/save', '/save-notes', '/sync/pair', '/sync/poll', '/sync/start', '/sync/result', '/sync/unpair'].includes(req.url)) return send(404, { error: 'Not found' });
100
+ try {
101
+ const chunks = []; let size = 0;
102
+ for await (const chunk of req) { size += chunk.length; if (size > 128 * 1024 * 1024) throw new Error('Upload exceeds 128 MiB'); chunks.push(chunk); }
103
+ const payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
104
+ if (req.url.startsWith('/sync/')) {
105
+ if (payload.project_id !== projectId) throw new Error('Wrong project');
106
+ if (req.url === '/sync/start') {
107
+ if (req.headers.origin) throw new Error('Sync must be requested by the local CLI');
108
+ if (!session || Date.now() - session.seen > 10000) throw new Error('Open the plugin, choose Save to project and enable CLI sync first.');
109
+ if (job && ['queued','running'].includes(job.state)) throw new Error('A sync is already running');
110
+ job = { id: randomUUID(), state:'queued', documentId:session.documentId, createdAt:Date.now() };
111
+ return send(200, job);
112
+ }
113
+ if (req.url === '/sync/pair') {
114
+ if (!payload.documentId) throw new Error('Document ID required');
115
+ if (session && Date.now()-session.seen < 10000) throw new Error('Another Figma document is paired; disable it first.');
116
+ session = { documentId:payload.documentId, token:randomUUID(), seen:Date.now() };
117
+ return send(200, { token:session.token });
118
+ }
119
+ if (!session || session.token !== payload.token || session.documentId !== payload.documentId) throw new Error('Pairing expired; enable CLI sync again.');
120
+ if (req.url === '/sync/unpair') {
121
+ session = null;
122
+ if (job && ['queued', 'running'].includes(job.state)) {
123
+ job.state = 'error'; job.error = 'CLI sync was disabled in the plugin; an export already started may still finish.';
124
+ }
125
+ return send(200, { success: true });
126
+ }
127
+ session.seen = Date.now();
128
+ if (req.url === '/sync/poll') {
129
+ if (job?.state === 'queued') { job.state='running'; return send(200,{ job }); }
130
+ return send(200,{ job:null });
131
+ }
132
+ if (req.url === '/sync/result') {
133
+ if (!job || job.id !== payload.jobId) throw new Error('Unknown sync');
134
+ job.state = payload.error ? 'error' : 'done'; job.error = payload.error; job.stats = payload.stats;
135
+ return send(200,{success:true});
136
+ }
137
+ }
138
+ const task = queue.then(() => {
139
+ const dest = target(payload);
140
+ if (req.url === '/check') {
141
+ if (typeof payload.snapshot === 'string') payload.content_hash = hash(payload.snapshot);
142
+ return { unchanged: unchanged(payload, dest), hash: payload.content_hash };
143
+ }
144
+ mkdirSync(dest, { recursive: true });
145
+ if (req.url === '/save-notes') {
146
+ const file = safe(dest, sanitize(payload.filename || 'flow_notes.md'));
147
+ writeFileSync(file, payload.content || ''); return { success: true, file };
148
+ }
149
+ if (!Array.isArray(payload.files) || !payload.files.length) throw new Error('No files provided');
150
+ const state = safe(dest, '.export-checkpoint.json');
151
+ if (existsSync(state)) unlinkSync(state);
152
+ const records = [];
153
+ for (const file of payload.files) {
154
+ if (file.name.startsWith('/') || file.name.split('/').some(p => ['.', '..'].includes(p))) throw new Error('Invalid filename');
155
+ const path = safe(dest, file.name.split('/').filter(Boolean).map(sanitize).join('/'));
156
+ if (path === state) throw new Error('Reserved checkpoint filename');
157
+ mkdirSync(dirname(path), { recursive: true });
158
+ const content = file.type === 'base64' ? Buffer.from(file.content, 'base64') : Buffer.from(file.content, 'utf8');
159
+ writeFileSync(path, content);
160
+ records.push({ name: relative(dest, path).split(sep).join('/'), hash: hash(content) });
161
+ }
162
+ guides(dest, payload.files);
163
+ if (payload.content_hash) atomic(state, { hash: payload.content_hash, files: records });
164
+ console.log(` Saved ${relative(output, dest)} (${records.length} files)`);
165
+ return { success: true, saved_to: dest, files: records.map(f => f.name) };
166
+ });
167
+ queue = task.catch(() => {});
168
+ send(200, await task);
169
+ } catch (error) { send(400, { success: false, error: error.message }); }
170
+ });
171
+ }
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { resolve, dirname, relative } from 'node:path';
4
+ import { ensurePortAvailable } from './port.js';
5
+ import { addProject, chooseProject, registerProject } from './projects.js';
6
+ import { createBridge } from './bridge.js';
7
+ import { configureFigma, openFigma } from './open-figma.js';
8
+ import { help } from './help.js';
9
+ import { showPlugin } from './plugin.js';
10
+
11
+ const configName = 'figma-export.config.json';
12
+ const args = process.argv.slice(2);
13
+ function option(name) {
14
+ const index = args.indexOf(name);
15
+ if (index < 0) return undefined;
16
+ if (!args[index + 1] || args[index + 1].startsWith('--')) throw new Error(`${name} requires a value`);
17
+ return args[index + 1];
18
+ }
19
+ function findConfig() {
20
+ let dir = process.cwd();
21
+ while (true) {
22
+ const candidate = resolve(dir, configName);
23
+ if (existsSync(candidate)) return candidate;
24
+ if (dirname(dir) === dir) return null;
25
+ dir = dirname(dir);
26
+ }
27
+ }
28
+ try {
29
+ const command = args[0];
30
+ const commands = ['start', 'serve', 'plugin', 'sync', 'init', 'open'];
31
+ if (command === '--version') {
32
+ if (args.length !== 1) throw new Error('Usage: figma-handoff --version');
33
+ console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
34
+ } else if (command === 'help') {
35
+ if (args.length > 2 || (args[1] && !commands.includes(args[1]))) throw new Error('Usage: figma-handoff help [start|serve|plugin|sync|init|open]');
36
+ console.log(help(args[1]));
37
+ } else if (!command || args.includes('--help') || args.includes('-h')) {
38
+ console.log(help(command));
39
+ } else if (command === 'plugin') {
40
+ await showPlugin(args.slice(1));
41
+ } else if (command === 'init') {
42
+ const root = process.cwd();
43
+ const legacy = resolve(root, configName);
44
+ if (existsSync(legacy)) {
45
+ const config = JSON.parse(readFileSync(legacy, 'utf8'));
46
+ registerProject({ root, projectId: config.projectId, outputDir: config.outputDir });
47
+ console.log('Existing configuration registered globally; legacy file was left unchanged.');
48
+ } else {
49
+ const project = await addProject(root, option('--output-dir') ?? (process.stdin.isTTY ? undefined : 'figma/exports'));
50
+ console.log(`Project registered globally.\nExports: ${resolve(root, project.outputDir)}\nRun figma-handoff start to launch the bridge.`);
51
+ }
52
+ } else if (command === 'sync') {
53
+ const project = await chooseProject(args.includes('--select'));
54
+ const port = Number(process.env.FIGMA_EXPORT_PORT || 3055);
55
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid bridge port.');
56
+ const base = `http://127.0.0.1:${port}`;
57
+ const health = await fetch(base+'/health', {signal:AbortSignal.timeout(3000)}).then(r=>r.json());
58
+ if (health.project_id !== project.projectId) throw new Error('Bridge is serving a different project. Run figma-handoff start --select first.');
59
+ const response = await fetch(base+'/sync/start', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({project_id:project.projectId}),signal:AbortSignal.timeout(3000)});
60
+ const started = await response.json();
61
+ if (!response.ok) throw new Error(started.error || 'Start failed; update bridge and plugin.');
62
+ console.log('Sync requested. Keep Figma and the plugin open.');
63
+ const deadline = Date.now()+15*60*1000;
64
+ while (Date.now()<deadline) {
65
+ await new Promise(resolve=>setTimeout(resolve,1000));
66
+ const status = await fetch(base+'/sync/status',{signal:AbortSignal.timeout(3000)}).then(r=>r.json());
67
+ if (status.job?.id !== started.id) throw new Error('Sync session changed');
68
+ if(status.job.state==='error') throw new Error(status.job.error);
69
+ if(status.job.state==='done') { const stats=status.job.stats || {}; console.log(`Sync complete · ${stats.checked || 0} checked · ${stats.saved || 0} saved · ${stats.skipped || 0} skipped`); break; }
70
+ if(!status.connected) throw new Error('Plugin disconnected; reopen it before retrying.');
71
+ if(Date.now()+1000>=deadline) throw new Error('Sync timed out; inspect the plugin before retrying.');
72
+ }
73
+ } else if (command === 'start' || command === 'serve' || command === 'open') {
74
+ const configPath = findConfig();
75
+ let project;
76
+ if (configPath && !args.includes('--select')) {
77
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
78
+ project = registerProject({ root: dirname(configPath), projectId: config.projectId, outputDir: config.outputDir });
79
+ } else {
80
+ project = await chooseProject(args.includes('--select'));
81
+ }
82
+ if (command === 'open') {
83
+ if (process.platform !== 'darwin') throw new Error('open currently supports macOS + Figma Desktop only.');
84
+ project = await configureFigma(project, option('--url'));
85
+ }
86
+ const root = project.root;
87
+ const config = project;
88
+ const output = resolve(root, project.outputDir);
89
+ const port = Number(process.env.FIGMA_EXPORT_PORT || 3055);
90
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid bridge port.');
91
+ await ensurePortAvailable(port);
92
+ const server = createBridge({ output, projectId: config.projectId, root });
93
+ server.on('error', error => {
94
+ console.error(error.code === 'EADDRINUSE' ? `Port ${port} became busy. Run figma-handoff start again.` : error.message);
95
+ process.exitCode = 1;
96
+ });
97
+ server.listen(port, '127.0.0.1', async () => {
98
+ console.log(`\n Figma Handoff Kit ● Ready\n\n Project ${root.split(/[\\/]/).pop()}\n Output ./${relative(root, output)}\n Bridge http://localhost:${port}\n\n Keep this terminal running on the same computer as Figma.\n Exports are saved locally in the selected project.\n Ctrl+C to stop\n`);
99
+ if (command === 'open') {
100
+ try { await openFigma(project); } catch (error) { console.error(`Cannot open Figma Desktop: ${error.message}`); server.close(); process.exitCode = 1; }
101
+ }
102
+ });
103
+ for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
104
+ } else {
105
+ console.error(`Unknown command: ${command}\nRun figma-handoff --help for usage.`);
106
+ process.exitCode = 1;
107
+ }
108
+ } catch (err) { console.error(args[0] === 'sync' && /fetch failed/.test(err.message) ? 'Cannot reach the bridge. Run figma-handoff start for this project, then enable CLI sync in the plugin.' : err.message); process.exitCode = 1; }