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/bin/help.js ADDED
@@ -0,0 +1,132 @@
1
+ export function help(command) {
2
+ const intro = 'Figma Handoff Kit — export Figma designs to a local project folder.\nRequires Node.js 20 or newer. No Python or cloud server required.\n';
3
+ const init = `USAGE
4
+ figma-handoff init [--output-dir <relative-path>]
5
+
6
+ Register the current directory as a project in the global registry.
7
+
8
+ OPTIONS
9
+ --output-dir <path> Output folder inside the project (e.g. docs/figma).
10
+ Prompts when omitted in a terminal; Enter uses
11
+ figma/exports. Non-interactive default: figma/exports.
12
+ -h, --help Show this help without creating files.
13
+
14
+ EXAMPLES
15
+ cd /path/to/repository
16
+ figma-handoff init
17
+ figma-handoff init --output-dir docs/figma
18
+
19
+ NOTES
20
+ Creates the output folder and stores project registration outside the repo.
21
+ Re-registering the same project keeps its project ID.
22
+ A legacy figma-export.config.json is imported if present and left unchanged;
23
+ --output-dir does not override that legacy file.
24
+ `;
25
+ const serve = `USAGE
26
+ figma-handoff start [--select]
27
+
28
+ Start the local bridge at http://localhost:3055.
29
+
30
+ OPTIONS
31
+ --select Choose another project, even inside a registered project.
32
+ -h, --help Show this help without starting a server.
33
+
34
+ PROJECT SELECTION
35
+ Inside a registered project: selects it automatically.
36
+ Outside projects: choose a registered project or add a new one.
37
+ Legacy config in the current directory or its ancestors takes precedence
38
+ unless --select is supplied.
39
+ Interactive selection requires a terminal; scripts should run inside
40
+ a registered project.
41
+
42
+ PORT CONFLICTS
43
+ Shows the listener and offers Stop or Exit in an interactive terminal.
44
+ Stopping requires confirmation. No automatic force kill.
45
+
46
+ EXAMPLES
47
+ figma-handoff start
48
+ figma-handoff start --select
49
+
50
+ WHILE RUNNING
51
+ Open the Figma Handoff Kit plugin on this same computer.
52
+ Check the project and output directory before exporting.
53
+ Keep this terminal open. Press Ctrl+C to stop.
54
+ `;
55
+ const open = `USAGE
56
+ figma-handoff open [--select] [--url <Figma HTTPS URL>]
57
+
58
+ macOS + Figma Desktop only. Starts the bridge and opens the project's saved
59
+ Figma file/section. First use asks for a URL; --url replaces it.
60
+ The URL is stored in the global project registry, not your repository.
61
+
62
+ The plugin must be installed/imported first. macOS Accessibility and
63
+ Automation → System Events permissions may be required for Quick Actions.
64
+ Quick Actions searches for Figma Handoff Kit; confirm the exact result with
65
+ Enter. No automatic export is performed. Keep this terminal open.
66
+
67
+ EXAMPLES
68
+ figma-handoff open --url "https://www.figma.com/design/FILE_KEY/Design?node-id=1-2"
69
+ figma-handoff open
70
+ figma-handoff open --select
71
+ `;
72
+ const sync = `USAGE
73
+ figma-handoff sync [--select]
74
+
75
+ Run figma-handoff start on this computer, open the plugin, choose Save to project and
76
+ check Allow CLI sync. This pairs the current Figma document to the bridge.
77
+ Sync exports all pages (excluding Trash), 2x, skipping unchanged screens.
78
+ Runs once, from Figma to local files. Does not watch, upload changes or delete
79
+ obsolete export folders.
80
+ Keep Figma, plugin and bridge running. Permission expires on plugin/bridge
81
+ restart. Ctrl+C stops waiting, not an export already running in Figma.
82
+ Timeout: 15 minutes. Results: checked, saved, skipped. No REST API is used.
83
+ `;
84
+ const plugin = `USAGE
85
+ figma-handoff plugin [--path | --open]
86
+
87
+ Show the installed manifest path and Figma Desktop import instructions.
88
+ --path Print only the absolute manifest path for copying or scripts.
89
+ --open Also open the folder in Finder or Windows Explorer.
90
+
91
+ EXAMPLES
92
+ figma-handoff plugin
93
+ figma-handoff plugin --open
94
+
95
+ Requires Figma Desktop on macOS/Windows for development import.
96
+ Import manually once; npm cannot register the plugin automatically.
97
+ `;
98
+ const overview = `USAGE
99
+ figma-handoff <command> [options]
100
+
101
+ COMMANDS
102
+ start Start the local bridge; select or add a project.
103
+ plugin Show the plugin manifest and import instructions.
104
+ sync Export once from Figma to local files (requires opt-in).
105
+ help [command] Show general or command-specific help.
106
+
107
+ OPTIONS
108
+ --version Print the installed package version.
109
+ -h, --help Show help. Supported after every command.
110
+
111
+ QUICK START
112
+ figma-handoff plugin --open
113
+ figma-handoff start
114
+
115
+ Import the plugin into Figma Desktop once. Keep the terminal open while
116
+ exporting. Press Ctrl+C to stop. To switch projects: start --select.
117
+
118
+ ADVANCED
119
+ init Register the current folder; supports --output-dir.
120
+ open Start bridge and open Figma (experimental, macOS only).
121
+
122
+ COMPATIBILITY
123
+ serve Alias for start.
124
+ figma-export Alias for figma-handoff.
125
+
126
+ MORE HELP
127
+ figma-handoff help start
128
+ figma-handoff plugin --help
129
+ figma-handoff sync --help
130
+ `;
131
+ return intro + '\n' + (command === 'init' ? init : (command === 'start' || command === 'serve') ? serve : command === 'open' ? open : command === 'sync' ? sync : command === 'plugin' ? plugin : overview);
132
+ }
@@ -0,0 +1,65 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { text, isCancel } from '@clack/prompts';
4
+ import { registerProject } from './projects.js';
5
+ const execute = promisify(execFile);
6
+ export function figmaLink(input) {
7
+ const url = new URL(input);
8
+ if (url.protocol !== 'https:' || !['figma.com','www.figma.com'].includes(url.hostname) || !/^\/(design|file)\/[a-zA-Z0-9]+(?:\/|$)/.test(url.pathname)) throw new Error('Enter a Figma design/file HTTPS URL, optionally including node-id.');
9
+ return url.toString();
10
+ }
11
+ export function desktopLink(input) {
12
+ const url = new URL(figmaLink(input));
13
+ return `figma://file/${url.pathname.split('/')[2]}${url.search}`;
14
+ }
15
+ export async function configureFigma(project, supplied) {
16
+ let value = supplied || project.figmaUrl;
17
+ if (!value) {
18
+ if (!process.stdin.isTTY) throw new Error('Use open --url <Figma URL> to configure this project.');
19
+ value = await text({ message: 'Figma file or section URL', validate: input => { try { figmaLink(input); } catch { return 'Enter a valid Figma design/file URL.'; } } });
20
+ if (isCancel(value)) throw new Error('Cancelled.');
21
+ }
22
+ const figmaUrl = figmaLink(value);
23
+ return registerProject({ ...project, figmaUrl });
24
+ }
25
+ export async function openFigma(project) {
26
+ // Pass URL as an argument, never interpolate it into AppleScript or a shell.
27
+ const deepLink = desktopLink(project.figmaUrl);
28
+ await execute('/usr/bin/open', ['-a', 'Figma', deepLink]);
29
+ try {
30
+ const result = await execute('/usr/bin/osascript', ['-e', `
31
+ tell application "Figma" to activate
32
+ tell application "System Events"
33
+ repeat 40 times
34
+ if exists process "Figma" then exit repeat
35
+ delay 0.25
36
+ end repeat
37
+ tell process "Figma"
38
+ set frontmost to true
39
+ delay 3
40
+ keystroke "/" using {command down}
41
+ delay 1
42
+ keystroke "Figma Handoff Kit"
43
+ delay 1
44
+ repeat with uiItem in (entire contents)
45
+ try
46
+ if name of uiItem is "Figma Handoff Kit" then
47
+ if role of uiItem is "AXButton" or role of uiItem is "AXMenuItem" then
48
+ perform action "AXPress" of uiItem
49
+ return "launched"
50
+ end if
51
+ end if
52
+ end try
53
+ end repeat
54
+ return "manual"
55
+ end tell
56
+ end tell
57
+ `], { timeout: 20000 });
58
+ if (result.stdout.trim() === 'launched') { console.log('Plugin launch requested. Choose options in the Figma popup; export requires your click.'); return; }
59
+ console.log('Figma Quick Actions is open with “Figma Handoff Kit”. Confirm the matching plugin with Enter. No export has started.');
60
+ } catch (error) {
61
+ console.error(`Plugin launch failed: ${(error.stderr || error.message).trim()}`);
62
+ console.error('System Settings → Privacy & Security → Accessibility: allow the terminal hosting this CLI. Also approve Automation → System Events when prompted.');
63
+ console.error('In Figma, use Quick Actions (⌘/) and run Figma Handoff Kit. Import the plugin first if missing.');
64
+ }
65
+ }
package/bin/plugin.js ADDED
@@ -0,0 +1,45 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname } from 'node:path';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+
7
+ export const pluginManifest = fileURLToPath(new URL('../figma-exporter-plugin/manifest.json', import.meta.url));
8
+
9
+ export async function showPlugin(args) {
10
+ if (args.some(arg => !['--path', '--open'].includes(arg))) throw new Error('Usage: figma-handoff plugin [--path | --open]');
11
+ if (args.includes('--path') && args.includes('--open')) throw new Error('Choose --path or --open, not both.');
12
+ for (const name of ['manifest.json', 'code.js', 'ui.html']) {
13
+ if (!existsSync(fileURLToPath(new URL('../figma-exporter-plugin/' + name, import.meta.url)))) {
14
+ throw new Error(`Plugin file missing: ${name}. Reinstall figma-handoff-kit.`);
15
+ }
16
+ }
17
+ if (args.includes('--path')) { console.log(pluginManifest); return; }
18
+ console.log(`Figma Handoff Kit — plugin setup
19
+
20
+ Manifest: ${pluginManifest}
21
+
22
+ 1. Open Figma Desktop (macOS or Windows), then a Design file you can edit.
23
+ 2. Plugins → Development → Import plugin from manifest…
24
+ 3. Select the manifest above. Keep code.js and ui.html beside it.
25
+ macOS file picker: press Cmd+Shift+G and paste the full manifest path.
26
+ Windows file picker: paste the full manifest path into File name.
27
+ 4. Plugins → Development → Figma Handoff Kit.
28
+ 5. Download ZIP, or run figma-handoff start and choose Save to project.
29
+
30
+ Import once per computer. npm installation does not register plugins in Figma.
31
+ After updating npm: restart the bridge and reopen the plugin. If you change
32
+ Node installations or remove this package, import again from its new path.
33
+ Can view only? Use an editable file/copy or ask the owner for edit access.
34
+ Organization policy may also require plugin approval.
35
+
36
+ Print just the path: figma-handoff plugin --path
37
+ Open its folder: figma-handoff plugin --open`);
38
+ if (args.includes('--open')) {
39
+ const commands = { darwin: ['open', [dirname(pluginManifest)]], win32: ['explorer.exe', [dirname(pluginManifest)]] };
40
+ const command = commands[process.platform];
41
+ if (!command) { console.log('Open the manifest folder manually; development import requires Figma Desktop on macOS/Windows.'); return; }
42
+ try { await promisify(execFile)(...command); }
43
+ catch { console.error('Could not open the folder automatically. Use the manifest path above.'); }
44
+ }
45
+ }
package/bin/port.js ADDED
@@ -0,0 +1,69 @@
1
+ import { createServer } from 'node:net';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { select, confirm, isCancel, note } from '@clack/prompts';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+
6
+ export function portBusy(port) {
7
+ return new Promise((resolve, reject) => {
8
+ const server = createServer();
9
+ server.once('error', err => err.code === 'EADDRINUSE' ? resolve(true) : reject(err));
10
+ server.listen({ host: '127.0.0.1', port, exclusive: true }, () => server.close(() => resolve(false)));
11
+ });
12
+ }
13
+ export function listeners(port) {
14
+ try {
15
+ if (process.platform === 'win32') {
16
+ const script = `Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique | ForEach-Object { Get-Process -Id $_ | Select-Object Id,ProcessName } | ConvertTo-Json -Compress`;
17
+ const raw = execFileSync('powershell.exe', ['-NoProfile', '-Command', script], { encoding: 'utf8', timeout: 3000 }).trim();
18
+ return raw ? [JSON.parse(raw)].flat().map(p => ({ pid: p.Id, name: p.ProcessName })) : [];
19
+ }
20
+ const output = execFileSync('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fpct'], { encoding: 'utf8', timeout: 3000 });
21
+ const result = [];
22
+ for (const line of output.split('\n')) {
23
+ if (line.startsWith('p')) result.push({ pid: Number(line.slice(1)), name: 'unknown' });
24
+ if (line.startsWith('c') && result.length) result.at(-1).name = line.slice(1);
25
+ }
26
+ return result.filter((p, i) => result.findIndex(q => q.pid === p.pid) === i);
27
+ } catch { return []; }
28
+ }
29
+ export async function ensurePortAvailable(port) {
30
+ if (!await portBusy(port)) return;
31
+ const owners = listeners(port);
32
+ if (process.stdin.isTTY && process.stdout.isTTY) {
33
+ note(owners.map(p => `${p.name} · PID ${p.pid}`).join("\n") || "Unknown process", `Port ${port} is in use`);
34
+ } else {
35
+ console.error(`Port ${port} is already in use.`);
36
+ }
37
+ if (!process.stdin.isTTY || !owners.length) {
38
+ throw new Error(owners.length ? 'Run figma-handoff start in an interactive terminal to choose Stop or Exit.' : 'Cannot identify the listener; no process was stopped.');
39
+ }
40
+ const action = await select({
41
+ message: 'How would you like to continue?',
42
+ initialValue: 'exit',
43
+ options: [
44
+ { value: 'stop', label: 'Stop listener and start bridge', hint: `Free port ${port}` },
45
+ { value: 'exit', label: 'Exit', hint: 'Keep existing service running' }
46
+ ]
47
+ });
48
+ if (isCancel(action) || action !== 'stop') throw new Error('Exited; existing service was left running.');
49
+ const approved = await confirm({
50
+ message: `Stop ${owners.map(p => `${p.name} (PID ${p.pid})`).join(', ')}? This may stop another application.`,
51
+ initialValue: false
52
+ });
53
+ if (isCancel(approved) || !approved) throw new Error('Cancelled; existing service was left running.');
54
+ const current = listeners(port);
55
+ if (JSON.stringify(current) !== JSON.stringify(owners)) throw new Error('Listener changed; run figma-handoff start again. No process was stopped.');
56
+ for (const owner of owners) {
57
+ if (owner.pid === process.pid || owner.pid <= 1) throw new Error('Refusing to stop this process.');
58
+ process.kill(owner.pid, 'SIGTERM');
59
+ if (process.platform !== 'win32') {
60
+ try { process.kill(owner.pid, 'SIGCONT'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
61
+ }
62
+ }
63
+ for (let attempt = 0; attempt < 50; attempt++) {
64
+ if (!await portBusy(port)) return;
65
+ await delay(100);
66
+ }
67
+ throw new Error(`Port ${port} is still busy after 5 seconds; no force kill was attempted.`);
68
+
69
+ }
@@ -0,0 +1,53 @@
1
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync } from 'node:fs';
2
+ import { resolve, dirname, basename, relative, isAbsolute, join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { select, text, isCancel } from '@clack/prompts';
6
+
7
+ export const registryFile = process.env.FIGMA_EXPORT_REGISTRY || join(homedir(), '.config', 'figma-export', 'projects.json');
8
+ export function readProjects() {
9
+ if (!existsSync(registryFile)) return [];
10
+ const data = JSON.parse(readFileSync(registryFile, 'utf8'));
11
+ if (data.version !== 1 || !Array.isArray(data.projects)) throw new Error('Invalid global project registry.');
12
+ return data.projects;
13
+ }
14
+ export function validateProject(project) {
15
+ const rel = relative(project.root, resolve(project.root, project.outputDir));
16
+ if (!project.projectId || !isAbsolute(project.root) || !project.outputDir || isAbsolute(project.outputDir) || !rel || rel === '..' || rel.startsWith('../') || rel.startsWith('..\\')) throw new Error('Invalid project root or output directory.');
17
+ if (!statSync(project.root).isDirectory()) throw new Error('Project directory does not exist.');
18
+ return project;
19
+ }
20
+ export function registerProject(project) {
21
+ validateProject(project);
22
+ const projects = readProjects();
23
+ const index = projects.findIndex(p => p.root === project.root);
24
+ if (index >= 0) projects[index] = project; else projects.push(project);
25
+ mkdirSync(dirname(registryFile), { recursive: true });
26
+ const tmp = `${registryFile}.${process.pid}.tmp`;
27
+ writeFileSync(tmp, JSON.stringify({ version: 1, projects }, null, 2) + '\n', { mode: 0o600 });
28
+ renameSync(tmp, registryFile);
29
+ return project;
30
+ }
31
+ function answer(value) {
32
+ if (isCancel(value)) throw new Error('Cancelled; no bridge was started.');
33
+ return value;
34
+ }
35
+ export async function addProject(root, outputDir) {
36
+ if (!root) root = resolve(answer(await text({ message: 'Project directory', placeholder: process.cwd(), defaultValue: process.cwd() })));
37
+ const previous = readProjects().find(p => p.root === root);
38
+ if (outputDir === undefined) outputDir = answer(await text({ message: 'Output directory relative to project', placeholder: 'figma/exports', defaultValue: previous?.outputDir || 'figma/exports' }));
39
+ const project = validateProject({ ...previous, root, outputDir: outputDir.trim() || 'figma/exports', projectId: previous?.projectId || randomUUID() });
40
+ mkdirSync(resolve(root, project.outputDir), { recursive: true });
41
+ return registerProject(project);
42
+ }
43
+ export async function chooseProject(forceSelect = false) {
44
+ const projects = readProjects();
45
+ const matches = projects.filter(p => { const rel = relative(p.root, process.cwd()); return !isAbsolute(rel) && rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\'); }).sort((a,b) => b.root.length - a.root.length);
46
+ if (!forceSelect && matches.length) return validateProject(matches[0]);
47
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('No current project. Run figma-handoff start in a terminal to select a project, or run init first.');
48
+ const value = answer(await select({
49
+ message: 'Choose a project',
50
+ options: [...projects.map(p => ({ value: p.root, label: basename(p.root), hint: `${p.root} → ${p.outputDir}` })), { value: '__add__', label: 'Add a new project' }]
51
+ }));
52
+ return value === '__add__' ? addProject() : validateProject(projects.find(p => p.root === value));
53
+ }