@finedesign/cli 0.6.0 → 0.7.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.
@@ -2,15 +2,17 @@
2
2
  "schemaVersion": 1,
3
3
  "version": "1.25.0",
4
4
  "sourceKind": "repository-snapshot",
5
- "sourceRevision": "a88c1a76dc006929aa6ab9ce4f9de4ad0e926d0c",
5
+ "sourceRevision": "1c7c921d638a7db72b10c53b264eb2b0a0c3ec9c",
6
6
  "sourceDirty": false,
7
- "contentHash": "c2edf1d31c61e83fa7996dca770a5e9ef87a5e67ce5fd55ccd4922a6e6bfe450",
8
- "catalogSha256": "4b911bc129ea5a13070e2fcfac3a2f8d61087beb2758d2ae50b46e99180bba18",
7
+ "contentHash": "556790f5c8bb8d702b3db8b5fe8925560bcdad642eb4f28de32d74b8e800401a",
8
+ "catalogSha256": "66c94445015341755aebe2a51e2947a4c3a76f796718f337f0eb1a5a81c56fbc",
9
9
  "skillFiles": {
10
- "references/component-guide.md": "612948840948e65f250998231eaa16fc41e8e27b9c03b19af32571422ca8185a",
10
+ "references/component-guide.md": "a91d47075e1c9fc90e8c4a5160e645a4d6ba7d12903688014cd1a22b0c5ef627",
11
11
  "references/docs-slug-map.md": "440ce5cf137fd22eabfcc5b51c3f55b85174aa643773ef0cedd5df542e77bbc2",
12
- "references/imports-and-setup.md": "9a404ad7243f0fa734d34c5fd0106287ededf36bbc1693812917ce9cb9780e40",
12
+ "references/imports-and-setup.md": "12278a80918a003a2285da510a77e77521a2771d47ae7bd0c8ea3f9a181d8398",
13
+ "references/standalone-task-page.md": "97f05c06e1a4e7a9517d53ed6a358d9515d799e1b8c8731cbd50ccf060f3eaea",
14
+ "references/task-list.js": "8e9f7daea7b8a003b0eb4cc1fc510b4a2d37f6812c846c882c01fa23be5adf19",
13
15
  "references/theme-and-dark-mode.md": "2eccae4930ea993e7088eee03a4b4a0f1c839033079db5f21f8c60e0fe8168d1",
14
- "SKILL.md": "512ecee9c5208436cda70c56cd691354ab83e2d85115c4bc6f3c1e0658e458ba"
16
+ "SKILL.md": "ad0bb8cf8a588b28e06a2a786483cb54124198a1e2bdf2e99a4c178147cd7968"
15
17
  }
16
18
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@finedesign/cli",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Versioned Fine Design docs, code checks and agent setup for coding agents",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -7,25 +7,29 @@ user-invocable: true
7
7
 
8
8
  # Fine Design
9
9
 
10
- Use `/fine-design` for component pages, fixes, and reviews. This folder guides AI; generated code must run without resolving skill files.
10
+ Apply this skill proactively when the task asks for Fine Design pages or touches `@fx-ui/fine-design` / `window.FineDesign` components, including fixes and reviews. Do not wait for a `/fine-design` invocation. Unrelated tasks do not trigger CLI calls. This folder guides AI; generated code must run without resolving skill files.
11
+
12
+ Use the project-local `npx fine-design` when installed, otherwise the global `fine-design`; fall back to `npx -y @finedesign/cli` when neither is available. On the first Fine Design task in a workspace, run `doctor --format json` unless its result is already available in this session. This Skill is already loaded; do not read it again through `bundledSkillPath`. Reuse discovery and API results while the workspace, CLI and component versions remain unchanged. The public CLI is separate from the private component package; a failed private-package lookup does not prove the CLI is unavailable. Report the actual command and error if it fails.
11
13
 
12
14
  ## Workflow
13
15
 
14
16
  1. Identify the deliverable and runtime: existing package-based project, standalone browser page, fix, or read-only review. Standalone HTML and embedded pages may use the public CDN runtime without npm or private-registry credentials. Preserve compatible existing components and explicit user choices; follow [imports-and-setup.md](references/imports-and-setup.md) for runtime selection.
15
17
  2. In a package-based project, resolve Fine Design and React versions from installed packages or the lockfile; in this repository use the checked-out package and sources. In browser mode, use the selected runtime manifest and its compatibility evidence rather than requiring an installed package. State unknown versions instead of inventing them or upgrading dependencies to fit examples.
