@finedesign/cli 0.0.0-stage → 0.1.0-rc.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.
@@ -0,0 +1,16 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "version": "1.24.9",
4
+ "sourceKind": "repository-snapshot",
5
+ "sourceRevision": "47587888b8857bab7565961347b2cf0de9a34693",
6
+ "sourceDirty": true,
7
+ "contentHash": "d5cc537c066dfe3537fcfb48929fa82daff9a46b4afd87770652a7e6e76bef5f",
8
+ "catalogSha256": "336f4c4d3d163e73df57ba2a4eeab7deb76659e86eb48d3242d9971e9ada60fa",
9
+ "skillFiles": {
10
+ "references/component-guide.md": "25508c9f1a36708d5dd221ca94a5942ba714cf199ce38a5eefd9cc4a9344bc36",
11
+ "references/docs-slug-map.md": "87e6814abe1a9509e99fcd92590756416db16a9394ff35aafc1729a7bacd2ae5",
12
+ "references/imports-and-setup.md": "a111bed0b13064b5be3bcec2b899fdd471e0e136c5d0a576ea62248fa35ac753",
13
+ "references/theme-and-dark-mode.md": "84aa0ff4245a989c1ccd6028e687946b71c1a0bebf8fd3893b09e5acd622478a",
14
+ "SKILL.md": "c94b678c5e714d0afb9eddf196795cc80561de58fcda700d7bf7849a37791074"
15
+ }
16
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "versions": {
4
+ "1.24.9": {
5
+ "catalog": "1.24.9/catalog.json",
6
+ "manifest": "1.24.9/manifest.json"
7
+ }
8
+ },
9
+ "skillVersion": "1.24.9"
10
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
- "name": "@finedesign/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@finedesign/cli",
3
+ "version": "0.1.0-rc.0",
4
+ "description": "Read-only, versioned Fine Design documentation for coding agents",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "registry": "https://registry.npmjs.org/",
8
+ "@finedesign:registry": "https://registry.npmjs.org/",
9
+ "access": "public"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "fine-design": "bin/fine-design.mjs"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "data",
19
+ "skills",
20
+ "README.md",
21
+ "CHANGELOG.md",
22
+ "LICENSE"
23
+ ],
24
+ "scripts": {
25
+ "start": "node bin/fine-design.mjs mcp"
26
+ },
27
+ "dependencies": {
28
+ "@modelcontextprotocol/sdk": "1.32.2",
29
+ "zod": "4.6.7"
30
+ },
31
+ "engines": {
32
+ "node": ">=20"
33
+ }
34
+ }
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: fine-design
3
+ description: '构建、修复、调试或评审 @fx-ui/fine-design 业务页面,聚焦组件选型、公开 API、主题与独立 React/TSX/HTML 示例。'
4
+ argument-hint: 'Describe the component page or fix and the output format.'
5
+ user-invocable: true
6
+ ---
7
+
8
+ # Fine Design
9
+
10
+ Use `/fine-design` for component pages, fixes, and reviews. This folder guides AI; generated code must run without resolving skill files.
11
+
12
+ ## Workflow
13
+
14
+ 1. Identify the deliverable: integrated page, standalone React/TSX/HTML, fix, or read-only review. Preserve compatible existing components and explicit user choices.
15
+ 2. Confirm the actual Fine Design and React versions. Use matching local docs, public declarations, and demos; in consuming projects, resolve online pages through [docs-slug-map.md](references/docs-slug-map.md). Inspect implementation only when the public contract is insufficient. State gaps instead of guessing APIs or upgrading dependencies to fit examples.
16
+ 3. When available, prefer the connected Fine Design MCP tools; otherwise use the local `fine-design` CLI with `--format json` and the exact installed component version. Query only the components and examples needed; if neither is available, use matching local documentation and public declarations.
17
+ 4. For ordinary component work, read the relevant sections of [component-guide.md](references/component-guide.md). Consult other references only for the conditions below.
18
+ 5. Run the existing build/type check appropriate to the change and verify an affected interaction with local test data. Fix introduced failures and recheck. Report actual results and unverified behavior; reviews remain read-only.
19
+
20
+ ## Core Contracts
21
+
22
+ - 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
+ - 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
+ - Runnable single-file output includes its styles/runtime setup and has no missing local helpers, assets, or CSS modules.
25
+
26
+ ## Read Only When Needed
27
+
28
+ | Condition | Reference |
29
+ | --- | --- |
30
+ | Version mismatch, unavailable docs, imports, or standalone setup | [imports-and-setup.md](references/imports-and-setup.md) |
31
+ | Theme, dark mode, or scoped themes | [theme-and-dark-mode.md](references/theme-and-dark-mode.md) |
@@ -0,0 +1,67 @@
1
+ # Component Guide
2
+
3
+ Use the sections relevant to the task. Selection choices are defaults for new work, not reasons to replace compatible existing components. For exact props, use the target version's docs via [docs-slug-map.md](docs-slug-map.md).
4
+
5
+ ## Select By Interaction
6
+
7
+ | Interaction | Default choice / distinction |
8
+ | --- | --- |
9
+ | Free text / numeric entry | `Input` / `InputNumber` |
10
+ | Typing with suggestions | `AutoComplete`; ordinary dropdowns use `Select` |
11
+ | Searchable or multi-select dropdown | `Select` with `showSearch` and/or `multiple` |
12
+ | Small set of visible choices | `Radio.Group` / `Check.Group` |
13
+ | Tree selection / linked levels | `TreeSelect` / `MCascader` |
14
+ | Date-time point / interval | `Datetime` / `DatetimeRange` |
15
+ | New tabular page | `NextTable`; use `virtualized` when needed for volume |
16
+ | Identity / status / count | `Avatar` / `Tag` / `Badge` |
17
+ | Loading / block placeholder / empty or error result | `Spin` / `Skeleton` / `Result` |
18
+ | Persistent inline guidance / transient global feedback | `Instruction` / `Notification` or `Toast` |
19
+ | Blocking acknowledgment / local confirmation | `Alert` / `PopConfirm` |
20
+ | Short text confirmation / multi-field modal / side editing | `Prompt` / `Dialog` / `Drawer` |
21
+ | Brief explanation / richer floating content / action menu | `Tooltip` / `Popover` / `Dropdown` + `Menu` |
22
+ | Spacing / grid / separation | `Space` / `Row` + `Col` / `Divider` |
23
+ | Navigation / peer views / upload | `Navigation` / `Tab` / `Upload` |
24
+
25
+ ## API Traps
26
+
27
+ | Component | Contract to preserve |
28
+ | --- | --- |
29
+ | `Button` | Destructive text actions use `type="text" danger`; `type="text-danger"` is not a public `ButtonType` |
30
+ | `Select`, `AutoComplete` | `options` use `{ label, value }` |
31
+ | `Combo`, `Combo.Check` | `items` use `{ text, value }`; `Combo.Check` is nested, not a separate root export |
32
+ | `NextTable` | Declare `Column`, `HeaderCell`, and `Cell` children, not a `columns` array; prefer its `pagination` when it owns paging |
33
+ | `Pagination`, `NextTable.pagination` | Use `page`, `size`, `sizeSet`, `count`; `sizeSet` contains the current `size`. To display the size chooser, also provide `showPageSize: size => String(size)`; `sizeSet` alone does not show it |
34
+ | Legacy `DataTable` | Measurement may call `render('', {}, 0)`; guard the fields your renderer needs before reading records or attaching actions |
35
+ | `PopConfirm` | Connect the confirmed mutation through `onOk` |
36
+ | `Dialog` | Save via `onOk`; handle both `onCancel` and `onCloseBtnClick` |
37
+ | `Tag` | Use semantic `type` or `style`; do not assume a `color` prop |
38
+ | `Avatar` | Character fallback uses `name` |
39
+
40
+ The table declaration differs from common `columns` APIs:
41
+
42
+ ```tsx
43
+ <NextTable data={pagedRows} rowKey="id" pagination={pagination}>
44
+ <NextTable.Column width={160}>
45
+ <NextTable.HeaderCell>名称</NextTable.HeaderCell>
46
+ <NextTable.Cell dataKey="name" />
47
+ </NextTable.Column>
48
+ </NextTable>
49
+ ```
50
+
51
+ For a legacy renderer that requires an id, a missing-id guard also handles measurement records without rejecting a valid id of `0`:
52
+
53
+ ```tsx
54
+ render: (_value, record) => {
55
+ if (record?.id == null) return null;
56
+ return <Button onClick={() => openEdit(record.id)}>编辑</Button>;
57
+ }
58
+ ```
59
+
60
+ ## State And Verification
61
+
62
+ - Keep one stored value domain across filters, rows, and edit drafts; map labels explicitly. A filter match must not compare a display label against a stored code.
63
+ - 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.
64
+ - 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.
65
+ - 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.
66
+
67
+ 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.
@@ -0,0 +1,79 @@
1
+ # Docs Slug Map
2
+
3
+ Use this map before fetching the overview page. If a name is missing or the current project uses an alias, fall back to `https://docs.fanruan.design/components/overview-cn/`.
4
+
5
+ | Component Name | Public Usage | Docs Slug | Notes |
6
+ | --- | --- | --- | --- |
7
+ | Button | `Button` | `button-cn` | Root export |
8
+ | SvgIcon | `SvgIcon` | `svg-icon-cn` | Root export |
9
+ | Divider | `Divider` | `divider-cn` | Root export |
10
+ | Typography | `Typography` | `typography-cn` | Root export |
11
+ | Grid | `Row` / `Col` | `grid-cn` | Docs page keyword for layout primitives; import `Row` and `Col` from the root package |
12
+ | Row | `Row` | `grid-cn` | Shares the Grid docs page |
13
+ | Col | `Col` | `grid-cn` | Shares the Grid docs page |
14
+ | Space | `Space` | `space-cn` | Root export |
15
+ | Splitter | `Splitter` | `splitter-cn` | Root export |
16
+ | Affix | `Affix` | `affix-cn` | Root export |
17
+ | Anchor | `Anchor` | `anchor-cn` | Root export |
18
+ | Breadcrumb | `Breadcrumb` | `breadcrumb-cn` | Root export |
19
+ | Dropdown | `Dropdown` | `dropdown-cn` | Root export |
20
+ | Menu | `Menu` | `menu-cn` | Root export |
21
+ | Navigation | `Navigation` | `navigation-cn` | Root export |
22
+ | Pagination | `Pagination` | `pagination-cn` | Root export |
23
+ | Step | `Step` | `step-cn` | Root export |
24
+ | Tab | `Tab` | `tab-cn` | Root export |
25
+ | Tree | `Tree` | `tree-cn` | Root export |
26
+ | AutoComplete | `AutoComplete` | `auto-complete-cn` | Root export |
27
+ | Check | `Check` | `check-cn` | Root export |
28
+ | MCascader | `MCascader` | `m-cascader-cn` | Public docs route exists; page title is Cascader |
29
+ | Cascader | `MCascader` preferred | `m-cascader-cn` | Online `cascader-cn` is 404; docs indicate legacy Cascader is being replaced |
30
+ | Datetime | `Datetime` | `datetime-cn` | Root export |
31
+ | DatetimeRange | `DatetimeRange` | `datetime-range-cn` | Root export |
32
+ | Form | `Form` | `form-cn` | Root export |
33
+ | Input | `Input` | `input-cn` | Root export |
34
+ | InputNumber | `InputNumber` | `input-number-cn` | Root export |
35
+ | Radio | `Radio` | `radio-cn` | Root export |
36
+ | Select | `Select` | `select-cn` | Root export |
37
+ | Slider | `Slider` | `slider-cn` | Root export |
38
+ | Switch | `Switch` | `switch-cn` | Root export |
39
+ | TreeSelect | `TreeSelect` | `tree-select-cn` | Root export |
40
+ | Upload | `Upload` | `upload-cn` | Root export |
41
+ | Avatar | `Avatar` | `avatar-cn` | Root export |
42
+ | Badge | `Badge` | `badge-cn` | Root export |
43
+ | Carousel | `Carousel` | `carousel-cn` | Root export |
44
+ | Collapse | `Collapse` | `collapse-cn` | Root export |
45
+ | FilePreview | `FilePreview` | `file-preview-cn` | Root export |
46
+ | Image | `Image` | `image-cn` | Root export |
47
+ | List | `List` | `list-cn` | Root export |
48
+ | Progress | `Progress` | `progress-cn` | Root export |
49
+ | Table | `Table` | `next-table-cn` | Online public table docs currently live at `next-table-cn`; `table-cn` returns 404 |
50
+ | NextTable | `NextTable` | `next-table-cn` | Same public table docs route |
51
+ | Tag | `Tag` | `tag-cn` | Root export |
52
+ | Alert | `Alert` | `alert-cn` | Root export |
53
+ | Dialog | `Dialog` | `dialog-cn` | Root export |
54
+ | Drawer | `Drawer` | `drawer-cn` | Root export |
55
+ | Instruction | `Instruction` | `instruction-cn` | Root export |
56
+ | ModalMask | `ModalMask` | `modal-mask-cn` | Root export |
57
+ | Notification | `Notification` | `notification-cn` | Root export |
58
+ | PopConfirm | `PopConfirm` | `pop-confirm-cn` | Root export |
59
+ | Popover | `Popover` | `popover-cn` | Root export |
60
+ | Prompt | `Prompt` | `prompt-cn` | Root export |
61
+ | Result | `Result` | `result-cn` | Root export |
62
+ | Skeleton | `Skeleton` | `skeleton-cn` | Root export |
63
+ | Spin | `Spin` | `spin-cn` | Root export |
64
+ | Toast | `Toast` | `toast-cn` | Root export |
65
+ | Tooltip | `Tooltip` | `tooltip-cn` | Root export |
66
+ | Watermark | `Watermark` | `watermark-cn` | Root export |
67
+ | ConfigProvider | `ConfigProvider` | `config-provider-cn` | Root export |
68
+ | Combo | `Combo` | `combo-cn` | Root export |
69
+ | ComboCheck | `Combo.Check` | `combo-check-cn` | Documented online, but not a root export in `src/index.ts` |
70
+ | DataTable | `DataTable` | `data-table-cn` | Root export |
71
+ | VirtualTable | `VirtualTable` | `virtual-table-cn` | Root export |
72
+
73
+ ## Fallback Rules
74
+
75
+ 1. If the component name does not appear here, fetch the overview page and search there.
76
+ 2. If the project already uses a component alias or wrapper, map it back to the Fine Design public component first.
77
+ 3. Use this table to locate pages, not to establish API compatibility. If routes or content disagree, follow the version and evidence rules in [imports-and-setup.md](imports-and-setup.md#version-and-compatibility); current website content must not override the installed version's public contract.
78
+ 4. If a component is documented but not root-exported, generate the correct public access form instead of inventing a root import.
79
+ 5. If the public site cannot be retrieved, use matching local declarations, docs, and demos and state any remaining uncertainty rather than repeatedly trying the same failed route.
@@ -0,0 +1,44 @@
1
+ # Imports And Setup
2
+
3
+ ## Version And Compatibility
4
+
5
+ - Resolve Fine Design, React, and ReactDOM versions from installed packages or the lockfile; a `package.json` range is not an exact version.
6
+ - In the Fine Design repository, use the checked-out docs, exports, and demos. In consuming projects, prefer matching-version docs and verify uncertain APIs against installed public declarations/exports. Current website content and skill defaults must not override that contract.
7
+ - If docs are unavailable, use matching local declarations and examples; inspect only unresolved implementation details. State remaining uncertainty. Do not upgrade dependencies merely to fit an example, or infer full React-major compatibility from a permissive peer range.
8
+ - Reuse the existing installation and package manager. A new project may install `@fx-ui/fine-design` when needed.
9
+
10
+ ## Package Imports And Styles
11
+
12
+ ```tsx
13
+ import { Button, Combo, Select } from '@fx-ui/fine-design';
14
+ import '@fx-ui/fine-design/dist/fine_design.css';
15
+ ```
16
+
17
+ Load the stylesheet once at application bootstrap, or include it in a standalone example. Use root-exported types when available; do not invent exports or deep-import `es`/`lib` internals unless explicitly requested. Nested APIs such as `Combo.Check` remain nested.
18
+
19
+ Single-file output includes all required code and styles; no unresolved `styles.xxx`, local helper imports, or assets. An integrated page reuses the project's existing bootstrap.
20
+
21
+ ## Standalone HTML
22
+
23
+ The public UMD runtime replaces package imports. Load in this order:
24
+
25
+ ```html
26
+ <link rel="stylesheet" href="https://docs.fanruan.design/assets/react/fine-design-runtime/fine-design/fine-design.min.css" />
27
+ <script src="https://cdn.jsdelivr.net/npm/react@18.3.1/umd/react.production.min.js"></script>
28
+ <script src="https://cdn.jsdelivr.net/npm/react-dom@18.3.1/umd/react-dom.production.min.js"></script>
29
+ <script src="https://docs.fanruan.design/assets/react/fine-design-runtime/fine-design/fine-design.min.js"></script>
30
+ ```
31
+
32
+ Use `window.FineDesign` for matching controls; ordinary document shells and page containers may use HTML. Use plain JavaScript/`React.createElement` unless a JSX transformer is included. The unversioned Fine Design assets do not prove an exact npm version; verify required exports and behavior.
33
+
34
+ Minimal mount after these scripts and a root element:
35
+
36
+ ```js
37
+ const h = React.createElement;
38
+ const { Button } = window.FineDesign;
39
+ ReactDOM.createRoot(document.getElementById('root')).render(
40
+ h(Button, { type: 'primary' }, '保存')
41
+ );
42
+ ```
43
+
44
+ In this repository, the public assets are generated by `npm run build:public-assets`; consuming projects use the published URLs.
@@ -0,0 +1,49 @@
1
+ # Theme And Dark Mode
2
+
3
+ Read only for theme work. Confirm exact tokens in the matching docs, the [theme guide](https://docs.fanruan.design/docs/react/theme-cn/), or the [token index](https://docs.fanruan.design/docs/react/token-cn/).
4
+
5
+ ## Shared Theme
6
+
7
+ ```tsx
8
+ import { ConfigProvider, theme } from '@fx-ui/fine-design';
9
+
10
+ <ConfigProvider theme={{
11
+ algorithm: dark ? theme.darkAlgorithm : undefined,
12
+ token: { colorPrimary: '#5865F5' }
13
+ }}>
14
+ <App />
15
+ </ConfigProvider>
16
+ ```
17
+
18
+ Load the global stylesheet through [imports-and-setup.md](imports-and-setup.md). Switch the shared provider's `theme` prop rather than remounting the app or manually recoloring children. Standalone HTML gets both exports from `window.FineDesign`.
19
+
20
+ ## Non-Obvious Contracts
21
+
22
+ | Need | Contract |
23
+ | --- | --- |
24
+ | Dark mode | Use `theme.darkAlgorithm` to generate semantic tokens, not just a dark page background |
25
+ | Brand/status colors | Put seeds such as `colorPrimary`, `colorError`, `colorWarning`, `colorSuccess`, `colorInfo` in `theme.token` |
26
+ | Derived-token exception | Explicit tokens are final overrides; keep neutral surfaces/borders on the neutral scale rather than deriving them all from the brand |
27
+ | Compose algorithms | Arrays run left to right; later output wins. Custom algorithms return `{ ...token, ...overrides }` to retain earlier results |
28
+ | Component-only exception | Use `theme.components`, e.g. `Button: { heightText: '28px', paddingTextLg: '12px' }` |
29
+ | Global imperative configuration | `ConfigProvider.config({ theme: { algorithm: theme.darkAlgorithm, token: { colorPrimary: '#5865F5' } } })`; use the provider for React state-driven switching |
30
+
31
+ ## Scoped Themes
32
+
33
+ Use only when separate themes coexist. `scope` must match a real wrapper selector; `reportStyleContainer` below is a dedicated existing `Element` for this provider's styles:
34
+
35
+ ```tsx
36
+ <div className="report-dark">
37
+ <ConfigProvider styleContainer={reportStyleContainer} theme={{
38
+ scope: '.report-dark',
39
+ algorithm: theme.darkAlgorithm
40
+ }}>
41
+ <Report />
42
+ </ConfigProvider>
43
+ </div>
44
+ ```
45
+
46
+ - `scope` isolates selectors, not style registration. Give coexisting providers distinct `styleContainer` values so a later theme does not replace an earlier generated style; nested scopes also need distinct selectors.
47
+ - Keep `inherit: true` unless the scope supplies a complete algorithm/token set.
48
+
49
+ Verify container, elevated, border, text/icon, fill, focus, disabled, overlay, and status interaction states. Child hard-coded light colors must not defeat the dark theme.
package/src/cli.mjs ADDED
@@ -0,0 +1,59 @@
1
+ import fs from 'node:fs';
2
+ import { parseArgs } from 'node:util';
3
+ import { queryCatalog } from './core/catalog.mjs';
4
+ import { loadCatalog } from './core/data.mjs';
5
+ import { resolveVersion } from './core/version.mjs';
6
+ import { ToolError, errorResult } from './core/errors.mjs';
7
+
8
+ const help = `Usage: fine-design <command> [arguments] [options]
9
+
10
+ Commands:
11
+ search [query] Search or browse components
12
+ doc <component> Read component documentation
13
+ example <component> <id> Read source files and binary asset metadata
14
+ mcp Start the stdio MCP server
15
+
16
+ Options:
17
+ --fd-version <version> Exact Fine Design component version
18
+ --project <directory> Project used to detect the installed version
19
+ --format <text|json|markdown> Output format (default: text)
20
+ --section <heading> Exact doc section
21
+ --offset <number> Search pagination offset
22
+ --include-assets Include binary asset content in example output
23
+ --help Show help
24
+ --version Show tool version`;
25
+
26
+ export async function main(argv) {
27
+ let format = 'text';
28
+ try {
29
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, strict: true, options: {
30
+ help: { type: 'boolean' }, version: { type: 'boolean' }, 'fd-version': { type: 'string' }, project: { type: 'string' },
31
+ format: { type: 'string' }, section: { type: 'string' }, offset: { type: 'string' }, 'include-assets': { type: 'boolean' }
32
+ }});
33
+ format = values.format || 'text';
34
+ if (!['text', 'json', 'markdown'].includes(format)) throw new ToolError('INVALID_ARGUMENT', 'Unknown output format.', 2);
35
+ if (values.help || (!positionals.length && !values.version && !argv.length)) { console.log(help); return; }
36
+ if (values.version && argv.length === 1) { console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url))).version); return; }
37
+ const [command, ...args] = positionals;
38
+ if (command === 'mcp' && args.length === 0 && argv.length === 1) { await (await import('./mcp.mjs')).startMcp(); return; }
39
+ const tools = { search: 'search_components', doc: 'get_component_doc', example: 'get_component_example' };
40
+ if (!Object.hasOwn(tools, command) || values.version || (command === 'search' && args.length > 1) || (command === 'doc' && args.length !== 1) || (command === 'example' && args.length !== 2) || (values.section !== undefined && command !== 'doc') || (values.offset !== undefined && command !== 'search') || (values['include-assets'] !== undefined && command !== 'example')) throw new ToolError('INVALID_ARGUMENT', 'Invalid command or arguments. Use --help for usage.', 2);
41
+ if (values.offset !== undefined && !/^\d+$/.test(values.offset)) throw new ToolError('INVALID_ARGUMENT', 'Offset must be a non-negative integer.', 2);
42
+ const version = resolveVersion(values['fd-version'], values.project);
43
+ const input = { version, ...(command === 'search' ? { query: args[0] ?? '', ...(values.offset !== undefined && { offset: Number(values.offset) }) } : { component: args[0], ...(command === 'doc' && values.section !== undefined && { section: values.section }), ...(command === 'example' && { exampleId: args[1], ...(values['include-assets'] !== undefined && { includeAssets: values['include-assets'] }) }) }) };
44
+ const { validateInput } = await import('./core/contracts.mjs');
45
+ validateInput(tools[command], input);
46
+ const result = queryCatalog(loadCatalog(version), tools[command], input);
47
+ if (format === 'json') console.log(JSON.stringify(result));
48
+ else if (command === 'doc') console.log(`${result.markdown || `No documentation available for ${result.component}.`}
49
+
50
+ ${result.sections ? `Sections: ${result.sections.join(', ') || 'none'}\n` : ''}Examples: ${result.examples.map((item) => item.id).join(', ') || 'none'}`);
51
+ else if (command === 'search') console.log(`${result.components.map((item) => `${item.id} (${item.exports.join(', ')}): ${item.description}`).join('\n')}\nTotal: ${result.total}; nextOffset: ${result.nextOffset ?? 'none'}`);
52
+ else console.log(JSON.stringify(result, null, 2));
53
+ } catch (error) {
54
+ const normalized = error instanceof TypeError && error.code?.startsWith('ERR_PARSE_ARGS') ? new ToolError('INVALID_ARGUMENT', error.message, 2) : error;
55
+ const result = errorResult(normalized);
56
+ console.error(format === 'json' || argv.some((arg, index) => arg === '--format=json' || (arg === '--format' && argv[index + 1] === 'json')) ? JSON.stringify(result) : `${result.error.code}: ${result.error.message}${result.error.suggestions ? `\n${result.error.suggestions.join('\n')}` : ''}`);
57
+ process.exitCode = normalized.exitCode || 1;
58
+ }
59
+ }
@@ -0,0 +1,113 @@
1
+ import { ToolError } from './errors.mjs';
2
+ import { validateInput } from './contracts.mjs';
3
+ import { sha256 } from './data.mjs';
4
+
5
+ export function queryCatalog(catalog, tool, args) {
6
+ args = validateInput(tool, args);
7
+ if (args.version !== catalog.version) throw new ToolError('VERSION_NOT_SUPPORTED', 'Requested Fine Design version is not available.', 3, { requestedVersion: args.version, availableVersions: [catalog.version] });
8
+ const source = {
9
+ version: catalog.version,
10
+ sourceRevision: catalog.sourceRevision,
11
+ sourceDirty: catalog.sourceDirty,
12
+ contentHash: catalog.contentHash,
13
+ sourceKind: catalog.sourceKind
14
+ };
15
+ if (tool === 'search_components') {
16
+ const terms = args.query.toLowerCase().trim().split(/\s+/).filter(Boolean);
17
+ const matches = catalog.components.filter((component) => {
18
+ const text = [
19
+ component.id,
20
+ component.title,
21
+ component.subtitle,
22
+ ...component.exports,
23
+ ...component.aliases,
24
+ component.description,
25
+ ...component.examples.map((item) => item.title)
26
+ ]
27
+ .join(' ')
28
+ .toLowerCase();
29
+ return terms.every((term) => text.includes(term));
30
+ });
31
+ return {
32
+ ...source,
33
+ total: matches.length,
34
+ components: matches
35
+ .slice(args.offset || 0, (args.offset || 0) + 20)
36
+ .map(
37
+ ({
38
+ id,
39
+ title,
40
+ subtitle,
41
+ exports,
42
+ description,
43
+ sourcePath,
44
+ examples,
45
+ docsAvailable
46
+ }) => ({
47
+ id,
48
+ title,
49
+ subtitle,
50
+ exports,
51
+ description,
52
+ sourcePath,
53
+ docsAvailable,
54
+ examples: examples.map(({ id, title }) => ({ id, title }))
55
+ })
56
+ ),
57
+ nextOffset: matches.length > (args.offset || 0) + 20 ? (args.offset || 0) + 20 : null
58
+ };
59
+ }
60
+ const component = catalog.components.find((item) =>
61
+ [item.id, ...item.exports, ...item.aliases].some(
62
+ (name) => name.toLowerCase() === args.component.toLowerCase()
63
+ )
64
+ );
65
+ if (!component)
66
+ throw new ToolError('COMPONENT_NOT_FOUND', `Unknown component: ${args.component}.`, 4, { suggestions: ['Use search to find a component.'] });
67
+ if (tool === 'get_component_doc') {
68
+ const examples = component.examples.map(
69
+ ({ id, title, entry, dependencies, unresolved }) => ({
70
+ id,
71
+ title,
72
+ entry,
73
+ dependencies,
74
+ unresolved
75
+ })
76
+ );
77
+ if (args.section) {
78
+ const section = component.sections.find((item) => item.heading === args.section);
79
+ if (!section)
80
+ throw new ToolError('SECTION_NOT_FOUND', 'Unknown section.', 4, { availableSections: component.sections.map((item) => item.heading) });
81
+ return {
82
+ ...source,
83
+ component: component.id,
84
+ sourcePath: component.sourcePath,
85
+ ...section,
86
+ examples
87
+ };
88
+ }
89
+ return {
90
+ ...source,
91
+ component: component.id,
92
+ exports: component.exports,
93
+ docsAvailable: component.docsAvailable,
94
+ sourcePath: component.sourcePath,
95
+ sections: component.sections.map(({ heading }) => heading),
96
+ markdown: component.markdown,
97
+ examples
98
+ };
99
+ }
100
+ if (tool === 'get_component_example') {
101
+ const example = component.examples.find((item) => item.id === args.exampleId);
102
+ if (!example)
103
+ throw new ToolError('EXAMPLE_NOT_FOUND', 'Unknown example.', 4, { availableExamples: component.examples.map((item) => item.id) });
104
+ const files = example.files.map((file) => {
105
+ if (file.encoding !== 'base64') return file;
106
+ const { content, ...metadata } = file;
107
+ const bytes = Buffer.from(content, 'base64');
108
+ return { ...metadata, size: bytes.length, sha256: sha256(bytes), ...(args.includeAssets ? { content } : {}) };
109
+ });
110
+ return { ...source, component: component.id, ...example, files };
111
+ }
112
+ throw new Error(`Unknown tool: ${tool}`);
113
+ }
@@ -0,0 +1,18 @@
1
+ import { z } from 'zod';
2
+ import { ToolError } from './errors.mjs';
3
+
4
+ const version = z.string().min(1).max(80);
5
+ const component = z.string().min(1).max(100);
6
+ export const schemas = {
7
+ search_components: z.object({ version, query: z.string().max(200), offset: z.number().int().min(0).max(10000).optional() }).strict(),
8
+ get_component_doc: z.object({ version, component, section: z.string().min(1).max(200).optional() }).strict(),
9
+ get_component_example: z.object({ version, component, exampleId: z.string().min(1).max(200), includeAssets: z.boolean().optional().describe('Include binary asset content as base64; default returns only asset metadata.') }).strict()
10
+ };
11
+
12
+ export function validateInput(tool, input) {
13
+ const result = schemas[tool]?.safeParse(input);
14
+ if (!result?.success) {
15
+ throw new ToolError('INVALID_ARGUMENT', result?.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ') || `Unknown tool: ${tool}`, 2);
16
+ }
17
+ return result.data;
18
+ }
@@ -0,0 +1,99 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { ToolError } from './errors.mjs';
6
+
7
+ const dataRoot = fileURLToPath(new URL('../../data/', import.meta.url));
8
+ export const sha256 = (content) => createHash('sha256').update(content).digest('hex');
9
+ export const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
10
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value);
11
+ const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
12
+
13
+ export function safeFile(root, name) {
14
+ if (typeof name !== 'string' || !name || name.split('/').some((part) => !part || part === '.' || part === '..') || /[\\:\0]/.test(name) || path.isAbsolute(name)) throw new Error(`Invalid data path: ${name}`);
15
+ const filename = path.join(root, name);
16
+ if (!fs.realpathSync(filename).startsWith(`${fs.realpathSync(root)}${path.sep}`) || !fs.statSync(filename).isFile()) throw new Error(`Invalid data path: ${name}`);
17
+ return filename;
18
+ }
19
+
20
+ export function readTree(root) {
21
+ if (!fs.lstatSync(root).isDirectory()) throw new Error(`Expected a directory without a symbolic link: ${root}`);
22
+ const files = {};
23
+ function visit(directory, prefix = '') {
24
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
25
+ const name = `${prefix}${entry.name}`;
26
+ if (entry.isSymbolicLink()) throw new Error(`Symbolic links are not allowed: ${name}`);
27
+ if (entry.isDirectory()) visit(path.join(directory, entry.name), `${name}/`);
28
+ else if (entry.isFile()) files[name] = sha256(fs.readFileSync(safeFile(root, name)));
29
+ else throw new Error(`Unsupported file: ${name}`);
30
+ }
31
+ }
32
+ visit(root);
33
+ return files;
34
+ }
35
+
36
+ export function validateSkills(root, expected) {
37
+ if (!object(expected) || !Object.hasOwn(expected, 'SKILL.md')) throw new Error('Missing Skill manifest');
38
+ const actual = readTree(root);
39
+ if (Object.keys(actual).length !== Object.keys(expected).length || Object.entries(actual).some(([name, hash]) => expected[name] !== hash)) throw new Error('Invalid or corrupted Skill snapshot');
40
+ for (const name of Object.keys(actual).filter((name) => name.endsWith('.md'))) {
41
+ const markdown = fs.readFileSync(safeFile(root, name), 'utf8');
42
+ for (const match of markdown.matchAll(/\]\(([^\s)]+)(?:\s+[^)]*)?\)/g)) {
43
+ const link = match[1];
44
+ if (/^(?:[a-z][a-z\d+.-]*:|#|\/)/i.test(link)) continue;
45
+ const target = path.posix.normalize(path.posix.join(path.posix.dirname(name), decodeURIComponent(link.split('#')[0])));
46
+ safeFile(root, target);
47
+ }
48
+ }
49
+ }
50
+
51
+ export function readSnapshot(root, version, skills = false) {
52
+ const raw = fs.readFileSync(safeFile(root, 'catalog.json'));
53
+ const manifest = JSON.parse(fs.readFileSync(safeFile(root, 'manifest.json'), 'utf8'));
54
+ const catalog = JSON.parse(raw);
55
+ const { contentHash, ...content } = catalog;
56
+ if (!exactVersion.test(version) || manifest.schemaVersion !== 1 || manifest.version !== version || manifest.catalogSha256 !== sha256(raw) || catalog.schemaVersion !== 1 || catalog.package !== '@fx-ui/fine-design' || catalog.version !== version || !Array.isArray(catalog.components) || !catalog.components.length || typeof catalog.sourceRevision !== 'string' || typeof catalog.sourceDirty !== 'boolean' || catalog.sourceKind !== 'repository-snapshot' || contentHash !== sha256(JSON.stringify(content)) || ['contentHash', 'sourceKind', 'sourceRevision', 'sourceDirty'].some((key) => catalog[key] !== manifest[key])) throw new Error('Invalid or corrupted Fine Design data snapshot');
57
+ const ids = new Set();
58
+ const exports = new Set();
59
+ for (const component of catalog.components) {
60
+ if (!object(component) || !/^[a-z][a-z0-9-]*$/.test(component.id) || ids.has(component.id) || !strings(component.exports) || !component.exports.length || component.exports.some((name) => exports.has(name)) || !strings(component.aliases) || typeof component.title !== 'string' || typeof component.subtitle !== 'string' || typeof component.description !== 'string' || typeof component.docsAvailable !== 'boolean' || typeof component.sourcePath !== 'string' || typeof component.markdown !== 'string' || !Array.isArray(component.sections) || !component.sections.every((item) => typeof item.heading === 'string' && typeof item.markdown === 'string') || !Array.isArray(component.examples)) throw new Error('Invalid component in data snapshot');
61
+ ids.add(component.id);
62
+ component.exports.forEach((name) => exports.add(name));
63
+ const examples = new Set();
64
+ for (const example of component.examples) {
65
+ if (!object(example) || typeof example.id !== 'string' || examples.has(example.id) || typeof example.title !== 'string' || typeof example.entry !== 'string' || !strings(example.dependencies) || !strings(example.unresolved) || !Array.isArray(example.files)) throw new Error('Invalid example in data snapshot');
66
+ examples.add(example.id);
67
+ const paths = new Set();
68
+ for (const file of example.files) {
69
+ if (!object(file) || typeof file.path !== 'string' || !/^(?:src|assets|public)\//.test(file.path) || file.path.split('/').some((part) => !part || part === '.' || part === '..') || /[\\:\0]/.test(file.path) || paths.has(file.path) || !['utf8', 'base64'].includes(file.encoding) || typeof file.content !== 'string') throw new Error('Invalid example file in data snapshot');
70
+ paths.add(file.path);
71
+ }
72
+ if (!paths.has(example.entry) && !example.unresolved.includes(example.entry)) throw new Error('Missing example entry');
73
+ }
74
+ }
75
+ if (skills) {
76
+ safeFile(root, 'skills/fine-design/SKILL.md');
77
+ validateSkills(path.join(root, 'skills/fine-design'), manifest.skillFiles);
78
+ }
79
+ return { catalog, manifest };
80
+ }
81
+
82
+ export function readIndex(root = dataRoot) {
83
+ const index = JSON.parse(fs.readFileSync(safeFile(root, 'index.json'), 'utf8'));
84
+ if (index.schemaVersion !== 1 || !object(index.versions) || !Object.keys(index.versions).length || Object.entries(index.versions).some(([version, entry]) => !exactVersion.test(version) || !object(entry) || entry.catalog !== `${version}/catalog.json` || entry.manifest !== `${version}/manifest.json`)) throw new Error('Invalid data index');
85
+ return index;
86
+ }
87
+
88
+ export function loadCatalog(version) {
89
+ const index = readIndex();
90
+ const entry = index.versions[version];
91
+ if (!Object.hasOwn(index.versions, version)) {
92
+ throw new ToolError('VERSION_NOT_SUPPORTED', 'Requested Fine Design version is not available.', 3, {
93
+ requestedVersion: version, availableVersions: Object.keys(index.versions), suggestions: ['Check the installed version or provide a supported --fd-version.']
94
+ });
95
+ }
96
+ safeFile(dataRoot, entry.catalog);
97
+ safeFile(dataRoot, entry.manifest);
98
+ return readSnapshot(path.join(dataRoot, version), version).catalog;
99
+ }