@tu-design/cli 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zhuchentong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.mjs ADDED
@@ -0,0 +1,585 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { spawnSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
5
+ import { Command } from "commander";
6
+ import picocolors from "picocolors";
7
+ import { detect } from "package-manager-detector";
8
+ import { dirname, join } from "node:path";
9
+ //#region src/io/node.ts
10
+ const nodeIo = {
11
+ exists: (path) => existsSync(path),
12
+ readFile: (path) => readFileSync(path, "utf8"),
13
+ writeFile: (path, content) => {
14
+ mkdirSync(dirname(path), { recursive: true });
15
+ writeFileSync(path, content);
16
+ },
17
+ readDir: (path) => readdirSync(path)
18
+ };
19
+ /** npm 通道:读取依赖 @tu-design/vue 包内 dist/registry/vue/<name>.json。 */
20
+ const nodeNpmChannel = {
21
+ hasItem(name) {
22
+ return existsSync(npmItemPath(name));
23
+ },
24
+ readItem(name) {
25
+ return JSON.parse(readFileSync(npmItemPath(name), "utf8"));
26
+ }
27
+ };
28
+ function npmItemPath(name) {
29
+ const pkgJson = createRequire(import.meta.url).resolve("@tu-design/vue/package.json");
30
+ return join(dirname(pkgJson), "dist/registry/vue", `${name}.json`);
31
+ }
32
+ //#endregion
33
+ //#region src/lib/config.ts
34
+ /** init 未显式传 --registry 时写入 components.json 的默认 URL 通道(不可达时 add 走 npm 兜底)。 */
35
+ const DEFAULT_REGISTRY = "https://gopowerteam.github.io/tu-design/r/vue";
36
+ const CONFIG_FILE = "components.json";
37
+ const ALIAS_KEYS = [
38
+ "components",
39
+ "utils",
40
+ "ui",
41
+ "lib"
42
+ ];
43
+ function validateConfig(raw) {
44
+ if (typeof raw !== "object" || raw === null) throw new Error(`${CONFIG_FILE} 内容不是 JSON 对象`);
45
+ const obj = raw;
46
+ const missing = [];
47
+ if (obj.framework === void 0) missing.push("framework");
48
+ else if (obj.framework !== "vue") throw new Error(`${CONFIG_FILE} 的 framework 仅支持 "vue",得到 ${JSON.stringify(obj.framework)}`);
49
+ if (typeof obj.registry !== "string") missing.push("registry");
50
+ const aliases = obj.aliases;
51
+ if (typeof aliases !== "object" || aliases === null) missing.push("aliases");
52
+ else for (const key of ALIAS_KEYS) if (typeof aliases[key] !== "string") missing.push(`aliases.${key}`);
53
+ const tailwind = obj.tailwind;
54
+ if (typeof tailwind !== "object" || tailwind === null) missing.push("tailwind");
55
+ else if (typeof tailwind.css !== "string") missing.push("tailwind.css");
56
+ if (missing.length > 0) throw new Error(`${CONFIG_FILE} 缺少或非法字段:${missing.join("、")}`);
57
+ return raw;
58
+ }
59
+ function defaultConfig(registry) {
60
+ return {
61
+ framework: "vue",
62
+ registry,
63
+ aliases: {
64
+ components: "@/components",
65
+ utils: "@/lib/utils",
66
+ ui: "@/components/ui",
67
+ lib: "@/lib"
68
+ },
69
+ tailwind: { css: "src/assets/main.css" }
70
+ };
71
+ }
72
+ function configPath(cwd) {
73
+ return `${cwd}/${CONFIG_FILE}`;
74
+ }
75
+ function loadConfig(io, cwd) {
76
+ const path = configPath(cwd);
77
+ if (!io.exists(path)) throw new Error(`未找到 ${CONFIG_FILE},请先运行 \`tu-design init\``);
78
+ return validateConfig(JSON.parse(io.readFile(path)));
79
+ }
80
+ function saveConfig(io, cwd, config) {
81
+ io.writeFile(configPath(cwd), `${JSON.stringify(config, null, 2)}\n`);
82
+ }
83
+ //#endregion
84
+ //#region src/lib/alias.ts
85
+ /**
86
+ * 将 paths 合并进 tsconfig 文本。优先 JSON round-trip;
87
+ * JSONC(带注释等无法解析)时回退纯文本插入,保留原注释。
88
+ */
89
+ function mergeTsconfigPaths(source, paths) {
90
+ let parsed;
91
+ try {
92
+ parsed = JSON.parse(source);
93
+ } catch {
94
+ return insertPathsText(source, paths);
95
+ }
96
+ if (typeof parsed !== "object" || parsed === null) return insertPathsText(source, paths);
97
+ const root = parsed;
98
+ const options = typeof root.compilerOptions === "object" && root.compilerOptions !== null ? root.compilerOptions : {};
99
+ options.paths = {
100
+ ...typeof options.paths === "object" && options.paths !== null ? options.paths : {},
101
+ ...paths
102
+ };
103
+ root.compilerOptions = options;
104
+ return `${JSON.stringify(root, null, 2)}\n`;
105
+ }
106
+ /**
107
+ * JSONC 回退:在 "compilerOptions": { 后做纯文本插入,保留注释;
108
+ * 已有 paths 或结构不识别时返回原文(调用方提示手动配置)。
109
+ */
110
+ function insertPathsText(source, paths) {
111
+ if (/"paths"\s*:/.test(source)) return source;
112
+ const match = /"compilerOptions"\s*:\s*\{/.exec(source);
113
+ if (!match) return source;
114
+ const insertAt = match.index + match[0].length;
115
+ const text = `\n "paths": ${JSON.stringify(paths)},`;
116
+ return `${source.slice(0, insertAt)}${text}${source.slice(insertAt)}`;
117
+ }
118
+ /**
119
+ * 将 alias 注入 vite 配置文本(纯字符串变换,无 AST):
120
+ * - 已有 alias 对象 → 在对象首行后追加键
121
+ * - 有 resolve 无 alias → 在 resolve 块内补 alias
122
+ * - 都没有 → 在 defineConfig({ 后插入 resolve 块
123
+ * - 无 defineConfig / 结构不识别 → 返回原文(调用方打印手动指引)
124
+ */
125
+ function mergeViteAlias(source, alias) {
126
+ if (!source.includes("defineConfig(")) return source;
127
+ if (new RegExp(`["']${alias.find}["']\\s*:`).test(source)) return source;
128
+ const entry = ` "${alias.find}": ${alias.replacement},\n`;
129
+ if (source.includes("alias: {")) {
130
+ const insertAt = source.indexOf("alias: {") + 8;
131
+ return `${source.slice(0, insertAt)}\n${entry}${source.slice(insertAt)}`;
132
+ }
133
+ if (source.includes("resolve: {")) {
134
+ const insertAt = source.indexOf("resolve: {") + 10;
135
+ const block = `\n alias: {\n${entry} },`;
136
+ return `${source.slice(0, insertAt)}${block}${source.slice(insertAt)}`;
137
+ }
138
+ const idx = source.indexOf("defineConfig({");
139
+ if (idx === -1) return source;
140
+ const insertAt = idx + 14;
141
+ const block = `\n resolve: {\n alias: {\n${entry} },\n },`;
142
+ return `${source.slice(0, insertAt)}${block}${source.slice(insertAt)}`;
143
+ }
144
+ function applyAliases(io, cwd, aliasRoot) {
145
+ const paths = { "@/*": [`./${aliasRoot}/*`] };
146
+ for (const name of ["tsconfig.json", "tsconfig.app.json"]) {
147
+ const tsconfigPath = `${cwd}/${name}`;
148
+ if (io.exists(tsconfigPath)) io.writeFile(tsconfigPath, mergeTsconfigPaths(io.readFile(tsconfigPath), paths));
149
+ }
150
+ const viteConfigPath = `${cwd}/vite.config.ts`;
151
+ if (io.exists(viteConfigPath)) {
152
+ const merged = mergeViteAlias(io.readFile(viteConfigPath), {
153
+ find: "@",
154
+ replacement: JSON.stringify(`${cwd}/${aliasRoot}`)
155
+ });
156
+ io.writeFile(viteConfigPath, merged);
157
+ }
158
+ }
159
+ //#endregion
160
+ //#region src/lib/init-core.ts
161
+ /**
162
+ * 与 @tu-design/vue/src/styles/tokens.css 保持一致(init-core.test.ts 有防漂移守卫)。
163
+ * 来源:packages/vue/src/styles/tokens.css
164
+ */
165
+ const TOKENS_CSS_SOURCE = `@import "tw-animate-css";
166
+
167
+ @custom-variant dark (&:where(.dark, .dark *));
168
+
169
+ :root {
170
+ --background: oklch(1 0 0);
171
+ --foreground: oklch(0.145 0 0);
172
+ --card: oklch(1 0 0);
173
+ --card-foreground: oklch(0.145 0 0);
174
+ --popover: oklch(1 0 0);
175
+ --popover-foreground: oklch(0.145 0 0);
176
+ --primary: oklch(0.205 0 0);
177
+ --primary-foreground: oklch(0.985 0 0);
178
+ --secondary: oklch(0.97 0 0);
179
+ --secondary-foreground: oklch(0.205 0 0);
180
+ --muted: oklch(0.97 0 0);
181
+ --muted-foreground: oklch(0.556 0 0);
182
+ --accent: oklch(0.97 0 0);
183
+ --accent-foreground: oklch(0.205 0 0);
184
+ --destructive: oklch(0.577 0.245 27.325);
185
+ --border: oklch(0.922 0 0);
186
+ --input: oklch(0.922 0 0);
187
+ --ring: oklch(0.708 0 0);
188
+ --radius: 0.625rem;
189
+ }
190
+
191
+ .dark {
192
+ --background: oklch(0.145 0 0);
193
+ --foreground: oklch(0.985 0 0);
194
+ --card: oklch(0.205 0 0);
195
+ --card-foreground: oklch(0.985 0 0);
196
+ --popover: oklch(0.269 0 0);
197
+ --popover-foreground: oklch(0.985 0 0);
198
+ --primary: oklch(0.922 0 0);
199
+ --primary-foreground: oklch(0.205 0 0);
200
+ --secondary: oklch(0.269 0 0);
201
+ --secondary-foreground: oklch(0.985 0 0);
202
+ --muted: oklch(0.269 0 0);
203
+ --muted-foreground: oklch(0.708 0 0);
204
+ --accent: oklch(0.371 0 0);
205
+ --accent-foreground: oklch(0.985 0 0);
206
+ --destructive: oklch(0.704 0.191 22.216);
207
+ --border: oklch(1 0 0 / 10%);
208
+ --input: oklch(1 0 0 / 15%);
209
+ --ring: oklch(0.556 0 0);
210
+ }
211
+
212
+ @theme inline {
213
+ --radius-sm: calc(var(--radius) - 4px);
214
+ --radius-md: calc(var(--radius) - 2px);
215
+ --radius-lg: var(--radius);
216
+ --radius-xl: calc(var(--radius) + 4px);
217
+ --color-background: var(--background);
218
+ --color-foreground: var(--foreground);
219
+ --color-card: var(--card);
220
+ --color-card-foreground: var(--card-foreground);
221
+ --color-popover: var(--popover);
222
+ --color-popover-foreground: var(--popover-foreground);
223
+ --color-primary: var(--primary);
224
+ --color-primary-foreground: var(--primary-foreground);
225
+ --color-secondary: var(--secondary);
226
+ --color-secondary-foreground: var(--secondary-foreground);
227
+ --color-muted: var(--muted);
228
+ --color-muted-foreground: var(--muted-foreground);
229
+ --color-accent: var(--accent);
230
+ --color-accent-foreground: var(--accent-foreground);
231
+ --color-destructive: var(--destructive);
232
+ --color-border: var(--border);
233
+ --color-input: var(--input);
234
+ --color-ring: var(--ring);
235
+ }
236
+
237
+ /* 全局边框色兜底,对齐 shadcn v4 官方 tokens(上游另含 outline-ring/50,此处仅移植 border):
238
+ 裸 border 类不再回退 currentColor,而是使用 --border token。 */
239
+ @layer base {
240
+ * {
241
+ border-color: var(--color-border);
242
+ }
243
+ }
244
+ `;
245
+ /** cn 工具模板,等价 @tu-design/vue/src/lib/utils.ts。 */
246
+ const CN_UTIL_SOURCE = `import { clsx, type ClassValue } from "clsx";
247
+ import { twMerge } from "tailwind-merge";
248
+
249
+ export function cn(...inputs: ClassValue[]) {
250
+ return twMerge(clsx(inputs));
251
+ }
252
+ `;
253
+ function detectTailwindV4(pkg, globalCss) {
254
+ const tw = {
255
+ ...pkg.dependencies,
256
+ ...pkg.devDependencies
257
+ }.tailwindcss;
258
+ if (!tw || !/^[~^]?4\./.test(tw)) return false;
259
+ return globalCss.includes("@import \"tailwindcss\"");
260
+ }
261
+ function mergeTokensCss(userCss, tokensCss) {
262
+ if (userCss.includes("@custom-variant dark")) return userCss;
263
+ const idx = userCss.indexOf("@import \"tailwindcss\";");
264
+ if (idx === -1) return `${userCss.trimEnd()}\n\n${tokensCss}`;
265
+ const end = idx + 22;
266
+ return `${userCss.slice(0, end)}\n${tokensCss}${userCss.slice(end)}`;
267
+ }
268
+ function joinPosix(...parts) {
269
+ return parts.map((p, i) => i === 0 ? p.replace(/\/+$/, "") : p.replace(/^\/+|\/+$/g, "")).filter((p) => p.length > 0).join("/");
270
+ }
271
+ /** 常见全局 CSS 位置(探测依次命中第一个含 @import "tailwindcss" 的文件)。 */
272
+ const CSS_PROBE = [
273
+ "src/assets/main.css",
274
+ "src/style.css",
275
+ "src/index.css",
276
+ "src/main.css",
277
+ "src/App.css",
278
+ "style.css"
279
+ ];
280
+ function probeCssPath(io, cwd, configured) {
281
+ for (const rel of [configured, ...CSS_PROBE]) {
282
+ const full = joinPosix(cwd, rel);
283
+ if (io.exists(full) && io.readFile(full).includes("@import \"tailwindcss\"")) return rel;
284
+ }
285
+ return configured;
286
+ }
287
+ function runInit(io, cwd, opts) {
288
+ const aliasRoot = opts.aliasRoot ?? "src";
289
+ const config = defaultConfig(opts.registry);
290
+ const cssRel = probeCssPath(io, cwd, opts.css ?? config.tailwind.css);
291
+ const cssPath = joinPosix(cwd, cssRel);
292
+ const globalCss = io.exists(cssPath) ? io.readFile(cssPath) : "";
293
+ if (!detectTailwindV4(JSON.parse(io.readFile(joinPosix(cwd, "package.json"))), globalCss)) throw new Error("未检测到 Tailwind CSS v4:需要 package.json 中的 tailwindcss ^4 依赖,以及全局 CSS 中的 @import \"tailwindcss\";");
294
+ const configPath = joinPosix(cwd, "components.json");
295
+ if (io.exists(configPath)) validateConfig(JSON.parse(io.readFile(configPath)));
296
+ else saveConfig(io, cwd, {
297
+ ...config,
298
+ tailwind: { css: cssRel }
299
+ });
300
+ const cnPath = joinPosix(cwd, aliasRoot, `${config.aliases.utils.replace(/^@\//, "")}.ts`);
301
+ io.writeFile(cnPath, CN_UTIL_SOURCE);
302
+ const merged = mergeTokensCss(globalCss, TOKENS_CSS_SOURCE);
303
+ const skippedCss = merged === globalCss;
304
+ if (!skippedCss) io.writeFile(cssPath, merged);
305
+ applyAliases(io, cwd, aliasRoot);
306
+ return {
307
+ configPath,
308
+ cnPath,
309
+ cssPath,
310
+ skippedCss
311
+ };
312
+ }
313
+ //#endregion
314
+ //#region src/lib/registry.ts
315
+ const ITEM_TYPES = [
316
+ "registry:ui",
317
+ "registry:lib",
318
+ "registry:style"
319
+ ];
320
+ /** override(--registry)优先于 components.json。 */
321
+ function resolveRegistryUrl(config, override) {
322
+ return override ?? config.registry;
323
+ }
324
+ /** registry item 最小结构校验(name/type/files)。 */
325
+ function validateRegistryItem(raw) {
326
+ if (typeof raw !== "object" || raw === null) throw new Error("registry item 不是 JSON 对象");
327
+ const obj = raw;
328
+ const missing = [];
329
+ if (typeof obj.name !== "string") missing.push("name");
330
+ if (typeof obj.type !== "string" || !ITEM_TYPES.includes(obj.type)) missing.push("type");
331
+ if (!Array.isArray(obj.files)) missing.push("files");
332
+ if (missing.length > 0) throw new Error(`registry item 缺少字段:${missing.join("、")}`);
333
+ return raw;
334
+ }
335
+ /**
336
+ * 双通道解析:URL 优先(fetch `${registryUrl}/${name}.json`),
337
+ * 失败 / 404 / 校验不过时回退 npm 通道;双失败抛错含组件名。
338
+ */
339
+ async function fetchItem(fetcher, registryUrl, npm, name) {
340
+ try {
341
+ return validateRegistryItem(await fetcher.fetchJson(`${registryUrl}/${name}.json`));
342
+ } catch {}
343
+ if (npm.hasItem(name)) return validateRegistryItem(npm.readItem(name));
344
+ throw new Error(`无法获取组件 ${name}:URL 通道与 npm 通道(@tu-design/vue)均不可用`);
345
+ }
346
+ //#endregion
347
+ //#region src/lib/pm.ts
348
+ const PM_NAMES = [
349
+ "pnpm",
350
+ "npm",
351
+ "yarn",
352
+ "bun"
353
+ ];
354
+ /** agent 形如 "pnpm@9.15.0";未知识别为 npm。 */
355
+ function detectPackageManager(agent) {
356
+ if (!agent) return "npm";
357
+ const name = agent.split("@")[0] ?? agent;
358
+ return PM_NAMES.includes(name) ? name : "npm";
359
+ }
360
+ /** 由 cwd 锁文件推断包管理器(package-manager-detector 的纯 IO 兜底路径)。 */
361
+ function detectPackageManagerFromLockfiles(io, cwd) {
362
+ if (io.exists(`${cwd}/pnpm-lock.yaml`)) return "pnpm";
363
+ if (io.exists(`${cwd}/yarn.lock`)) return "yarn";
364
+ if (io.exists(`${cwd}/bun.lockb`) || io.exists(`${cwd}/bun.lock`)) return "bun";
365
+ return "npm";
366
+ }
367
+ function buildInstallCommand(pm, deps, dev) {
368
+ const base = {
369
+ pnpm: ["pnpm", "add"],
370
+ npm: ["npm", "install"],
371
+ yarn: ["yarn", "add"],
372
+ bun: ["bun", "add"]
373
+ };
374
+ const devFlag = {
375
+ pnpm: "-D",
376
+ npm: "-D",
377
+ yarn: "-D",
378
+ bun: "-d"
379
+ };
380
+ const cmd = [...base[pm], ...deps];
381
+ return dev ? [...cmd, devFlag[pm]] : cmd;
382
+ }
383
+ function installDependencies(io, cwd, deps, dev, pm = detectPackageManagerFromLockfiles(io, cwd)) {
384
+ if (deps.length === 0) return;
385
+ io.exec(buildInstallCommand(pm, deps, dev));
386
+ }
387
+ //#endregion
388
+ //#region src/lib/write.ts
389
+ function parentDir(dir) {
390
+ if (dir === "/") return null;
391
+ const idx = dir.lastIndexOf("/");
392
+ return idx <= 0 ? "/" : dir.slice(0, idx);
393
+ }
394
+ /** 自 cwd 向上找最近的 components.json;到文件系统根仍无 → 抛错提示 init。 */
395
+ function findProjectRoot(io, cwd) {
396
+ let dir = cwd.replace(/\\/g, "/");
397
+ for (;;) {
398
+ if (io.exists(`${dir}/components.json`)) return dir;
399
+ const up = parentDir(dir);
400
+ if (up === null) throw new Error(`未找到 components.json(自 ${cwd} 向上层均未命中)——请先运行 \`tu-design init\``);
401
+ dir = up;
402
+ }
403
+ }
404
+ /** registry target 恒为 POSIX /;纯逻辑层统一 POSIX 路径,真实 fs 由 node IO 兜底(Windows 同样接受 /)。 */
405
+ function resolveTarget(target, config, aliasRoot) {
406
+ return `${aliasRoot.replace(/\\/g, "/").replace(/\/+$/, "")}/${target}`;
407
+ }
408
+ function planWrites(items, io, aliasRoot, config) {
409
+ const plans = [];
410
+ for (const item of items) for (const file of item.files) {
411
+ const path = resolveTarget(file.target, config, aliasRoot);
412
+ plans.push({
413
+ path,
414
+ content: file.content,
415
+ exists: io.exists(path)
416
+ });
417
+ }
418
+ return plans;
419
+ }
420
+ async function writeFiles(plans, io, opts) {
421
+ const written = [];
422
+ for (const plan of plans) {
423
+ if (plan.exists && !opts.overwrite) {
424
+ if (!opts.confirm) continue;
425
+ if (!await opts.confirm(`文件已存在,覆盖?${plan.path}`)) continue;
426
+ }
427
+ io.writeFile(plan.path, plan.content);
428
+ written.push(plan.path);
429
+ }
430
+ return written;
431
+ }
432
+ //#endregion
433
+ //#region src/lib/add-core.ts
434
+ async function resolveTopo(names, fetchOne) {
435
+ const out = [];
436
+ const visited = /* @__PURE__ */ new Set();
437
+ const stack = [];
438
+ async function visit(name) {
439
+ if (visited.has(name)) return;
440
+ if (stack.includes(name)) {
441
+ const cycle = [...stack.slice(stack.indexOf(name)), name].join(" -> ");
442
+ throw new Error(`registryDependencies 存在循环引用:${cycle}`);
443
+ }
444
+ stack.push(name);
445
+ const item = await fetchOne(name);
446
+ for (const dep of item.registryDependencies ?? []) await visit(dep);
447
+ stack.pop();
448
+ visited.add(name);
449
+ out.push(item);
450
+ }
451
+ for (const name of names) await visit(name);
452
+ return out;
453
+ }
454
+ function collectDeps(items) {
455
+ const dependencies = [];
456
+ const devDependencies = [];
457
+ const push = (list, dep) => {
458
+ if (!list.includes(dep)) list.push(dep);
459
+ };
460
+ for (const item of items) {
461
+ for (const dep of item.dependencies ?? []) push(dependencies, dep);
462
+ for (const dep of item.devDependencies ?? []) push(devDependencies, dep);
463
+ }
464
+ return {
465
+ dependencies,
466
+ devDependencies
467
+ };
468
+ }
469
+ const DEFAULT_ALIAS_ROOT = "src";
470
+ async function runAdd(io, cwd, names, opts) {
471
+ const root = findProjectRoot(io, cwd);
472
+ const config = loadConfig(io, root);
473
+ const registryUrl = resolveRegistryUrl(config, opts.registry);
474
+ const aliasRoot = `${root}/${DEFAULT_ALIAS_ROOT}`;
475
+ const npm = opts.npm ?? {
476
+ hasItem: () => false,
477
+ readItem: () => void 0
478
+ };
479
+ const items = await resolveTopo(names, (name) => fetchItem(io, registryUrl, npm, name));
480
+ const files = await writeFiles(planWrites(items, io, aliasRoot, config), io, {
481
+ overwrite: opts.overwrite,
482
+ confirm: opts.confirm
483
+ });
484
+ const { dependencies, devDependencies } = collectDeps(items);
485
+ const pm = detectPackageManagerFromLockfiles(io, root);
486
+ if (dependencies.length > 0) installDependencies(io, root, dependencies, false, pm);
487
+ if (devDependencies.length > 0) installDependencies(io, root, devDependencies, true, pm);
488
+ return {
489
+ files,
490
+ dependencies,
491
+ devDependencies
492
+ };
493
+ }
494
+ //#endregion
495
+ //#region src/lib/version.ts
496
+ /** 从 package.json 原始文本解析版本号(纯函数,便于测试)。 */
497
+ function parsePkgVersion(raw) {
498
+ const parsed = JSON.parse(raw);
499
+ if (typeof parsed.version !== "string" || parsed.version.length === 0) throw new Error("package.json 缺少 version 字段");
500
+ return parsed.version;
501
+ }
502
+ //#endregion
503
+ //#region src/index.ts
504
+ const RUNTIME_DEPS = [
505
+ "clsx",
506
+ "tailwind-merge",
507
+ "class-variance-authority"
508
+ ];
509
+ function makeExecIo(cwd) {
510
+ return {
511
+ ...nodeIo,
512
+ exec(cmd) {
513
+ if (spawnSync(cmd[0], cmd.slice(1), {
514
+ cwd,
515
+ stdio: "inherit"
516
+ }).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
517
+ }
518
+ };
519
+ }
520
+ const program = new Command();
521
+ program.name("tu-design").description("tu-design 组件 registry CLI").version(parsePkgVersion(readFileSync(new URL("../package.json", import.meta.url), "utf8")));
522
+ program.command("init").description("初始化 components.json 并注入基础依赖与样式 tokens").option("--registry <url>", "registry URL 通道", DEFAULT_REGISTRY).option("--css <path>", "全局 CSS 路径(默认自动探测常见位置)").action(async (opts) => {
523
+ const cwd = process.cwd();
524
+ try {
525
+ const summary = runInit(nodeIo, cwd, {
526
+ registry: opts.registry,
527
+ css: opts.css
528
+ });
529
+ console.log(`✔ 已写入 ${summary.configPath}`);
530
+ console.log(`✔ 已注入 cn 工具 ${summary.cnPath}`);
531
+ console.log(summary.skippedCss ? `ℹ ${summary.cssPath} 已包含 tokens,跳过` : `✔ 已合并 tokens 至 ${summary.cssPath}`);
532
+ const pm = detectPackageManager((await detect({ cwd }))?.agent);
533
+ console.log(`ℹ 使用 ${pm} 安装 ${RUNTIME_DEPS.join(" ")}`);
534
+ installDependencies(makeExecIo(cwd), cwd, RUNTIME_DEPS, false, pm);
535
+ console.log("✔ 依赖安装完成");
536
+ } catch (error) {
537
+ console.error(picocolors.red(`✖ ${error instanceof Error ? error.message : String(error)}`));
538
+ process.exitCode = 1;
539
+ }
540
+ });
541
+ program.command("add <components...>").description("添加组件源码到项目").option("--registry <url>", "覆盖 components.json 中的 registry URL").option("--overwrite", "覆盖已存在的文件而不询问").action(async (components, opts) => {
542
+ const cwd = process.cwd();
543
+ try {
544
+ const summary = await runAdd({
545
+ ...nodeIo,
546
+ async fetchJson(url) {
547
+ const res = await fetch(url);
548
+ if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
549
+ return res.json();
550
+ },
551
+ exec(cmd) {
552
+ if (spawnSync(cmd[0], cmd.slice(1), {
553
+ cwd,
554
+ stdio: "inherit"
555
+ }).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
556
+ }
557
+ }, cwd, components, {
558
+ registry: opts.registry,
559
+ overwrite: opts.overwrite,
560
+ npm: nodeNpmChannel,
561
+ confirm: async (msg) => {
562
+ if (!process.stdin.isTTY) return false;
563
+ const { default: prompts } = await import("prompts");
564
+ return (await prompts({
565
+ type: "confirm",
566
+ name: "ok",
567
+ message: msg,
568
+ initial: false
569
+ })).ok === true;
570
+ }
571
+ });
572
+ if (summary.files.length > 0) {
573
+ console.log("✔ 写入文件:");
574
+ for (const f of summary.files) console.log(` ${f}`);
575
+ } else console.log("ℹ 没有写入任何文件(可能全部跳过)");
576
+ for (const d of summary.dependencies) console.log(`✔ 依赖 ${picocolors.cyan(d)}`);
577
+ for (const d of summary.devDependencies) console.log(`✔ 开发依赖 ${picocolors.cyan(d)}`);
578
+ } catch (error) {
579
+ console.error(picocolors.red(`✖ ${error instanceof Error ? error.message : String(error)}`));
580
+ process.exitCode = 1;
581
+ }
582
+ });
583
+ program.parse();
584
+ //#endregion
585
+ export {};
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@tu-design/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.1",
4
+ "description": "tu-design CLI:初始化并按 registry 分发组件源码到用户项目(shadcn 模式)。",
5
+ "keywords": [
6
+ "cli",
7
+ "registry",
8
+ "scaffold",
9
+ "shadcn",
10
+ "vue"
11
+ ],
12
+ "homepage": "https://github.com/gopowerteam/tu-design#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/gopowerteam/tu-design/issues"
15
+ },
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/gopowerteam/tu-design.git"
20
+ },
21
+ "bin": {
22
+ "tu-design": "./dist/index.mjs"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "type": "module",
28
+ "exports": {
29
+ ".": "./dist/index.mjs",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@tu-design/vue": "0.2.1",
37
+ "commander": "^15",
38
+ "package-manager-detector": "^1",
39
+ "picocolors": "^1",
40
+ "prompts": "^2"
41
+ },
42
+ "devDependencies": {
43
+ "@types/prompts": "^2.4.8",
44
+ "tsx": "^4.0.0",
45
+ "typescript": "^5.9",
46
+ "vite-plus": "1.0.0",
47
+ "vitest": "^5.0.1"
48
+ },
49
+ "scripts": {
50
+ "build": "vp pack && tsx scripts/fix-bin.ts",
51
+ "typecheck": "tsc --noEmit",
52
+ "test": "vp test --run"
53
+ }
6
54
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.