16
- 3. Query only the components needed at the exact target version. Prefer connected Fine Design MCP tools when matching-version data is available, or use the local CLI with `--format json`. Start with `info <component>` or `doc <component> --toc`. Fetch `example <component> <id>` source only when needed. Use `search` for unknown component names and `token` for theming. Check the installed CLI's help for supported commands. If the version is unknown or unsupported, consult matching local declarations/docs or verify browser exports and behavior. Resolve website pages through [docs-slug-map.md](references/docs-slug-map.md).
18
+ 3. Before implementation or review conclusions, verify only the relevant components at the exact target version; reuse matching results already read in this session. Prefer connected Fine Design MCP tools when matching-version data is available, or use the CLI with `--format json`. Start with `info <component>`; it includes example IDs, so fetch `example <component> <id>` source only when needed. Use `search` for unknown component names, `doc --toc` / `doc --section` for missing details, and `token` for theming. Do not default to full catalogs, full docs or `--help`. If the version is unknown or unsupported, consult matching local declarations/docs or verify browser exports and behavior. Resolve website pages through [docs-slug-map.md](references/docs-slug-map.md).
17
19
  4. Use the relevant sections of [component-guide.md](references/component-guide.md) for component selection and API traps. Consult other references only for the conditions below.
18
- 5. Run the existing build/type check (plus `fine-design lint <file>` when available) and verify the affected interaction with local test data. Report verified and unverified behavior. Reviews remain read-only.
20
+ 5. After code changes, run the existing build/type check (plus `fine-design lint <file>` when available) and verify the affected interaction with local test data. Check that filter wording matches its date/value semantics, primary actions produce their stated results, and filters/actions can be reached by keyboard. Report actual commands and results, distinguishing API lint, DOM tests, independent browser checks, target preview checks and unverified steps. A passing lint is not a business or visual acceptance result. Reviews remain read-only.
19
21
 
20
22
  ## Core Contracts
21
23
 
22
24
  - Use target-version public APIs and package-root imports from `@fx-ui/fine-design`; deep imports require an explicit request. Standalone HTML uses the public UMD exports.
23
25
  - Match the chosen component's schema, exports, and events. Keep filters, rows, and forms in the same stored value domain, and connect confirmations to actual mutations.
24
26
  - Runnable single-file output includes its styles/runtime setup and has no missing local helpers, assets, or CSS modules.
27
+ - If the requested Fine Design runtime is unavailable, report the failed command and cause without guessing. A native HTML substitute is not a Fine Design component implementation; label it as an alternative and do not claim official lint passed. If real components are mandatory, stop and report the blocker instead of substituting them.
25
28
 
26
29
  ## Read Only When Needed
27
30
 
28
31
  | Condition | Reference |
29
32
  | --- | --- |
30
33
  | Version mismatch, installation failures, unavailable docs, imports, or standalone setup | [imports-and-setup.md](references/imports-and-setup.md) |
34
+ | New standalone table with filters, pagination and draft editing, or offline runtime export | [standalone-task-page.md](references/standalone-task-page.md) |
31
35
  | Theme, dark mode, or scoped themes | [theme-and-dark-mode.md](references/theme-and-dark-mode.md) |
@@ -36,6 +36,7 @@ Use the sections relevant to the task. Selection choices are defaults for new wo
36
36
  | `Dialog` | Save via `onOk`; handle close/cancel via `onCancel` (clicking the close button triggers `onCancel`, so do not bind the same handler to both `onCancel` and deprecated `onCloseBtnClick`) |
37
37
  | `Tag` | Use semantic `type` or `style`; do not assume a `color` prop |
38
38
  | `Avatar` | Character fallback uses `name` |
39
+ | `Radio.Group` | Set `tabFocus: true` for keyboard-reachable filters/view switches; its default is false |
39
40
  | `SvgIcon`, built-in icons | Import built-in icons from `@fx-ui/fine-design` (56 icons such as `SearchOutlined`, `PlusOutlined`, `EditOutlined`, `DeleteOutlined`, `SyncOutlined`, `RotateOutlined`, `EllipsisOutlined`); verify names via declarations or CLI `search`/`doc` instead of inventing `@ant-design/icons` names like `SettingOutlined` or `ReloadOutlined` |
40
41
 
41
42
  The table declaration differs from common `columns` APIs:
