@finedesign/cli 0.0.0-stage → 0.1.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,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
+ }
@@ -0,0 +1,17 @@
1
+ export class ToolError extends Error {
2
+ constructor(code, message, exitCode, context = {}) {
3
+ super(message);
4
+ this.code = code;
5
+ this.exitCode = exitCode;
6
+ this.context = context;
7
+ }
8
+ toJSON() {
9
+ return { error: { code: this.code, message: this.message, ...this.context } };
10
+ }
11
+ }
12
+
13
+ export function errorResult(error) {
14
+ return error instanceof ToolError ? error.toJSON() : {
15
+ error: { code: 'INTERNAL_ERROR', message: error.message }
16
+ };
17
+ }
@@ -0,0 +1,28 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { ToolError } from './errors.mjs';
4
+
5
+ export function resolveVersion(explicit, project = process.cwd()) {
6
+ if (explicit !== undefined) return explicit;
7
+ let directory = path.resolve(project);
8
+ if (!fs.existsSync(directory) || !fs.statSync(directory).isDirectory()) {
9
+ throw new ToolError('INVALID_ARGUMENT', `Project directory does not exist: ${directory}`, 2);
10
+ }
11
+ while (true) {
12
+ const filename = path.join(directory, 'node_modules', '@fx-ui', 'fine-design', 'package.json');
13
+ if (fs.existsSync(filename)) {
14
+ const installed = JSON.parse(fs.readFileSync(filename, 'utf8'));
15
+ if (installed.name === '@fx-ui/fine-design' && typeof installed.version === 'string' && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(installed.version)) return installed.version;
16
+ throw new ToolError('VERSION_NOT_DETECTED', 'Installed Fine Design package has no valid exact version.', 3, { suggestions: ['Specify --fd-version with an exact supported version.'] });
17
+ }
18
+ const parent = path.dirname(directory);
19
+ if (parent === directory) break;
20
+ directory = parent;
21
+ }
22
+ throw new ToolError('VERSION_NOT_DETECTED', 'Cannot find an installed @fx-ui/fine-design version in this project or its parent directories.', 3, { suggestions: [
23
+ 'Run from the component project or pass --project <directory>.',
24
+ 'For offline documentation without installing components, pass --fd-version <exact-supported-version>.',
25
+ 'If component installation fails, check the effective registry with npm config get @fx-ui:registry and npm config get registry.',
26
+ 'Reuse existing npm credentials with --userconfig=/absolute/path/to/.npmrc; configuration may also come from user/global files or environment variables. See README installation troubleshooting.'
27
+ ] });
28
+ }
package/src/mcp.mjs ADDED
@@ -0,0 +1,33 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
+ import fs from 'node:fs';
5
+ import { z } from 'zod';
6
+ import { queryCatalog } from './core/catalog.mjs';
7
+ import { loadCatalog } from './core/data.mjs';
8
+ import { schemas, validateInput } from './core/contracts.mjs';
9
+ import { errorResult } from './core/errors.mjs';
10
+
11
+ export async function startMcp() {
12
+ const packageInfo = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
13
+ const server = new Server({ name: 'fine-design', version: packageInfo.version }, { capabilities: { tools: {} } });
14
+ const descriptions = {
15
+ search_components: 'Search components; use nextOffset to browse subsequent pages.',
16
+ get_component_doc: 'Read component documentation and discover sections and example IDs.',
17
+ get_component_example: 'Read example source files, dependencies and binary asset metadata. Set includeAssets to include base64 asset content.'
18
+ };
19
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Object.entries(schemas).map(([name, schema]) => ({
20
+ name, description: descriptions[name], inputSchema: z.toJSONSchema(schema, { target: 'draft-07' }),
21
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
22
+ })) }));
23
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
24
+ try {
25
+ const { name, arguments: input } = request.params;
26
+ const args = validateInput(name, input);
27
+ return { content: [{ type: 'text', text: JSON.stringify(queryCatalog(loadCatalog(args.version), name, args)) }] };
28
+ } catch (error) {
29
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify(errorResult(error)) }] };
30
+ }
31
+ });
32
+ await server.connect(new StdioServerTransport());
33
+ }