@tu-design/cli 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/index.mjs +406 -21
- package/dist/mcp-core-Ct8Xf-FY.mjs +70 -0
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -16,12 +16,14 @@ npx @tu-design/cli add button
|
|
|
16
16
|
- 写入 `components.json`(registry URL、别名等配置)
|
|
17
17
|
- 注入 `cn` 工具到 `src/lib/utils.ts`
|
|
18
18
|
- 将主题 tokens 合并进全局 CSS(自动探测常见位置,可用 `--css` 指定;已包含则跳过)
|
|
19
|
+
- 写入 `AGENTS.md` AI 协作规则(组件安装 / 自动导入 / 语义 token 主题约定,供 AI 编码代理遵循;文件已存在时不覆盖,`--no-agents` 可显式跳过)
|
|
19
20
|
- 探测包管理器并安装运行时依赖(`clsx` / `tailwind-merge` / `class-variance-authority`)
|
|
20
21
|
|
|
21
22
|
| 选项 | 说明 |
|
|
22
23
|
| ------------------ | ----------------------------------- |
|
|
23
24
|
| `--registry <url>` | registry URL,默认线上 Pages 数据源 |
|
|
24
25
|
| `--css <path>` | 全局 CSS 路径 |
|
|
26
|
+
| `--no-agents` | 不写入 AGENTS.md AI 协作规则 |
|
|
25
27
|
|
|
26
28
|
### `add <components...>`
|
|
27
29
|
|
|
@@ -32,6 +34,20 @@ npx @tu-design/cli add button
|
|
|
32
34
|
| `--registry <url>` | 覆盖 `components.json` 中的 registry URL |
|
|
33
35
|
| `--overwrite` | 覆盖已存在的文件而不询问 |
|
|
34
36
|
|
|
37
|
+
### `mcp`
|
|
38
|
+
|
|
39
|
+
启动 MCP Server(stdio 传输,只查询、不安装):供 Claude / Cursor 等 AI 客户端在线查询组件 registry——列出组件、按关键字搜索、获取单个组件的 registry 详情(内联源码、依赖与安装提示),引导 AI 用 CLI 安装而不是手写源码。
|
|
40
|
+
|
|
41
|
+
| 选项 | 说明 |
|
|
42
|
+
| ------------------ | ----------------- |
|
|
43
|
+
| `--registry <url>` | registry URL 通道 |
|
|
44
|
+
|
|
45
|
+
客户端配置示例(与文档站一致):
|
|
46
|
+
|
|
47
|
+
```json
|
|
48
|
+
{ "mcpServers": { "tu-design": { "command": "npx", "args": ["-y", "@tu-design/cli", "mcp"] } } }
|
|
49
|
+
```
|
|
50
|
+
|
|
35
51
|
## 工作机制
|
|
36
52
|
|
|
37
53
|
CLI 从 registry 服务拉取每个组件的 **registry JSON**(遵循 [shadcn registry-item schema](https://ui.shadcn.com/schema/registry-item.json)),JSON 中内联了文件内容与写入目标,并声明:
|
package/dist/index.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from
|
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import picocolors from "picocolors";
|
|
7
7
|
import { dirname, join } from "node:path";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
8
9
|
//#region src/io/node.ts
|
|
9
10
|
const nodeIo = {
|
|
10
11
|
exists: (path) => existsSync(path),
|
|
@@ -94,6 +95,37 @@ function saveConfig(io, cwd, config) {
|
|
|
94
95
|
io.writeFile(configPath(cwd), `${JSON.stringify(config, null, 2)}\n`);
|
|
95
96
|
}
|
|
96
97
|
//#endregion
|
|
98
|
+
//#region src/lib/ai-rules.ts
|
|
99
|
+
/**
|
|
100
|
+
* init 注入到用户项目根目录 AGENTS.md 的 AI 协作规则。
|
|
101
|
+
* 目的:让 AI 编码代理遵循 tu-design 的组件安装 / 导入 / 主题约定,
|
|
102
|
+
* 而不是手写组件源码或硬编码样式,绕开 registry 分发链路。
|
|
103
|
+
*/
|
|
104
|
+
const AGENTS_MD_SOURCE = `# tu-design AI 协作规则
|
|
105
|
+
|
|
106
|
+
本项目使用 tu-design(shadcn 风格 Vue 3 组件库),AI 协作约定如下:
|
|
107
|
+
|
|
108
|
+
## 组件安装
|
|
109
|
+
|
|
110
|
+
- 组件必须通过 CLI 安装:在项目根目录执行 \`npx @tu-design/cli add <name>\`,禁止手写组件源码。
|
|
111
|
+
- 首次接入先安装基础项:\`npx @tu-design/cli add utils tokens\`。
|
|
112
|
+
|
|
113
|
+
## 导入约定
|
|
114
|
+
|
|
115
|
+
- 组件经 unplugin-vue-components + \`TuDesignResolver\` 自动导入,模板直接写 \`<Button />\`,无需手动 import。
|
|
116
|
+
- \`cn\` 来自 \`@/lib/utils\`。
|
|
117
|
+
|
|
118
|
+
## 主题约定
|
|
119
|
+
|
|
120
|
+
- 颜色/圆角一律使用语义 token 类(\`bg-primary\`、\`text-muted-foreground\`、\`rounded-md\`),禁止硬编码十六进制色值。
|
|
121
|
+
- 暗色模式由 \`.dark\` class 驱动。
|
|
122
|
+
|
|
123
|
+
## 参考资料
|
|
124
|
+
|
|
125
|
+
- 完整组件清单:https://gopowerteam.github.io/tu-design/llms.txt(可整页抓取给 AI)
|
|
126
|
+
- 全量文档:https://gopowerteam.github.io/tu-design/llms-full.txt(可整页抓取给 AI)
|
|
127
|
+
`;
|
|
128
|
+
//#endregion
|
|
97
129
|
//#region src/lib/alias.ts
|
|
98
130
|
/**
|
|
99
131
|
* 将 paths 合并进 tsconfig 文本。优先 JSON round-trip;
|
|
@@ -348,12 +380,17 @@ function runInit(io, cwd, opts) {
|
|
|
348
380
|
const merged = mergeTokensCss(globalCss, TOKENS_CSS_SOURCE);
|
|
349
381
|
const skippedCss = merged === globalCss;
|
|
350
382
|
if (!skippedCss) io.writeFile(cssPath, merged);
|
|
383
|
+
const agentsPath = joinPosix(cwd, "AGENTS.md");
|
|
384
|
+
const skippedAgents = opts.agents === false || io.exists(agentsPath);
|
|
385
|
+
if (!skippedAgents) io.writeFile(agentsPath, AGENTS_MD_SOURCE);
|
|
351
386
|
applyAliases(io, cwd, aliasRoot);
|
|
352
387
|
return {
|
|
353
388
|
configPath,
|
|
354
389
|
cnPath,
|
|
355
390
|
cssPath,
|
|
356
|
-
skippedCss
|
|
391
|
+
skippedCss,
|
|
392
|
+
agentsPath,
|
|
393
|
+
skippedAgents
|
|
357
394
|
};
|
|
358
395
|
}
|
|
359
396
|
//#endregion
|
|
@@ -382,6 +419,7 @@ function validateRegistryItem(raw) {
|
|
|
382
419
|
if (missing.length > 0) throw new Error(`registry item 缺少字段:${missing.join("、")}`);
|
|
383
420
|
const badFile = obj.files.findIndex((f) => typeof f !== "object" || f === null || typeof f.path !== "string" || typeof f.target !== "string" || typeof f.content !== "string");
|
|
384
421
|
if (badFile !== -1) throw new Error(`registry item ${String(obj.name)} 的 files[${badFile}] 缺少 path/target/content 字符串字段`);
|
|
422
|
+
if (obj.version !== void 0 && typeof obj.version !== "string") throw new Error(`registry item ${String(obj.name)} 的 version 字段必须是字符串,得到 ${obj.version === null ? "null" : typeof obj.version}`);
|
|
385
423
|
return raw;
|
|
386
424
|
}
|
|
387
425
|
function reasonOf(error) {
|
|
@@ -459,6 +497,53 @@ function installDependencies(io, cwd, deps, dev, pm = detectPackageManagerFromLo
|
|
|
459
497
|
io.exec(buildInstallCommand(pm, deps, dev));
|
|
460
498
|
}
|
|
461
499
|
//#endregion
|
|
500
|
+
//#region src/lib/lockfile.ts
|
|
501
|
+
/** 组件版本记录文件,位于项目根(components.json 旁)。 */
|
|
502
|
+
const LOCKFILE_NAME = "components.lock.json";
|
|
503
|
+
function hashContent(content) {
|
|
504
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
505
|
+
}
|
|
506
|
+
/** 刻意不含 installedAt 之类时间戳字段:跨机器安装会产生 VCS diff 噪音。 */
|
|
507
|
+
function validateLockfile(raw) {
|
|
508
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(`${LOCKFILE_NAME} 内容不是 JSON 对象`);
|
|
509
|
+
const obj = raw;
|
|
510
|
+
if (obj.lockfileVersion !== 1) throw new Error(`${LOCKFILE_NAME} 的 lockfileVersion 必须是 1,得到 ${JSON.stringify(obj.lockfileVersion)}`);
|
|
511
|
+
const packages = obj.packages;
|
|
512
|
+
if (typeof packages !== "object" || packages === null || Array.isArray(packages)) throw new Error(`${LOCKFILE_NAME} 缺少 packages 对象`);
|
|
513
|
+
const out = {};
|
|
514
|
+
for (const [name, pkg] of Object.entries(packages)) {
|
|
515
|
+
if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) throw new Error(`${LOCKFILE_NAME} 的 packages.${name} 不是对象`);
|
|
516
|
+
const entry = pkg;
|
|
517
|
+
if (entry.version !== null && typeof entry.version !== "string") throw new Error(`${LOCKFILE_NAME} 的 packages.${name}.version 必须是字符串或 null,得到 ${typeof entry.version}`);
|
|
518
|
+
if (typeof entry.files !== "object" || entry.files === null || Array.isArray(entry.files)) throw new Error(`${LOCKFILE_NAME} 的 packages.${name}.files 必须是对象`);
|
|
519
|
+
const files = {};
|
|
520
|
+
for (const [path, hash] of Object.entries(entry.files)) {
|
|
521
|
+
if (typeof hash !== "string") throw new Error(`${LOCKFILE_NAME} 的 packages.${name}.files.${path} 必须是字符串,得到 ${typeof hash}`);
|
|
522
|
+
files[path] = hash;
|
|
523
|
+
}
|
|
524
|
+
out[name] = {
|
|
525
|
+
version: entry.version,
|
|
526
|
+
files
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
return {
|
|
530
|
+
lockfileVersion: 1,
|
|
531
|
+
packages: out
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
/** 文件缺失 → 空 lockfile;存在但 JSON/结构非法 → throw(损坏的 lockfile 不能静默当空处理)。 */
|
|
535
|
+
function readLockfile(io, root) {
|
|
536
|
+
const path = `${root}/${LOCKFILE_NAME}`;
|
|
537
|
+
if (!io.exists(path)) return {
|
|
538
|
+
lockfileVersion: 1,
|
|
539
|
+
packages: {}
|
|
540
|
+
};
|
|
541
|
+
return validateLockfile(parseJson(io.readFile(path), LOCKFILE_NAME));
|
|
542
|
+
}
|
|
543
|
+
function writeLockfile(io, root, lockfile) {
|
|
544
|
+
io.writeFile(`${root}/${LOCKFILE_NAME}`, `${JSON.stringify(lockfile, null, 2)}\n`);
|
|
545
|
+
}
|
|
546
|
+
//#endregion
|
|
462
547
|
//#region src/lib/write.ts
|
|
463
548
|
function parentDir(dir) {
|
|
464
549
|
if (dir === "/") return null;
|
|
@@ -517,17 +602,45 @@ function planWrites(items, io, aliasRoot, config) {
|
|
|
517
602
|
}
|
|
518
603
|
return plans;
|
|
519
604
|
}
|
|
605
|
+
/**
|
|
606
|
+
* 覆盖安全语义:内容比对(sha256)优先于存在性判断——
|
|
607
|
+
* 内容相同的重复安装不算冲突,静默跳过;只有「存在且内容不同」才进入覆盖询问 / conflict 分支。
|
|
608
|
+
*/
|
|
520
609
|
async function writeFiles(plans, io, opts) {
|
|
521
|
-
const
|
|
610
|
+
const result = {
|
|
611
|
+
written: [],
|
|
612
|
+
overwrites: [],
|
|
613
|
+
upToDate: [],
|
|
614
|
+
declined: [],
|
|
615
|
+
conflicts: []
|
|
616
|
+
};
|
|
522
617
|
for (const plan of plans) {
|
|
523
|
-
if (
|
|
524
|
-
if (
|
|
525
|
-
|
|
618
|
+
if (io.exists(plan.path)) {
|
|
619
|
+
if (hashContent(io.readFile(plan.path)) === hashContent(plan.content)) {
|
|
620
|
+
result.upToDate.push(plan.path);
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
if (opts.overwrite) {
|
|
624
|
+
io.writeFile(plan.path, plan.content);
|
|
625
|
+
result.written.push(plan.path);
|
|
626
|
+
result.overwrites.push(plan.path);
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (opts.confirm) {
|
|
630
|
+
if (await opts.confirm(`文件已有本地改动,覆盖?${plan.path}`)) {
|
|
631
|
+
io.writeFile(plan.path, plan.content);
|
|
632
|
+
result.written.push(plan.path);
|
|
633
|
+
result.overwrites.push(plan.path);
|
|
634
|
+
} else result.declined.push(plan.path);
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
result.conflicts.push(plan.path);
|
|
638
|
+
continue;
|
|
526
639
|
}
|
|
527
640
|
io.writeFile(plan.path, plan.content);
|
|
528
|
-
written.push(plan.path);
|
|
641
|
+
result.written.push(plan.path);
|
|
529
642
|
}
|
|
530
|
-
return
|
|
643
|
+
return result;
|
|
531
644
|
}
|
|
532
645
|
//#endregion
|
|
533
646
|
//#region src/lib/add-core.ts
|
|
@@ -566,32 +679,142 @@ function collectDeps(items) {
|
|
|
566
679
|
devDependencies
|
|
567
680
|
};
|
|
568
681
|
}
|
|
569
|
-
|
|
682
|
+
/** add / diff 共用:由项目根推出组件源码落点根(aliasRoot)。 */
|
|
683
|
+
function aliasRootOf(root) {
|
|
684
|
+
return `${root}/src`;
|
|
685
|
+
}
|
|
570
686
|
async function runAdd(io, cwd, names, opts) {
|
|
571
687
|
const root = findProjectRoot(io, cwd);
|
|
572
688
|
const config = loadConfig(io, root);
|
|
573
689
|
const registryUrl = resolveRegistryUrl(config, opts.registry);
|
|
574
|
-
const aliasRoot =
|
|
690
|
+
const aliasRoot = aliasRootOf(root);
|
|
575
691
|
const npm = opts.npm ?? {
|
|
576
692
|
hasItem: () => false,
|
|
577
693
|
readItem: () => void 0
|
|
578
694
|
};
|
|
579
695
|
const items = await resolveTopo(names, (name) => fetchItem(io, registryUrl, npm, name));
|
|
580
|
-
const
|
|
696
|
+
const plans = planWrites(items, io, aliasRoot, config);
|
|
697
|
+
const { dependencies, devDependencies } = collectDeps(items);
|
|
698
|
+
if (opts.dryRun) {
|
|
699
|
+
const files = [];
|
|
700
|
+
const overwrites = [];
|
|
701
|
+
const upToDate = [];
|
|
702
|
+
for (const plan of plans) {
|
|
703
|
+
if (!io.exists(plan.path)) {
|
|
704
|
+
files.push(plan.path);
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
if (hashContent(io.readFile(plan.path)) === hashContent(plan.content)) upToDate.push(plan.path);
|
|
708
|
+
else {
|
|
709
|
+
files.push(plan.path);
|
|
710
|
+
overwrites.push(plan.path);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return {
|
|
714
|
+
files,
|
|
715
|
+
overwrites,
|
|
716
|
+
conflicts: [],
|
|
717
|
+
upToDate,
|
|
718
|
+
declined: [],
|
|
719
|
+
dependencies,
|
|
720
|
+
devDependencies,
|
|
721
|
+
dryRun: true
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
const result = await writeFiles(plans, io, {
|
|
581
725
|
overwrite: opts.overwrite,
|
|
582
726
|
confirm: opts.confirm
|
|
583
727
|
});
|
|
584
|
-
const
|
|
728
|
+
const lockfile = readLockfile(io, root);
|
|
729
|
+
const knownRemote = /* @__PURE__ */ new Set([...result.written, ...result.upToDate]);
|
|
730
|
+
for (const item of items) {
|
|
731
|
+
const files = {};
|
|
732
|
+
let allKnown = true;
|
|
733
|
+
for (const file of item.files) {
|
|
734
|
+
const target = resolveTarget(file.target, config, aliasRoot);
|
|
735
|
+
if (!knownRemote.has(target)) {
|
|
736
|
+
allKnown = false;
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
files[target] = hashContent(file.content);
|
|
740
|
+
}
|
|
741
|
+
if (allKnown) lockfile.packages[item.name] = {
|
|
742
|
+
version: item.version ?? null,
|
|
743
|
+
files
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
writeLockfile(io, root, lockfile);
|
|
585
747
|
const pm = detectPackageManagerForProject(io, root);
|
|
586
748
|
if (dependencies.length > 0) installDependencies(io, root, dependencies, false, pm);
|
|
587
749
|
if (devDependencies.length > 0) installDependencies(io, root, devDependencies, true, pm);
|
|
588
750
|
return {
|
|
589
|
-
files,
|
|
751
|
+
files: result.written,
|
|
752
|
+
overwrites: result.overwrites,
|
|
753
|
+
conflicts: result.conflicts,
|
|
754
|
+
upToDate: result.upToDate,
|
|
755
|
+
declined: result.declined,
|
|
590
756
|
dependencies,
|
|
591
757
|
devDependencies
|
|
592
758
|
};
|
|
593
759
|
}
|
|
594
760
|
//#endregion
|
|
761
|
+
//#region src/lib/diff-core.ts
|
|
762
|
+
/**
|
|
763
|
+
* 本地文件 vs 线上 registry vs lockfile 安装时快照的三方比对。
|
|
764
|
+
* 每文件按有序决策树判定(first-match):
|
|
765
|
+
* 1. 本地 === 线上 → up-to-date
|
|
766
|
+
* 2. 无安装记录(legacy)且与线上不同 → different(两方对比降级)
|
|
767
|
+
* 3. 本地 === 上次安装 → updatable(本地干净,可安全覆盖)
|
|
768
|
+
* 4. 线上 === 上次安装 → modified(远端没动,本地改的)
|
|
769
|
+
* 5. 三方互不相同 → conflict
|
|
770
|
+
*/
|
|
771
|
+
async function diffComponents(io, fetcher, registryUrl, npm, root, config, names) {
|
|
772
|
+
const lockfile = readLockfile(io, root);
|
|
773
|
+
const list = names ?? Object.keys(lockfile.packages);
|
|
774
|
+
const aliasRoot = aliasRootOf(root);
|
|
775
|
+
const out = [];
|
|
776
|
+
for (const name of list) {
|
|
777
|
+
const record = lockfile.packages[name] ?? null;
|
|
778
|
+
const diff = {
|
|
779
|
+
name,
|
|
780
|
+
remoteVersion: null,
|
|
781
|
+
localVersion: record?.version ?? null,
|
|
782
|
+
legacy: record === null,
|
|
783
|
+
files: []
|
|
784
|
+
};
|
|
785
|
+
let item;
|
|
786
|
+
try {
|
|
787
|
+
item = await fetchItem(fetcher, registryUrl, npm, name);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
diff.error = error instanceof Error ? error.message : String(error);
|
|
790
|
+
out.push(diff);
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
diff.remoteVersion = item.version ?? null;
|
|
794
|
+
for (const file of item.files) {
|
|
795
|
+
const target = resolveTarget(file.target, config, aliasRoot);
|
|
796
|
+
const remoteHash = hashContent(file.content);
|
|
797
|
+
const installedHash = record?.files[target] ?? null;
|
|
798
|
+
let status;
|
|
799
|
+
if (!io.exists(target)) status = "missing";
|
|
800
|
+
else {
|
|
801
|
+
const localHash = hashContent(io.readFile(target));
|
|
802
|
+
if (localHash === remoteHash) status = "up-to-date";
|
|
803
|
+
else if (installedHash === null) status = "different";
|
|
804
|
+
else if (localHash === installedHash) status = "updatable";
|
|
805
|
+
else if (remoteHash === installedHash) status = "modified";
|
|
806
|
+
else status = "conflict";
|
|
807
|
+
}
|
|
808
|
+
diff.files.push({
|
|
809
|
+
target,
|
|
810
|
+
status
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
out.push(diff);
|
|
814
|
+
}
|
|
815
|
+
return out;
|
|
816
|
+
}
|
|
817
|
+
//#endregion
|
|
595
818
|
//#region src/lib/version.ts
|
|
596
819
|
/** 从 package.json 原始文本解析版本号(纯函数,便于测试)。 */
|
|
597
820
|
function parsePkgVersion(raw) {
|
|
@@ -617,17 +840,21 @@ function makeExecIo(cwd) {
|
|
|
617
840
|
};
|
|
618
841
|
}
|
|
619
842
|
const program = new Command();
|
|
620
|
-
|
|
621
|
-
program.
|
|
843
|
+
const PKG_VERSION = parsePkgVersion(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
844
|
+
program.name("tu-design").description("tu-design 组件 registry CLI").version(PKG_VERSION);
|
|
845
|
+
program.command("init").description("初始化 components.json 并注入基础依赖与样式 tokens").option("--registry <url>", "registry URL 通道", DEFAULT_REGISTRY).option("--css <path>", "全局 CSS 路径(默认自动探测常见位置)").option("--no-agents", "不写入 AGENTS.md AI 协作规则").action(async (opts) => {
|
|
622
846
|
const cwd = process.cwd();
|
|
623
847
|
try {
|
|
624
848
|
const summary = runInit(nodeIo, cwd, {
|
|
625
849
|
registry: opts.registry,
|
|
626
|
-
css: opts.css
|
|
850
|
+
css: opts.css,
|
|
851
|
+
agents: opts.agents
|
|
627
852
|
});
|
|
628
853
|
console.log(`✔ 已写入 ${summary.configPath}`);
|
|
629
854
|
console.log(`✔ 已注入 cn 工具 ${summary.cnPath}`);
|
|
630
855
|
console.log(summary.skippedCss ? `ℹ ${summary.cssPath} 已包含 tokens,跳过` : `✔ 已合并 tokens 至 ${summary.cssPath}`);
|
|
856
|
+
if (summary.skippedAgents) console.log(opts.agents === false ? "ℹ 已按 --no-agents 跳过 AGENTS.md" : "ℹ AGENTS.md 已存在,跳过");
|
|
857
|
+
else console.log("✔ 已写入 AGENTS.md(AI 协作规则)");
|
|
631
858
|
const pm = detectPackageManagerForProject(nodeIo, cwd);
|
|
632
859
|
console.log(`ℹ 使用 ${pm} 安装 ${RUNTIME_DEPS.join(" ")}`);
|
|
633
860
|
installDependencies(makeExecIo(cwd), cwd, RUNTIME_DEPS, false, pm);
|
|
@@ -637,7 +864,7 @@ program.command("init").description("初始化 components.json 并注入基础
|
|
|
637
864
|
process.exitCode = 1;
|
|
638
865
|
}
|
|
639
866
|
});
|
|
640
|
-
program.command("add <components...>").description("添加组件源码到项目").option("--registry <url>", "覆盖 components.json 中的 registry URL").option("--overwrite", "覆盖已存在的文件而不询问").action(async (components, opts) => {
|
|
867
|
+
program.command("add <components...>").description("添加组件源码到项目").option("--registry <url>", "覆盖 components.json 中的 registry URL").option("--overwrite", "覆盖已存在的文件而不询问").option("--dry-run", "预览模式:报告将写入/覆盖/已最新的文件,不实际写入").action(async (components, opts) => {
|
|
641
868
|
const cwd = process.cwd();
|
|
642
869
|
try {
|
|
643
870
|
const summary = await runAdd({
|
|
@@ -651,9 +878,9 @@ program.command("add <components...>").description("添加组件源码到项目"
|
|
|
651
878
|
}, cwd, components, {
|
|
652
879
|
registry: opts.registry,
|
|
653
880
|
overwrite: opts.overwrite,
|
|
881
|
+
dryRun: opts.dryRun,
|
|
654
882
|
npm: nodeNpmChannel,
|
|
655
|
-
confirm: async (msg) => {
|
|
656
|
-
if (!process.stdin.isTTY) return false;
|
|
883
|
+
confirm: process.stdin.isTTY ? async (msg) => {
|
|
657
884
|
const { default: prompts } = await import("prompts");
|
|
658
885
|
return (await prompts({
|
|
659
886
|
type: "confirm",
|
|
@@ -661,12 +888,44 @@ program.command("add <components...>").description("添加组件源码到项目"
|
|
|
661
888
|
message: msg,
|
|
662
889
|
initial: false
|
|
663
890
|
})).ok === true;
|
|
664
|
-
}
|
|
891
|
+
} : void 0
|
|
665
892
|
});
|
|
893
|
+
if (summary.dryRun) {
|
|
894
|
+
console.log("ℹ dry-run:未写入任何文件");
|
|
895
|
+
const fresh = summary.files.filter((f) => !summary.overwrites.includes(f));
|
|
896
|
+
if (fresh.length > 0) {
|
|
897
|
+
console.log("将写入:");
|
|
898
|
+
for (const f of fresh) console.log(` ${f}`);
|
|
899
|
+
}
|
|
900
|
+
if (summary.overwrites.length > 0) {
|
|
901
|
+
console.log("将覆盖:");
|
|
902
|
+
for (const f of summary.overwrites) console.log(` ${f}`);
|
|
903
|
+
}
|
|
904
|
+
if (summary.upToDate.length > 0) {
|
|
905
|
+
console.log("已最新(跳过):");
|
|
906
|
+
for (const f of summary.upToDate) console.log(` ${f}`);
|
|
907
|
+
}
|
|
908
|
+
const willInstall = [...summary.dependencies, ...summary.devDependencies];
|
|
909
|
+
if (willInstall.length > 0) console.log(`ℹ 将安装依赖(dry-run 未执行):${willInstall.join(" ")}`);
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
666
912
|
if (summary.files.length > 0) {
|
|
667
913
|
console.log("✔ 写入文件:");
|
|
668
914
|
for (const f of summary.files) console.log(` ${f}`);
|
|
669
|
-
} else console.log("ℹ
|
|
915
|
+
} else console.log("ℹ 没有写入任何文件(可能已最新或全部跳过)");
|
|
916
|
+
if (summary.upToDate.length > 0) {
|
|
917
|
+
console.log("ℹ 已是最新(跳过):");
|
|
918
|
+
for (const f of summary.upToDate) console.log(` ${f}`);
|
|
919
|
+
}
|
|
920
|
+
if (summary.declined.length > 0) {
|
|
921
|
+
console.log("ℹ 已拒绝覆盖:");
|
|
922
|
+
for (const f of summary.declined) console.log(` ${f}`);
|
|
923
|
+
}
|
|
924
|
+
if (summary.conflicts.length > 0) {
|
|
925
|
+
console.log(picocolors.yellow(`⚠ ${summary.conflicts.length} 个文件本地有改动且未覆盖;非交互环境如需覆盖请加 --overwrite`));
|
|
926
|
+
for (const f of summary.conflicts) console.log(picocolors.yellow(` ${f}`));
|
|
927
|
+
process.exitCode = 1;
|
|
928
|
+
}
|
|
670
929
|
for (const d of summary.dependencies) console.log(`✔ 依赖 ${picocolors.cyan(d)}`);
|
|
671
930
|
for (const d of summary.devDependencies) console.log(`✔ 开发依赖 ${picocolors.cyan(d)}`);
|
|
672
931
|
} catch (error) {
|
|
@@ -674,6 +933,132 @@ program.command("add <components...>").description("添加组件源码到项目"
|
|
|
674
933
|
process.exitCode = 1;
|
|
675
934
|
}
|
|
676
935
|
});
|
|
936
|
+
/** diff 状态的中文标签(展示层职责,纯逻辑层只产英文枚举)。 */
|
|
937
|
+
const DIFF_STATUS_LABELS = {
|
|
938
|
+
"up-to-date": "最新",
|
|
939
|
+
updatable: "可更新",
|
|
940
|
+
modified: "本地已改",
|
|
941
|
+
conflict: "冲突",
|
|
942
|
+
missing: "缺失",
|
|
943
|
+
different: "不一致(未跟踪)"
|
|
944
|
+
};
|
|
945
|
+
program.command("diff [components...]").description("比对本地组件与线上 registry(无参数时比对 components.lock.json 记录的全部组件)").option("--registry <url>", "覆盖 components.json 中的 registry URL").action(async (components, opts) => {
|
|
946
|
+
const cwd = process.cwd();
|
|
947
|
+
try {
|
|
948
|
+
const diffIo = {
|
|
949
|
+
...nodeIo,
|
|
950
|
+
async fetchJson(url) {
|
|
951
|
+
const res = await fetch(url);
|
|
952
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
|
|
953
|
+
return res.json();
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
const root = findProjectRoot(nodeIo, cwd);
|
|
957
|
+
const config = loadConfig(nodeIo, root);
|
|
958
|
+
const registryUrl = resolveRegistryUrl(config, opts.registry);
|
|
959
|
+
const names = components && components.length > 0 ? components : void 0;
|
|
960
|
+
const diffs = await diffComponents(diffIo, diffIo, registryUrl, nodeNpmChannel, root, config, names);
|
|
961
|
+
if (diffs.length === 0) {
|
|
962
|
+
console.log("ℹ 没有可比对的组件(components.lock.json 不存在或为空;可指定组件名)");
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
const counts = /* @__PURE__ */ new Map();
|
|
966
|
+
for (const d of diffs) {
|
|
967
|
+
const localPart = d.legacy ? "本地未跟踪(legacy)" : `本地 ${d.localVersion ?? "-"}`;
|
|
968
|
+
console.log(`▸ ${d.name}(线上 ${d.remoteVersion ?? "-"} / ${localPart})`);
|
|
969
|
+
for (const f of d.files) {
|
|
970
|
+
console.log(` ${DIFF_STATUS_LABELS[f.status]} ${f.target}`);
|
|
971
|
+
counts.set(f.status, (counts.get(f.status) ?? 0) + 1);
|
|
972
|
+
}
|
|
973
|
+
if (d.error !== void 0) console.log(picocolors.yellow(` ⚠ 获取失败:${d.error}`));
|
|
974
|
+
}
|
|
975
|
+
const stat = Object.keys(DIFF_STATUS_LABELS).filter((s) => (counts.get(s) ?? 0) > 0).map((s) => `${DIFF_STATUS_LABELS[s]} ${counts.get(s)}`).join(",");
|
|
976
|
+
if (stat.length > 0) console.log(`ℹ 统计:${stat}`);
|
|
977
|
+
const affected = diffs.filter((d) => d.files.some((f) => f.status === "updatable" || f.status === "conflict" || f.status === "missing")).map((d) => d.name);
|
|
978
|
+
if (affected.length > 0) console.log(`ℹ 更新:npx @tu-design/cli add ${affected.join(" ")} --overwrite`);
|
|
979
|
+
if ((counts.get("conflict") ?? 0) > 0) console.log(picocolors.yellow("⚠ 冲突文件:本地、上次安装、线上三者互不相同,建议先 git diff 人工比对再覆盖"));
|
|
980
|
+
} catch (error) {
|
|
981
|
+
console.error(picocolors.red(`✖ ${error instanceof Error ? error.message : String(error)}`));
|
|
982
|
+
process.exitCode = 1;
|
|
983
|
+
}
|
|
984
|
+
});
|
|
985
|
+
/** MCP 错误统一转 isError 结果(stdout 只承载 JSON-RPC,消息文本放 content)。 */
|
|
986
|
+
function mcpError(error) {
|
|
987
|
+
return {
|
|
988
|
+
isError: true,
|
|
989
|
+
content: [{
|
|
990
|
+
type: "text",
|
|
991
|
+
text: error instanceof Error ? error.message : String(error)
|
|
992
|
+
}]
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
function registryHttpFetcher() {
|
|
996
|
+
return { async fetchJson(url) {
|
|
997
|
+
const res = await fetch(url);
|
|
998
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
|
|
999
|
+
return res.json();
|
|
1000
|
+
} };
|
|
1001
|
+
}
|
|
1002
|
+
program.command("mcp").description("启动 MCP Server(stdio,仅查询组件 registry)").option("--registry <url>", "registry URL 通道", DEFAULT_REGISTRY).action(async (opts) => {
|
|
1003
|
+
const log = (msg) => console.error(msg);
|
|
1004
|
+
try {
|
|
1005
|
+
const [{ McpServer }, { StdioServerTransport }, { z }, { fetchRegistryIndex, searchComponents, getComponent }] = await Promise.all([
|
|
1006
|
+
import("@modelcontextprotocol/sdk/server/mcp.js"),
|
|
1007
|
+
import("@modelcontextprotocol/sdk/server/stdio.js"),
|
|
1008
|
+
import("zod"),
|
|
1009
|
+
import("./mcp-core-Ct8Xf-FY.mjs")
|
|
1010
|
+
]);
|
|
1011
|
+
const fetcher = registryHttpFetcher();
|
|
1012
|
+
const server = new McpServer({
|
|
1013
|
+
name: "tu-design",
|
|
1014
|
+
version: PKG_VERSION
|
|
1015
|
+
});
|
|
1016
|
+
server.registerTool("list_components", { description: "列出全部 tu-design 组件(name / title / description)" }, async () => {
|
|
1017
|
+
try {
|
|
1018
|
+
const list = await fetchRegistryIndex(fetcher, opts.registry);
|
|
1019
|
+
return { content: [{
|
|
1020
|
+
type: "text",
|
|
1021
|
+
text: JSON.stringify(list, null, 2)
|
|
1022
|
+
}] };
|
|
1023
|
+
} catch (error) {
|
|
1024
|
+
return mcpError(error);
|
|
1025
|
+
}
|
|
1026
|
+
});
|
|
1027
|
+
server.registerTool("search_components", {
|
|
1028
|
+
description: "按关键字搜索 tu-design 组件(大小写不敏感,匹配 name / title / description)",
|
|
1029
|
+
inputSchema: { query: z.string().describe("搜索关键字,如 table、dialog、表格") }
|
|
1030
|
+
}, async ({ query }) => {
|
|
1031
|
+
try {
|
|
1032
|
+
const results = await searchComponents(fetcher, opts.registry, query);
|
|
1033
|
+
return { content: [{
|
|
1034
|
+
type: "text",
|
|
1035
|
+
text: JSON.stringify(results, null, 2)
|
|
1036
|
+
}] };
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
return mcpError(error);
|
|
1039
|
+
}
|
|
1040
|
+
});
|
|
1041
|
+
server.registerTool("get_component", {
|
|
1042
|
+
description: "获取单个 tu-design 组件的 registry 详情(内联源码 files、依赖、安装提示);只查询,不安装",
|
|
1043
|
+
inputSchema: { name: z.string().describe("组件名,小写字母/数字/连字符,如 button") }
|
|
1044
|
+
}, async ({ name }) => {
|
|
1045
|
+
try {
|
|
1046
|
+
const item = await getComponent(fetcher, opts.registry, name);
|
|
1047
|
+
return { content: [{
|
|
1048
|
+
type: "text",
|
|
1049
|
+
text: JSON.stringify(item, null, 2)
|
|
1050
|
+
}] };
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
return mcpError(error);
|
|
1053
|
+
}
|
|
1054
|
+
});
|
|
1055
|
+
await server.connect(new StdioServerTransport());
|
|
1056
|
+
log("tu-design MCP server 运行中(stdio)");
|
|
1057
|
+
} catch (error) {
|
|
1058
|
+
log(`✖ ${error instanceof Error ? error.message : String(error)}`);
|
|
1059
|
+
process.exitCode = 1;
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
677
1062
|
program.parse();
|
|
678
1063
|
//#endregion
|
|
679
|
-
export {};
|
|
1064
|
+
export { validateRegistryItem as t };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { t as validateRegistryItem } from "./index.mjs";
|
|
2
|
+
//#region src/lib/mcp-core.ts
|
|
3
|
+
/** 组件名只允许小写字母、数字与连字符:防路径穿越与 URL 注入。 */
|
|
4
|
+
const NAME_RE = /^[a-z0-9-]+$/;
|
|
5
|
+
/** registry URL 尾斜杠会让拼接变成 //name.json,多数静态托管据此 404。 */
|
|
6
|
+
function trimUrl(registryUrl) {
|
|
7
|
+
return registryUrl.replace(/\/+$/, "");
|
|
8
|
+
}
|
|
9
|
+
function reasonOf(error) {
|
|
10
|
+
return error instanceof Error ? error.message : String(error);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* 拉取 registry 索引(GET `${registryUrl}/registry.json`),过滤只留 registry:ui 组件。
|
|
14
|
+
* 最小形态校验:items 为数组、每项 name 为 string;错误消息中文且含 URL,便于定位数据源问题。
|
|
15
|
+
*/
|
|
16
|
+
async function fetchRegistryIndex(fetcher, registryUrl) {
|
|
17
|
+
const url = `${trimUrl(registryUrl)}/registry.json`;
|
|
18
|
+
const raw = await fetcher.fetchJson(url);
|
|
19
|
+
if (typeof raw !== "object" || raw === null) throw new Error(`registry index 不是 JSON 对象:${url}`);
|
|
20
|
+
const items = raw.items;
|
|
21
|
+
if (!Array.isArray(items)) throw new Error(`registry index 缺少 items 数组:${url}`);
|
|
22
|
+
return items.map((item, index) => {
|
|
23
|
+
if (typeof item !== "object" || item === null || typeof item.name !== "string") throw new Error(`registry index items[${index}] 缺少 name 字符串字段:${url}`);
|
|
24
|
+
const obj = item;
|
|
25
|
+
return {
|
|
26
|
+
name: obj.name,
|
|
27
|
+
type: obj.type,
|
|
28
|
+
title: obj.title,
|
|
29
|
+
description: obj.description
|
|
30
|
+
};
|
|
31
|
+
}).filter((item) => item.type === "registry:ui").map((item) => ({
|
|
32
|
+
name: item.name,
|
|
33
|
+
title: typeof item.title === "string" ? item.title : "",
|
|
34
|
+
description: typeof item.description === "string" ? item.description : ""
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
/** 在 name / title / description 上做大小写不敏感子串过滤(空 query 返回全部)。 */
|
|
38
|
+
async function searchComponents(fetcher, registryUrl, query) {
|
|
39
|
+
const entries = await fetchRegistryIndex(fetcher, registryUrl);
|
|
40
|
+
const q = query.toLowerCase();
|
|
41
|
+
return entries.filter((e) => e.name.toLowerCase().includes(q) || e.title.toLowerCase().includes(q) || e.description.toLowerCase().includes(q));
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 拉取单个组件 registry item(GET `${registryUrl}/${name}.json`)。
|
|
45
|
+
* 只走线上 URL 通道并复用 validateRegistryItem 校验,不用 fetchItem 的 npm 回退——
|
|
46
|
+
* MCP 是只读查询面,npm 本地回退会让查询结果取决于安装缓存,语义混乱。
|
|
47
|
+
* 返回项附加 installHint,引导 AI 用 CLI 安装而不是复制源码。
|
|
48
|
+
*/
|
|
49
|
+
async function getComponent(fetcher, registryUrl, name) {
|
|
50
|
+
if (!NAME_RE.test(name)) throw new Error(`非法组件名 ${name}:只允许小写字母、数字与连字符`);
|
|
51
|
+
const url = `${trimUrl(registryUrl)}/${name}.json`;
|
|
52
|
+
let raw;
|
|
53
|
+
try {
|
|
54
|
+
raw = await fetcher.fetchJson(url);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new Error(`无法获取组件 ${name}:${url} 拉取失败(${reasonOf(error)})`);
|
|
57
|
+
}
|
|
58
|
+
let item;
|
|
59
|
+
try {
|
|
60
|
+
item = validateRegistryItem(raw);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
throw new Error(`组件 ${name} 的 registry item 校验失败:${url}(${reasonOf(error)})`);
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
...item,
|
|
66
|
+
installHint: `npx @tu-design/cli add ${item.name}`
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
export { fetchRegistryIndex, getComponent, searchComponents };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tu-design/cli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "tu-design CLI:初始化并按 registry 分发组件源码到用户项目(shadcn 模式)。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -34,10 +34,12 @@
|
|
|
34
34
|
"access": "public"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@
|
|
37
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
38
|
+
"@tu-design/vue": "0.4.2",
|
|
38
39
|
"commander": "^15",
|
|
39
40
|
"picocolors": "^1",
|
|
40
|
-
"prompts": "^2"
|
|
41
|
+
"prompts": "^2",
|
|
42
|
+
"zod": "^4"
|
|
41
43
|
},
|
|
42
44
|
"devDependencies": {
|
|
43
45
|
"@types/prompts": "^2.4.8",
|