@@ -64,5 +65,8 @@ render: (_value, record) => {
64
65
  - Reset page to `1` when filters or page size change, including `AutoComplete.onSearch` and `onChange`. Use the filtered total, and clamp the page after filtering or deletion reduces available pages.
65
66
  - Edit a draft separate from saved data. Validation/save failure preserves the draft and leaves the dialog open; cancel/close must not persist the edit. Expose pending/error feedback for asynchronous saves.
66
67
  - Verify affected behavior: change a filter from a later page; cancel then confirm removal; submit an invalid draft; cancel an edit; save and reopen another row. Choose checks for the actual change rather than testing every example.
68
+ - Check business wording against actual predicates (calendar week versus rolling days), ensure actions report real results, and verify keyboard access to filters, cards and actions. New multi-project records must select or inherit the intended project. CLI lint does not verify these business contracts.
69
+
70
+ For standalone HTML, see the bundled [task page](standalone-task-page.md). Use shared semantic tokens for page surfaces/text instead of recoloring every component; select exact theme tokens through `token` when needed.
67
71
 
68
72
  For full page patterns in this repository, consult `playground/product-list/index.tsx`. Outside it, reuse local project examples. These are references, not dependencies for single-file outputs.
@@ -12,7 +12,7 @@
12
12
 
13
13
  ## Component Installation And Registry
14
14
 
15
- The public `@finedesign/cli` package does not require company-registry credentials. Installing the component library `@fx-ui/fine-design` is separate. CLI documentation queries can use an explicit supported `--fd-version` without installing the component library.
15
+ The public `@finedesign/cli` package does not require company-registry credentials. Run `npx -y @finedesign/cli doctor --format json`; installing the component library `@fx-ui/fine-design` is separate. CLI documentation queries can use an explicit supported `--fd-version` without installing the component library. A missing local executable or a failed private-package lookup does not establish that the public CLI is unavailable. Report the actual command, exit code and error; distinguish registry, authentication and network failures without guessing.
16
16
 
17
17
  If component installation fails, inspect the effective configuration from the consuming project:
18
18
 
@@ -49,13 +49,15 @@ Use browser/CDN mode for standalone pages, embedded pages and previews without a
49
49
 
50
50
  ### Select Resources
51
51
 
52
- With CLI `0.2.0` or newer, use `fine-design runtime list --format json` and `fine-design runtime --fd-version <exact-version> --format json` (MCP: `list_browser_runtimes` / `get_browser_runtime`). Use `fine-design runtime --fd-version <exact-version> --format html > demo.html` for a runnable standalone example (add `--runtime-url` for an explicitly selected preview). Only the currently hosted version is available; offline documentation may include more versions. An unavailable version is an error, not a reason to change the requested version.
52
+ Run `npx -y @finedesign/cli runtime list --format json` first and check its exit code. Use a version from its `versions` result with `npx -y @finedesign/cli runtime --fd-version <exact-version> --format html > demo.html` for a standalone starting page, or `--format json` for resources (MCP: `list_browser_runtimes` / `get_browser_runtime`). Use `--runtime-url` only for an explicitly selected preview. Only the currently hosted version is available; offline documentation may include more versions. An unavailable version is an error, not a reason to change the requested version. If discovery fails, report the actual error instead of guessing asset URLs or repeatedly probing unrelated packages.
53
53
 
54
54
  1. Read the public [runtime manifest](https://fine-design-runtime.pages.dev/manifest.json). In this repository it is generated under `tools/fine-design/public/assets/react/fine-design-runtime/`. The manifest directly contains `version` and `resources`; there is no discovery pointer or historical version index.
55
55
  2. Resolve resource `path` relative to that manifest; `url` is used exactly. Hosted paths include the precise package version, such as `fine-design/1.25.0/fine-design.min.js`. There is no hash directory or releaseId. Resource SHA-256 and SRI still verify the exact bytes.
56
56
  3. The host retains only the current release files. Old URLs may disappear on upgrade; save matching resources yourself for long-lived standalone pages. Do not claim historical runtime availability from the CLI's offline catalog.
57
57
  4. If the manifest cannot be retrieved, report the failure and use an explicitly selected verified host or previously saved matching resources. The old unversioned website resources have been removed; do not fall back to them or substitute another component version.
58
58
 
59
+ For offline or CSP-restricted previews, use `fine-design runtime --fd-version <exact-version> --output ./demo` with a new destination directory. `--dry-run --format json` previews file paths. The export verifies sizes/SHA-256 before writing local resources, preserves SRI and records their remote provenance in `runtime-lock.json`; it also includes a working [task page](standalone-task-page.md). Initial export needs network access; subsequent pages reference only local resources. The host must still permit page scripts/styles. Existing destinations are rejected rather than overwritten.
60
+
59
61
  Load `fineDesignCss`, then `react`, `reactDOM`, `fineDesign`. Pin exact URLs and integrity in generated HTML and use `crossorigin="anonymous"`; the host must provide CORS. Do not drop SRI from a selected versioned runtime to hide an error. Avoid async scripts and conflicting second React instances. If an embedding host lacks compatible React globals, use a separate document/iframe.
60
62
 
61
63
  Use `--runtime-url <verified-base-url>` only for a clearly selected host. The default public host is `https://fine-design-runtime.pages.dev/`, verified after production deployment; local testing alone does not prove a host is live. Optional chart resources are loaded only for chart requests.
@@ -0,0 +1,30 @@
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.
@@ -0,0 +1,82 @@
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
+ };
package/src/cli.mjs CHANGED
@@ -7,7 +7,7 @@ import { validateInput } from './core/contracts.mjs';
7
7
  import { loadCatalog, readIndex } from './core/data.mjs';
8
8
  import { resolveLintVersion, resolveVersion } from './core/version.mjs';
9
9
  import { ToolError, errorResult } from './core/errors.mjs';
10
- import { listRuntimes, resolveRuntime } from './core/runtime.mjs';
10
+ import { listRuntimes, resolveRuntime, exportRuntime } from './core/runtime.mjs';
11
11
  import html from './core/html.cjs';
12
12
 
13
13
  const help = `Usage: fine-design <command> [arguments] [options]
@@ -32,8 +32,9 @@ Options:
32
32
  --project <directory> Project used to detect the installed version
33
33
  --component <name> Compare only this component (diff command only)
34
34
  --agent <cursor|claude|codex|all> Target agent configuration (init command only)
35
- --output <directory> Destination directory for extracted component (add command only)
36
- --force Overwrite existing files (init and add commands)
35
+ --output <directory> Destination for an example or offline runtime (add and runtime)
36
+ --force Update managed files or overwrite examples (init and add)
37
+ --dry-run Preview changes without writing (init, add and runtime --output)
37
38
  --runtime-url <url> Runtime hosting base URL (runtime command only)
38
39
  --format <text|json|markdown|html> Output format (markdown: doc/info/token; html: runtime)
39
40
  --section <heading> Doc section heading (exact or case-insensitive)
@@ -73,13 +74,21 @@ function runDoctor(values) {
73
74
  throw error;
74
75
  }
75
76
  }
77
+ const catalog = versionStatus === 'supported' ? loadCatalog(detectedVersion) : null;
76
78
  return {
77
79
  toolVersion: pkg.version,
78
80
  nodeVersion: process.version,
79
81
  projectDir,
80
82
  detectedVersion,
83
+ versionSource: detectedVersion === null ? null : values['fd-version'] !== undefined ? 'explicit' : 'project',
81
84
  versionStatus,
82
85
  availableVersions,
86
+ catalogSource: catalog ? {
87
+ sourceKind: catalog.sourceKind,
88
+ sourceRevision: catalog.sourceRevision,
89
+ sourceDirty: catalog.sourceDirty,
90
+ contentHash: catalog.contentHash
91
+ } : null,
83
92
  bundledSkillVersion: index.skillVersion,
84
93
  bundledSkillPath,
85
94
  bundledSkillAvailable,
@@ -101,15 +110,18 @@ function runInit(values) {
101
110
  const bundledSkillDir = fileURLToPath(new URL('../skills/fine-design', import.meta.url));
102
111
  const created = [];
103
112
  const updated = [];
113
+ const skipped = [];
114
+ const warnings = [];
104
115
 
105
116
  const agentInstructions = `# Fine Design Rules
106
117
 
107
- 开发或修改 Fine Design 页面时,在目标项目目录运行 CLI。项目已安装 CLI 时用 \`npx fine-design\`,否则用 \`npx -y @finedesign/cli\`。
118
+ 开发或修改 Fine Design 页面时,以及调试或评审涉及 \`@fx-ui/fine-design\` / \`window.FineDesign\` 的代码时,主动调用 CLI 核对组件 API,无需用户提醒。无关任务不触发。在目标工作目录运行:项目内已安装 CLI 时用 \`npx fine-design\`,否则使用全局 \`fine-design\`;两者均不可用时用 \`npx -y @finedesign/cli\`。
108
119
 
109
- 1. 运行 \`doctor --format json\` 并读取 \`bundledSkillPath\` 指向的 Skill。先确定交付形式。接入现有 React 工程时沿用项目组件版本、壳层和同类页面。
120
+ 1. 首次处理当前工作目录的 Fine Design 任务时,运行 \`doctor --format json\`,读取 \`bundledSkillPath\` 指向的 Skill;当前会话已加载则复用,不重复读取。同一工作目录、CLI 和组件版本未变化时复用诊断结果。先确定交付形式;接入现有 React 工程时沿用项目组件版本、壳层和同类页面。
110
121
  2. 交付独立 HTML 或无构建预览时,先单独运行 \`runtime list --format json\`,根据退出码判断清单是否可用。用 \`versions\` 返回的版本解析 UMD 资源,再查组件 API。
111
- 3. 按目标版本用 \`info\` 查组件 API。\`list --format json\` 从 \`components\` 数组读取组件,\`example <组件>\` 先列示例 ID,按需再读源码。
112
- 4. 对改动文件运行 \`lint\` 并执行项目已有检查。分别记录工程检查、UMD 清单解析和目标预览中的关键交互结果,标明未验证项。
122
+ 3. 实现或给出评审结论前,按目标版本用 \`info <组件> --format json\` 核对本次涉及的 API。同一版本已查资料可复用;组件不明确时才 \`search\`,需要示例时从 \`info\` 返回的 ID 读取源码,不默认运行全量 \`list\` 或读取全部文档。
123
+ 4. 有代码改动时,对改动文件运行 \`lint\` 并执行项目已有检查,验证受影响交互。分别记录实际执行的命令、检查结果和未验证项;只读评审不修改代码。
124
+ 5. CLI 与私有组件包是独立的;本地命令缺失或私有包查询失败不能证明公开 CLI 不存在。失败时记录实际命令、退出码和错误。真实组件不可用时,原生页面只能标为替代实现,不能声称通过官方 lint;若必须使用真实组件则报告阻碍。
113
125
  `;
114
126
 
115
127
  const cursorMdcContent = `---
@@ -120,72 +132,82 @@ alwaysApply: false
120
132
 
121
133
  ${agentInstructions}`;
122
134
 
123
- if (agent === 'cursor' || agent === 'all') {
124
- const cursorRulesFile = path.join(projectDir, '.cursorrules');
125
- if (!fs.existsSync(cursorRulesFile) || values.force) {
126
- fs.writeFileSync(cursorRulesFile, agentInstructions, 'utf8');
127
- created.push('.cursorrules');
128
- } else {
129
- const existing = fs.readFileSync(cursorRulesFile, 'utf8');
130
- if (!existing.includes('fine-design') && !existing.includes('@finedesign/cli')) {
131
- fs.appendFileSync(cursorRulesFile, `\n\n${agentInstructions}`, 'utf8');
132
- updated.push('.cursorrules');
133
- }
135
+ const startMarker = '<!-- fine-design:start -->';
136
+ const endMarker = '<!-- fine-design:end -->';
137
+ const managedInstructions = `${startMarker}\n${agentInstructions.trimEnd()}\n${endMarker}`;
138
+ function write(relative, content, overwrite = false) {
139
+ const filename = path.join(projectDir, relative);
140
+ const exists = fs.existsSync(filename);
141
+ if (exists && !overwrite) {
142
+ skipped.push(relative);
143
+ return;
134
144
  }
135
- const cursorRulesDir = path.join(projectDir, '.cursor', 'rules');
136
- fs.mkdirSync(cursorRulesDir, { recursive: true });
137
- const mdcFile = path.join(cursorRulesDir, 'fine-design.mdc');
138
- if (!fs.existsSync(mdcFile) || values.force) {
139
- fs.writeFileSync(mdcFile, cursorMdcContent, 'utf8');
140
- created.push('.cursor/rules/fine-design.mdc');
145
+ (exists ? updated : created).push(relative);
146
+ if (!values['dry-run']) {
147
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
148
+ fs.writeFileSync(filename, content);
141
149
  }
142
150
  }
143
-
144
- if (agent === 'claude' || agent === 'all') {
145
- const claudeSkillsDir = path.join(projectDir, '.claude', 'skills', 'fine-design');
146
- if (fs.existsSync(bundledSkillDir) && (!fs.existsSync(claudeSkillsDir) || values.force)) {
147
- fs.mkdirSync(claudeSkillsDir, { recursive: true });
148
- fs.cpSync(bundledSkillDir, claudeSkillsDir, { recursive: true });
149
- created.push('.claude/skills/fine-design/');
150
- }
151
- const claudeMdFile = path.join(projectDir, 'CLAUDE.md');
152
- if (!fs.existsSync(claudeMdFile) || values.force) {
153
- fs.writeFileSync(claudeMdFile, agentInstructions, 'utf8');
154
- created.push('CLAUDE.md');
151
+ function writeInstructions(relative) {
152
+ const filename = path.join(projectDir, relative);
153
+ if (!fs.existsSync(filename)) return write(relative, `${managedInstructions}\n`);
154
+ const existing = fs.readFileSync(filename, 'utf8');
155
+ const start = existing.indexOf(startMarker);
156
+ const end = existing.indexOf(endMarker);
157
+ if (start !== -1 || end !== -1) {
158
+ if (start === -1 || end < start || existing.indexOf(startMarker, start + startMarker.length) !== -1 || existing.indexOf(endMarker, end + endMarker.length) !== -1) {
159
+ skipped.push(relative);
160
+ warnings.push(`${relative}: invalid Fine Design markers; update manually.`);
161
+ } else if (values.force) {
162
+ write(relative, existing.slice(0, start) + managedInstructions + existing.slice(end + endMarker.length), true);
163
+ } else skipped.push(relative);
164
+ } else if (existing.includes('fine-design') || existing.includes('@finedesign/cli')) {
165
+ skipped.push(relative);
166
+ warnings.push(`${relative}: existing Fine Design instructions have no markers; update manually.`);
155
167
  } else {
156
- const existing = fs.readFileSync(claudeMdFile, 'utf8');
157
- if (!existing.includes('fine-design') && !existing.includes('@finedesign/cli')) {
158
- fs.appendFileSync(claudeMdFile, `\n\n${agentInstructions}`, 'utf8');
159
- updated.push('CLAUDE.md');
160
- }
168
+ write(relative, `${existing}\n\n${managedInstructions}\n`, true);
161
169
  }
162
170
  }
163
-
164
- if (agent === 'codex' || agent === 'all') {
165
- const codexSkillsDir = path.join(projectDir, '.agents', 'skills', 'fine-design');
166
- if (fs.existsSync(bundledSkillDir) && (!fs.existsSync(codexSkillsDir) || values.force)) {
167
- fs.mkdirSync(codexSkillsDir, { recursive: true });
168
- fs.cpSync(bundledSkillDir, codexSkillsDir, { recursive: true });
169
- created.push('.agents/skills/fine-design/');
171
+ function writeSkill(relative) {
172
+ const target = path.join(projectDir, relative);
173
+ if (fs.existsSync(target) && !values.force) {
174
+ skipped.push(`${relative}/`);
175
+ return;
170
176
  }
171
- const agentsMdFile = path.join(projectDir, 'AGENTS.md');
172
- if (!fs.existsSync(agentsMdFile) || values.force) {
173
- fs.writeFileSync(agentsMdFile, agentInstructions, 'utf8');
174
- created.push('AGENTS.md');
175
- } else {
176
- const existing = fs.readFileSync(agentsMdFile, 'utf8');
177
- if (!existing.includes('fine-design') && !existing.includes('@finedesign/cli')) {
178
- fs.appendFileSync(agentsMdFile, `\n\n${agentInstructions}`, 'utf8');
179
- updated.push('AGENTS.md');
177
+ function copyFiles(source, destination) {
178
+ for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
179
+ const src = path.join(source, entry.name);
180
+ const dest = path.join(destination, entry.name);
181
+ if (entry.isDirectory()) copyFiles(src, dest);
182
+ else if (entry.isFile()) write(dest, fs.readFileSync(src), values.force);
180
183
  }
181
184
  }
185
+ if (fs.existsSync(bundledSkillDir)) copyFiles(bundledSkillDir, relative);
186
+ }
187
+
188
+ if (agent === 'cursor' || agent === 'all') {
189
+ writeInstructions('.cursorrules');
190
+ write('.cursor/rules/fine-design.mdc', cursorMdcContent, values.force);
191
+ }
192
+
193
+ if (agent === 'claude' || agent === 'all') {
194
+ writeSkill('.claude/skills/fine-design');
195
+ writeInstructions('CLAUDE.md');
196
+ }
197
+
198
+ if (agent === 'codex' || agent === 'all') {
199
+ writeSkill('.agents/skills/fine-design');
200
+ writeInstructions('AGENTS.md');
182
201
  }
183
202
 
184
203
  return {
185
204
  projectDir,
186
205
  agent,
187
206
  created: [...new Set(created)],
188
- updated: [...new Set(updated)]
207
+ updated: [...new Set(updated)],
208
+ skipped,
209
+ warnings,
210
+ dryRun: Boolean(values['dry-run'])
189
211
  };
190
212
  }
191
213
 
@@ -235,13 +257,20 @@ function runAdd(componentArg, exampleArg, values) {
235
257
  const prefix = sourceDir === '.' ? '' : `${sourceDir}/`;
236
258
  const files = example.files.map((file) => ({ file, destPath: path.join(targetDir, file.path.slice(prefix.length)) }));
237
259
  const writtenFiles = [];
260
+ const created = [];
261
+ const updated = [];
262
+ const conflicts = [];
238
263
 
239
264
  for (const { destPath } of files) {
240
- if (fs.existsSync(destPath) && !values.force) {
241
- throw new ToolError('FILE_EXISTS', `File already exists: ${path.relative(projectDir, destPath)}. Use --force to overwrite.`, 1);
242
- }
265
+ const relative = path.relative(projectDir, destPath);
266
+ if (!fs.existsSync(destPath)) created.push(relative);
267
+ else if (values.force) updated.push(relative);
268
+ else conflicts.push(relative);
269
+ }
270
+ if (conflicts.length && !values['dry-run']) {
271
+ throw new ToolError('FILE_EXISTS', `File already exists: ${conflicts[0]}. Use --force to overwrite.`, 1);
243
272
  }
244
- for (const { file, destPath } of files) {
273
+ for (const { file, destPath } of values['dry-run'] ? [] : files) {
245
274
  fs.mkdirSync(path.dirname(destPath), { recursive: true });
246
275
  if (file.encoding === 'base64') {
247
276
  fs.writeFileSync(destPath, Buffer.from(file.content, 'base64'));
@@ -261,6 +290,10 @@ function runAdd(componentArg, exampleArg, values) {
261
290
  version,
262
291
  targetDir: path.relative(projectDir, targetDir) || '.',
263
292
  writtenFiles,
293
+ created,
294
+ updated,
295
+ conflicts,
296
+ dryRun: Boolean(values['dry-run']),
264
297
  dependencies: example.dependencies || [],
265
298
  requiredDependencies
266
299
  };
@@ -274,7 +307,7 @@ export async function main(argv) {
274
307
  format: { type: 'string' }, section: { type: 'string' }, toc: { type: 'boolean' }, summary: { type: 'boolean' },
275
308
  offset: { type: 'string' }, limit: { type: 'string' }, 'include-assets': { type: 'boolean' },
276
309
  'runtime-url': { type: 'string' }, component: { type: 'string' },
277
- agent: { type: 'string' }, output: { type: 'string' }, force: { type: 'boolean' }
310
+ agent: { type: 'string' }, output: { type: 'string' }, force: { type: 'boolean' }, 'dry-run': { type: 'boolean' }
278
311
  }});
279
312
  format = values.format || 'text';
280
313
  if (!['text', 'json', 'markdown', 'html'].includes(format)) throw new ToolError('INVALID_ARGUMENT', 'Unknown output format.', 2);
@@ -286,8 +319,9 @@ export async function main(argv) {
286
319
  if (command !== 'runtime' && (values['runtime-url'] !== undefined)) throw new ToolError('INVALID_ARGUMENT', 'Runtime options are only supported for runtime.', 2);
287
320
  if (command !== 'diff' && values.component !== undefined) throw new ToolError('INVALID_ARGUMENT', '--component is only supported for diff.', 2);
288
321
  if (command !== 'init' && values.agent !== undefined) throw new ToolError('INVALID_ARGUMENT', '--agent is only supported for init.', 2);
289
- if (command !== 'add' && values.output !== undefined) throw new ToolError('INVALID_ARGUMENT', '--output is only supported for add.', 2);
322
+ if (!['add', 'runtime'].includes(command) && values.output !== undefined) throw new ToolError('INVALID_ARGUMENT', '--output is only supported for add and runtime.', 2);
290
323
  if (!['init', 'add'].includes(command) && values.force !== undefined) throw new ToolError('INVALID_ARGUMENT', '--force is only supported for init and add.', 2);
324
+ if (!['init', 'add', 'runtime'].includes(command) && values['dry-run'] !== undefined) throw new ToolError('INVALID_ARGUMENT', '--dry-run is only supported for init, add and runtime --output.', 2);
291
325
  if (format === 'markdown' && !['doc', 'info', 'token'].includes(command)) {
292
326
  throw new ToolError('INVALID_ARGUMENT', 'Markdown output format is only supported for the doc, info and token commands.', 2);
293
327
  }
@@ -295,7 +329,13 @@ export async function main(argv) {
295
329
  if (command === 'runtime') {
296
330
  const list = args.length === 1 && args[0] === 'list';
297
331
  if ((!list && args.length) || values.version || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined || (list && (values['fd-version'] !== undefined || values.project !== undefined))) throw new ToolError('INVALID_ARGUMENT', 'Use runtime [list] with --fd-version and --runtime-url as applicable.', 2);
332
+ if ((list && (values.output !== undefined || values['dry-run'] !== undefined)) || (values['dry-run'] !== undefined && values.output === undefined) || (values.output !== undefined && (!values.output.trim() || !['text', 'json'].includes(format)))) throw new ToolError('INVALID_ARGUMENT', 'Use runtime --output <new-directory> [--dry-run] [--format text|json].', 2);
298
333
  const result = list ? await listRuntimes(values['runtime-url']) : await resolveRuntime({ version: resolveVersion(values['fd-version'], values.project), runtimeURL: values['runtime-url'] });
334
+ if (values.output !== undefined) {
335
+ const report = await exportRuntime(result, path.resolve(values.project || process.cwd(), values.output), Boolean(values['dry-run']));
336
+ console.log(format === 'json' ? JSON.stringify(report) : `${report.dryRun ? 'Preview' : 'Exported'} Fine Design ${report.version} to ${report.targetDir}:\n${report.plannedFiles.map((name) => ` ${name}`).join('\n')}`);
337
+ return;
338
+ }
299
339
  console.log(format === 'html' ? html.exampleHTML(result.resources, './').trimEnd() : format === 'json' ? JSON.stringify(result) : list ? result.versions.join('\n') : `Fine Design ${result.version} (offline docs: ${result.docsAvailable ? 'available' : 'not bundled'})\n${result.tags}\nExample: ${result.exampleURL}`);
300
340
  return;
301
341
  }
@@ -310,8 +350,9 @@ export async function main(argv) {
310
350
  const lines = [
311
351
  `CLI version: ${report.toolVersion} (Node ${report.nodeVersion})`,
312
352
  `Project directory: ${report.projectDir}`,
313
- `Detected Fine Design: ${report.detectedVersion ?? 'none'} (${report.versionStatus})`,
353
+ `Fine Design version: ${report.detectedVersion ?? 'none'} (${report.versionStatus}${report.versionSource ? `, ${report.versionSource}` : ''})`,
314
354
  `Bundled catalogs: ${report.availableVersions.join(', ')}`,
355
+ ...(report.catalogSource ? [`Catalog source: ${report.catalogSource.sourceKind} ${report.catalogSource.sourceRevision}${report.catalogSource.sourceDirty ? ' (dirty)' : ''}`] : []),
315
356
  `Bundled Skill (${report.bundledSkillVersion}): ${report.bundledSkillPath}`
316
357
  ];
317
358
  if (report.suggestions?.length) lines.push(`Suggestions:\n${report.suggestions.map((item) => ` - ${item}`).join('\n')}`);
@@ -321,18 +362,21 @@ export async function main(argv) {
321
362
  }
322
363
  if (command === 'init') {
323
364
  if (values.version || args.length > 0 || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined || values['fd-version'] !== undefined || !['text', 'json'].includes(format)) {
324
- throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design init [--agent <cursor|claude|codex|all>] [--project <dir>] [--force] [--format text|json]', 2);
365
+ throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design init [--agent <cursor|claude|codex|all>] [--project <dir>] [--force] [--dry-run] [--format text|json]', 2);
325
366
  }
326
367
  const report = runInit(values);
327
368
  if (format === 'json') {
328
369
  console.log(JSON.stringify(report));
329
370
  } else {
330
371
  const lines = [
331
- `Initialized Fine Design agent configuration (${report.agent}) in ${report.projectDir}:`,
372
+ `${report.dryRun ? 'Preview' : 'Initialized'} Fine Design agent configuration (${report.agent}) in ${report.projectDir}:`,
332
373
  ' Created files:',
333
374
  ...(report.created.length ? report.created.map((f) => ` - ${f}`) : [' - none']),
334
375
  ' Updated files:',
335
- ...(report.updated.length ? report.updated.map((f) => ` - ${f}`) : [' - none'])
376
+ ...(report.updated.length ? report.updated.map((f) => ` - ${f}`) : [' - none']),
377
+ ' Skipped files:',
378
+ ...(report.skipped.length ? report.skipped.map((f) => ` - ${f}`) : [' - none']),
379
+ ...report.warnings.map((warning) => ` Warning: ${warning}`)
336
380
  ];
337
381
  console.log(lines.join('\n'));
338
382
  }
@@ -340,15 +384,18 @@ export async function main(argv) {
340
384
  }
341
385
  if (command === 'add') {
342
386
  if (values.version || args.length < 1 || args.length > 2 || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined || !['text', 'json'].includes(format)) {
343
- throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design add <component> [id] [--output <dir>] [--force] [--fd-version <version>] [--format text|json]', 2);
387
+ throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design add <component> [id] [--output <dir>] [--force] [--dry-run] [--fd-version <version>] [--format text|json]', 2);
344
388
  }
345
389
  const report = runAdd(args[0], args[1], values);
346
390
  if (format === 'json') {
347
391
  console.log(JSON.stringify(report));
348
392
  } else {
349
393
  const lines = [
350
- `Added ${report.component} (${report.exampleId}) to ${report.targetDir}:`,
351
- ...report.writtenFiles.map((f) => ` - ${f}`)
394
+ `${report.dryRun ? 'Preview' : 'Added'} ${report.component} (${report.exampleId}) to ${report.targetDir}:`,
395
+ ...report.created.map((f) => ` Create: ${f}`),
396
+ ...report.updated.map((f) => ` Overwrite: ${f}`),
397
+ ...report.conflicts.map((f) => ` Conflict: ${f}`),
398
+ ...(report.conflicts.length ? [' No files will be written unless conflicts are resolved or --force is used.'] : [])
352
399
  ];
353
400
  if (report.requiredDependencies.length) {
354
401
  lines.push('', 'Required dependencies:', ` npm install ${report.requiredDependencies.join(' ')}`);
@@ -489,7 +536,7 @@ export async function main(argv) {
489
536
  });
490
537
  return [` - ${exports.join('/')} (${id})`, ...details].join('\n');
491
538
  }),
492
- ...(result.migrations.length ? ['Recommended migrations:', ...result.migrations.map((m) => ` - ${m.legacy} -> ${m.recommended}: ${m.note}`)] : [])
539
+ ...(result.migrations.length ? ['Recommended migrations (general guidance, not specific to these versions):', ...result.migrations.map((m) => ` - ${m.legacy} -> ${m.recommended}: ${m.note}`)] : [])
493
540
  ].join('\n'));
494
541
  }
495
542
  return;
@@ -484,6 +484,7 @@ export function diffCatalogs(fromCatalog, toCatalog, component) {
484
484
  addedComponents,
485
485
  removedComponents,
486
486
  updatedComponents,
487
+ migrationScope: 'general',
487
488
  migrations: [
488
489
  { components: ['table', 'data-table', 'next-table'], legacy: 'Table / DataTable', recommended: 'NextTable', note: 'Use <NextTable> with declarative <NextTable.Column>, <NextTable.HeaderCell>, and <NextTable.Cell dataKey="..."> children.' },
489
490
  { components: ['cascader', 'm-cascader'], legacy: 'Cascader', recommended: 'MCascader', note: 'Legacy Cascader has no online docs page; prefer MCascader for new pages.' },