@finedesign/cli 0.7.0 → 0.8.1

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.
@@ -0,0 +1,138 @@
1
+ import fs from 'node:fs';
2
+ import { ToolError } from './errors.mjs';
3
+
4
+ const figmaData = JSON.parse(fs.readFileSync(new URL('./figma-data.json', import.meta.url), 'utf8'));
5
+
6
+ export function normalizeNodeId(nodeId) {
7
+ if (!nodeId || typeof nodeId !== 'string') return null;
8
+ const trimmed = nodeId.trim();
9
+ const match = trimmed.match(/^(\d+)[:-](\d+)$/);
10
+ return match ? `${match[1]}:${match[2]}` : null;
11
+ }
12
+
13
+ export function parseFigmaUrl(value) {
14
+ try {
15
+ const url = new URL(value);
16
+ if (!['http:', 'https:'].includes(url.protocol) || !['figma.com', 'www.figma.com'].includes(url.hostname)) return null;
17
+ const path = url.pathname.match(/^\/(?:design|file)\/([a-z\d]+)(?:\/branch\/([a-z\d]+))?(?:\/|$)/i);
18
+ if (!path) return null;
19
+ return { fileKey: path[2] || path[1], nodeId: normalizeNodeId(url.searchParams.get('node-id')) };
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ function matchedResult(match, query) {
26
+ return {
27
+ matched: true,
28
+ query,
29
+ component: match.component,
30
+ designName: match.designName,
31
+ nodeId: match.nodeId,
32
+ url: match.url,
33
+ fileKey: figmaData.fileKey,
34
+ codeConnect: {
35
+ templateId: match.templateId,
36
+ templateFile: match.file,
37
+ source: match.source,
38
+ imports: match.imports,
39
+ connectedComponent: match.connectedComponent,
40
+ wrapperSignature: match.wrapperSignature,
41
+ shortcut: match.shortcut,
42
+ businessInputs: match.businessInputs,
43
+ exampleSnippet: match.exampleSnippet,
44
+ exampleNodeId: match.exampleNodeId,
45
+ exampleImports: match.exampleImports
46
+ },
47
+ designProperties: match.properties,
48
+ recommendations: match.recommendations,
49
+ apiDocHint: `fine-design info ${match.component.split('.')[0]}`
50
+ };
51
+ }
52
+
53
+ export function resolveFigmaComponent(input = {}) {
54
+ const target = (input.target || input.url || input.nodeId || input.component || '').trim();
55
+ if (!target) {
56
+ throw new ToolError('INVALID_ARGUMENT', 'Target URL, node ID, or component name is required.', 2);
57
+ }
58
+
59
+ const isUrl = (!input.target && !!input.url) || /^[a-z][a-z\d+.-]*:\/\//i.test(target);
60
+ const url = isUrl ? parseFigmaUrl(target) : null;
61
+ if (isUrl && url?.fileKey !== figmaData.fileKey) {
62
+ return {
63
+ matched: false,
64
+ query: { input: target },
65
+ message: `Use a Figma design or file URL from the Fine Design library (${figmaData.fileKey}). For a project design, use Figma MCP to locate the library's main component first.`
66
+ };
67
+ }
68
+ const nodeId = isUrl ? url.nodeId : normalizeNodeId(target);
69
+ if (isUrl || nodeId || (!input.target && input.nodeId)) {
70
+ const query = { input: target, nodeId };
71
+ const match = figmaData.mappings.find((m) => m.nodeId === nodeId);
72
+ if (match) return matchedResult(match, query);
73
+ return {
74
+ matched: false,
75
+ query,
76
+ message: 'No mapped library node found. Use Figma MCP to locate the main component for a page, instance or variant, then query its URL or node ID.'
77
+ };
78
+ }
79
+
80
+ const searchName = target.toLowerCase().replace(/[-_\s]/g, '');
81
+ const canonicalName = (Object.hasOwn(figmaData.aliases, searchName) ? figmaData.aliases[searchName] : target).toLowerCase();
82
+
83
+ // Check known unmapped notes
84
+ for (const [unmappedName, note] of Object.entries(figmaData.unmappedNotes)) {
85
+ const unmappedLower = unmappedName.toLowerCase();
86
+ if (unmappedLower === searchName || unmappedLower === canonicalName) {
87
+ return {
88
+ matched: false,
89
+ unmapped: true,
90
+ component: unmappedName,
91
+ note,
92
+ fileKey: figmaData.fileKey,
93
+ apiDocHint: `fine-design info ${unmappedName}`
94
+ };
95
+ }
96
+ }
97
+
98
+ const exact = figmaData.mappings.filter((m) => m.component.toLowerCase() === canonicalName);
99
+ const primaryNodeId = figmaData.primaryLinks[exact[0]?.component];
100
+ const matchedEntry = exact.find((m) => m.nodeId === primaryNodeId) ?? exact[0]
101
+ ?? figmaData.mappings.find((m) => m.component.toLowerCase().replace(/[-_\s.]/g, '') === searchName)
102
+ ?? (searchName && figmaData.mappings.find((m) => m.designName.toLowerCase().includes(searchName) || m.component.toLowerCase().includes(searchName)));
103
+ if (matchedEntry) {
104
+ return matchedResult(matchedEntry, { input: target, component: matchedEntry.component });
105
+ }
106
+
107
+ // Suggestions when not matched
108
+ const suggestions = figmaData.mappings
109
+ .filter((m) => searchName && m.component.toLowerCase().includes(searchName.slice(0, 3)))
110
+ .map((m) => `${m.component} (${m.designName})`)
111
+ .slice(0, 5);
112
+
113
+ return {
114
+ matched: false,
115
+ query: { input: target },
116
+ message: `No matching Fine Design component found for "${target}".`,
117
+ ...(suggestions.length ? { suggestions } : {})
118
+ };
119
+ }
120
+
121
+ export function listFigmaComponents() {
122
+ return {
123
+ total: figmaData.mappings.length,
124
+ fileKey: figmaData.fileKey,
125
+ indexNodeId: figmaData.indexNodeId,
126
+ components: figmaData.mappings.map((m) => ({
127
+ component: m.component,
128
+ designName: m.designName,
129
+ nodeId: m.nodeId,
130
+ url: m.url,
131
+ templateId: m.templateId,
132
+ templateFile: m.file,
133
+ imports: m.imports,
134
+ shortcut: m.shortcut,
135
+ businessInputs: m.businessInputs
136
+ }))
137
+ };
138
+ }
package/src/core/html.cjs CHANGED
@@ -1,4 +1,4 @@
1
- function exampleHTML(resources, prefix, appScript) {
1
+ function exampleHTML(resources, prefix) {
2
2
  const url = (entry) => entry.url || `${prefix}${entry.path}`;
3
3
  const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
4
4
  const css = resources.fineDesignCss;
@@ -8,14 +8,6 @@ function exampleHTML(resources, prefix, appScript) {
8
8
  const entry = resources[name];
9
9
  return `<script defer src="${escape(url(entry))}" integrity="${escape(entry.integrity)}" crossorigin="anonymous" ${events(name)}></script>`;
10
10
  }).join('\n');
11
- const state = appScript ? '' : 'const [count, setCount] = React.useState(0);';
12
- const demo = appScript ? 'return h(window.FineDesignTaskList);' : `return h('div', { className: 'demo' },
13
- h('p', null, '每一次交互,都由真实组件驱动'),
14
- h('output', { className: 'demo-count', 'aria-live': 'polite' }, String(count).padStart(2, '0')),
15
- h('p', null, '试着点击按钮,开始你的第一次交互。'),
16
- h('div', { className: 'demo-actions' },
17
- h(FineDesign.Button, { type: 'primary', onClick: () => setCount(count + 1) }, '已点击 ' + count + ' 次'),
18
- h(FineDesign.Button, { type: 'normal', onClick: () => setCount(0) }, '重置')));`;
19
11
  return `<!doctype html>
20
12
  <html lang="zh-CN">
21
13
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
@@ -96,7 +88,7 @@ function exampleHTML(resources, prefix, appScript) {
96
88
  </main>
97
89
  <footer><span>Fine Design ${escape(resources.fineDesign.version)} / React ${escape(resources.react.version)}</span><span>组件通过 window.FineDesign 提供</span></footer>
98
90
  </div>
99
- ${appScript ? `<script src="${escape(appScript)}"></script>\n` : ''}<script>
91
+ <script>
100
92
  (() => {
101
93
  const loaded = new Set();
102
94
  const status = document.getElementById('runtime-status');
@@ -116,13 +108,19 @@ ${appScript ? `<script src="${escape(appScript)}"></script>\n` : ''}<script>
116
108
  if (!window.React || !window.FineDesign || !window.ReactDOM || typeof ReactDOM.createRoot !== 'function') throw new Error('Missing runtime');
117
109
  const h = React.createElement;
118
110
  function App() {
119
- ${state}
111
+ const [count, setCount] = React.useState(0);
120
112
  React.useEffect(() => {
121
113
  document.body.dataset.state = 'ready';
122
114
  document.getElementById('root').setAttribute('aria-busy', 'false');
123
115
  status.textContent = '运行时已就绪';
124
116
  }, []);
125
- ${demo}
117
+ return h('div', { className: 'demo' },
118
+ h('p', null, '每一次交互,都由真实组件驱动'),
119
+ h('output', { className: 'demo-count', 'aria-live': 'polite' }, String(count).padStart(2, '0')),
120
+ h('p', null, '试着点击按钮,开始你的第一次交互。'),
121
+ h('div', { className: 'demo-actions' },
122
+ h(FineDesign.Button, { type: 'primary', onClick: () => setCount(count + 1) }, '已点击 ' + count + ' 次'),
123
+ h(FineDesign.Button, { type: 'normal', onClick: () => setCount(0) }, '重置')));
126
124
  }
127
125
  ReactDOM.createRoot(document.getElementById('root')).render(h(App));
128
126
  }
@@ -82,7 +82,7 @@ export async function exportRuntime(runtime, output, dryRun = false) {
82
82
  const entry = runtime.resources[name];
83
83
  return [name, { ...entry, localPath: `vendor/${path.posix.basename(new URL(entry.url).pathname)}` }];
84
84
  }));
85
- const plannedFiles = ['index.html', 'task-list.html', 'task-list.js', 'runtime-lock.json', ...Object.values(resources).map((entry) => entry.localPath)];
85
+ const plannedFiles = ['index.html', 'runtime-lock.json', ...Object.values(resources).map((entry) => entry.localPath)];
86
86
  const report = { version: runtime.version, targetDir, plannedFiles, writtenFiles: [], dryRun };
87
87
  if (dryRun) return report;
88
88
  const files = new Map();
@@ -107,8 +107,6 @@ export async function exportRuntime(runtime, output, dryRun = false) {
107
107
  }
108
108
  const localResources = Object.fromEntries(Object.entries(resources).map(([name, entry]) => [name, { ...entry, url: entry.localPath }]));
109
109
  files.set('index.html', html.exampleHTML(localResources, './'));
110
- files.set('task-list.html', html.exampleHTML(localResources, './', 'task-list.js'));
111
- files.set('task-list.js', fs.readFileSync(new URL('../../skills/fine-design/references/task-list.js', import.meta.url)));
112
110
  files.set('runtime-lock.json', JSON.stringify({ schemaVersion: 1, version: runtime.version, manifestURL: runtime.manifestURL, resources }, null, 2) + '\n');
113
111
  const parent = path.dirname(targetDir);
114
112
  fs.mkdirSync(parent, { recursive: true });
package/src/mcp.mjs CHANGED
@@ -29,7 +29,9 @@ export async function startMcp() {
29
29
  lint_files: 'Scan code for Fine Design API traps. Pass an exact version if it cannot be detected from the targets.',
30
30
  get_component_example: 'List example IDs and titles, or pass exampleId to read source, dependencies and asset metadata. Version is optional. Set includeAssets with exampleId to include large assets.',
31
31
  list_browser_runtimes: 'Read the one currently hosted UMD version from its online manifest. Requires network access.',
32
- get_browser_runtime: 'Resolve a component version to versioned current UMD URLs and SRI loading tags. Version is optional (defaults to hosted version). Requires network access; never falls back to another version.'
32
+ get_browser_runtime: 'Resolve a component version to versioned current UMD URLs and SRI loading tags. Version is optional (defaults to hosted version). Requires network access; never falls back to another version.',
33
+ resolve_figma_component: 'Look up a Fine Design library node URL, library node ID, or component name in the offline Code Connect snapshot. Use Figma MCP first for page, frame, or instance links.',
34
+ list_figma_components: 'List all Figma-connected Fine Design components, node IDs, and Code Connect template IDs.'
33
35
  };
34
36
  server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Object.entries(schemas).map(([name, schema]) => ({
35
37
  name, description: descriptions[name], inputSchema: z.toJSONSchema(schema, { target: 'draft-07' }),
@@ -61,6 +63,12 @@ export async function startMcp() {
61
63
  const version = resolveLintVersion(args.version, targets);
62
64
  const { lintFiles } = await import('./core/lint.mjs');
63
65
  result = lintFiles(loadCatalog(version), targets);
66
+ } else if (toolName === 'resolve_figma_component') {
67
+ const { resolveFigmaComponent } = await import('./core/figma.mjs');
68
+ result = resolveFigmaComponent(args);
69
+ } else if (toolName === 'list_figma_components') {
70
+ const { listFigmaComponents } = await import('./core/figma.mjs');
71
+ result = listFigmaComponents();
64
72
  } else {
65
73
  const ver = resolveMcpVersion(args.version);
66
74
  result = queryCatalog(loadCatalog(ver), toolName, { ...args, version: ver });
@@ -1,30 +0,0 @@
1
- # Standalone Task Page
2
-
3
- Use this reference for a new standalone table with filters, pagination and draft editing. Preserve existing project components instead of replacing them with this sample.
4
-
5
- After discovering the hosted version, run:
6
-
7
- ```sh
8
- fine-design runtime --fd-version <exact-version> --output ./task-demo
9
- ```
10
-
11
- The destination must not exist. `--dry-run --format json` previews paths without downloading assets or writing files. Export downloads the four required resources once, checks their declared sizes and SHA-256, then installs the directory. Download, integrity or conflict failures leave the destination untouched. The current browser starter uses React 18's `createRoot`; verify compatibility when targeting a different React major.
12
-
13
- - `index.html`: existing button/runtime smoke example.
14
- - `task-list.html` and `task-list.js`: working local task example. No JSX transformer or extra dependency.
15
- - `vendor/`: pinned React, ReactDOM, Fine Design JavaScript and stylesheet.
16
- - `runtime-lock.json`: source manifest URL, exact resource metadata and local paths. This is an archive record, not a hosting manifest.
17
-
18
- Use the target host's normal local preview. Resource URLs are local and SRI is retained; the host must still permit the page's scripts and styles. No CDN fallback is needed for an exported directory. Keep the whole directory together when copying it.
19
-
20
- The complete [task-list.js](task-list.js) is also bundled with this Skill. It is a reference, not a runtime dependency: copy it into the deliverable before linking it. Its component is `window.FineDesignTaskList`; mount it after the runtime is loaded. The example stores status codes consistently, enables Radio keyboard focus, labels text inputs, keeps edits in a separate draft, and binds deletion to `PopConfirm.onOk`.
21
-
22
- ## Verify The Business Contract
23
-
24
- 1. From a later page, filter by keyword/status and reset; verify the matching rows and page number.
25
- 2. Create a task, reject an empty name, save a valid task, edit it, cancel an edit, then reopen it.
26
- 3. Cancel deletion, then confirm deletion; remove the last row on a later page and verify pagination clamps.
27
- 4. Use Tab and the component's supported keys to reach filters and actions; check focus and the actual accessible names in the target preview.
28
- 5. For extensions, define calendar-week versus rolling-date semantics explicitly. An export action must create a file or report a real result; mark intentionally unfinished actions. If tasks belong to multiple projects, new tasks must select or inherit the intended project.
29
-
30
- CLI lint checks API usage, not business correctness, accessibility compliance or visual layout. Report syntax/API tests, DOM behavior tests and actual browser/host checks separately. DOM-only checks cannot verify clipping, colors or responsive layout.
@@ -1,82 +0,0 @@
1
- /* 独立页面组合参考:运行时加载后用 React.createElement(window.FineDesignTaskList) 渲染。 */
2
- window.FineDesignTaskList = function FineDesignTaskList() {
3
- const React = window.React;
4
- const h = React.createElement;
5
- const { Button, Input, Select, Radio, NextTable, Pagination, Drawer, PopConfirm, Tag } = window.FineDesign;
6
- const [rows, setRows] = React.useState([
7
- { id: 1, name: '整理需求', status: 'todo' },
8
- { id: 2, name: '接口联调', status: 'doing' },
9
- { id: 3, name: '组件验收', status: 'done' },
10
- { id: 4, name: '补充用例', status: 'todo' },
11
- { id: 5, name: '检查交付', status: 'doing' }
12
- ]);
13
- const [keyword, setKeyword] = React.useState('');
14
- const [status, setStatus] = React.useState('all');
15
- const [page, setPage] = React.useState(1);
16
- const [size, setSize] = React.useState(2);
17
- const [draft, setDraft] = React.useState(null);
18
- const [error, setError] = React.useState('');
19
- const statuses = [{ label: '待规划', value: 'todo' }, { label: '进行中', value: 'doing' }, { label: '已完成', value: 'done' }];
20
- const filtered = rows.filter(row => (status === 'all' || row.status === status) && row.name.includes(keyword.trim()));
21
- const maxPage = Math.max(1, Math.ceil(filtered.length / size));
22
- React.useEffect(() => { if (page > maxPage) setPage(maxPage); }, [page, maxPage]);
23
-
24
- function edit(row) { setDraft({ ...row }); setError(''); }
25
- function close() { setDraft(null); setError(''); }
26
- function save() {
27
- const name = draft.name.trim();
28
- if (!name) { setError('请填写任务名称'); return; }
29
- const saved = { ...draft, name, id: draft.id ?? Math.max(0, ...rows.map(row => row.id)) + 1 };
30
- setRows(draft.id == null ? [saved, ...rows] : rows.map(row => row.id === saved.id ? saved : row));
31
- if (draft.id == null) setPage(1);
32
- close();
33
- }
34
- function column(title, width, render) {
35
- return h(NextTable.Column, { width }, h(NextTable.HeaderCell, null, title),
36
- h(NextTable.Cell, null, row => row?.id != null ? render(row) : null));
37
- }
38
- const fieldStyle = { display: 'grid', gap: 8 };
39
- return h('div', { style: { display: 'grid', gap: 16, padding: 20, color: 'var(--fd-color-text)' } },
40
- h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 12 } },
41
- h('strong', { 'aria-live': 'polite' }, '任务清单 · ' + filtered.length + ' 项'),
42
- h(Button, { type: 'primary', onClick: () => edit({ id: null, name: '', status: 'todo' }) }, '新建任务')),
43
- h('label', { style: fieldStyle }, '任务关键词', h(Input, {
44
- value: keyword, placeholder: '输入任务名称', allowClear: true,
45
- onChange: value => { setKeyword(value); setPage(1); }
46
- })),
47
- h(Radio.Group, { value: status, tabFocus: true, direction: 'horizontal', optionType: 'button', block: false,
48
- onChange: value => { setStatus(value); setPage(1); }
49
- }, [{ label: '全部任务', value: 'all' }, ...statuses].map(item => h(Radio, { key: item.value, value: item.value }, item.label))),
50
- h(Button, { onClick: () => { setKeyword(''); setStatus('all'); setPage(1); } }, '重置筛选'),
51
- h('div', { style: { overflowX: 'auto', minWidth: 0 } }, h(NextTable, {
52
- data: filtered.slice((page - 1) * size, page * size), rowKey: 'id', width: 780, autoHeight: true, fillHeight: false,
53
- renderEmpty: () => h('p', null, '暂无符合条件的任务')
54
- },
55
- column('编号', 100, row => String(row.id)),
56
- column('名称', 340, row => row.name),
57
- column('状态', 140, row => h(Tag, { type: row.status === 'done' ? 'success' : 'info' }, statuses.find(item => item.value === row.status).label)),
58
- column('操作', 200, row => h('div', { style: { display: 'flex', gap: 8 } },
59
- h(Button, { type: 'text', onClick: () => edit(row) }, '编辑'),
60
- h(PopConfirm, { content: '确认删除“' + row.name + '”?', text4Ok: '确认删除', text4Cancel: '取消',
61
- onOk: () => setRows(rows.filter(item => item.id !== row.id))
62
- }, h(Button, { type: 'text', danger: true }, '删除'))))
63
- )),
64
- h(Pagination, { page, size, sizeSet: [2, 5], count: filtered.length, showPageSize: value => value + ' 条/页',
65
- showTotal: count => '共 ' + count + ' 项', onPageChange: setPage,
66
- onSizeChange: value => { setSize(value); setPage(1); }
67
- }),
68
- draft && h(Drawer, { visible: true, placement: 'right', edge: { width: 'min(520px, 100vw)', top: 0 },
69
- title: draft.id == null ? '新建任务' : '编辑任务', onClose: close,
70
- footer: h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8 } },
71
- h(Button, { onClick: close }, '取消'), h(Button, { type: 'primary', onClick: save }, '保存'))
72
- }, h('div', { style: { display: 'grid', gap: 16 } },
73
- h('label', { style: fieldStyle }, '任务名称(必填)', h(Input, { value: draft.name,
74
- inputState: error ? 'error' : 'normal', onChange: value => { setDraft({ ...draft, name: value }); setError(''); }
75
- })),
76
- error && h('p', { role: 'alert' }, error),
77
- h('div', { style: fieldStyle }, h('span', null, '任务状态'), h(Select, { value: draft.status, options: statuses, 'aria-label': '任务状态',
78
- onChange: value => setDraft({ ...draft, status: value })
79
- })))
80
- )
81
- );
82
- };