@tu-design/cli 0.3.0 → 0.4.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.
Files changed (3) hide show
  1. package/README.md +49 -0
  2. package/dist/index.mjs +115 -38
  3. package/package.json +4 -4
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @tu-design/cli
2
+
3
+ `tu-design` —— [tu-design](../vue) 组件库的 registry 分发 CLI(shadcn 模式):初始化项目配置,并把组件源码从 registry 拉取写入你的项目。
4
+
5
+ ## 使用
6
+
7
+ ```bash
8
+ npx @tu-design/cli init
9
+ npx @tu-design/cli add button
10
+ ```
11
+
12
+ ### `init`
13
+
14
+ 初始化 `components.json`,并自动完成基础接入:
15
+
16
+ - 写入 `components.json`(registry URL、别名等配置)
17
+ - 注入 `cn` 工具到 `src/lib/utils.ts`
18
+ - 将主题 tokens 合并进全局 CSS(自动探测常见位置,可用 `--css` 指定;已包含则跳过)
19
+ - 探测包管理器并安装运行时依赖(`clsx` / `tailwind-merge` / `class-variance-authority`)
20
+
21
+ | 选项 | 说明 |
22
+ | ------------------ | ----------------------------------- |
23
+ | `--registry <url>` | registry URL,默认线上 Pages 数据源 |
24
+ | `--css <path>` | 全局 CSS 路径 |
25
+
26
+ ### `add <components...>`
27
+
28
+ 按名字添加组件源码(支持一次多个),文件写入 `components.json` 声明的位置:
29
+
30
+ | 选项 | 说明 |
31
+ | ------------------ | ---------------------------------------- |
32
+ | `--registry <url>` | 覆盖 `components.json` 中的 registry URL |
33
+ | `--overwrite` | 覆盖已存在的文件而不询问 |
34
+
35
+ ## 工作机制
36
+
37
+ CLI 从 registry 服务拉取每个组件的 **registry JSON**(遵循 [shadcn registry-item schema](https://ui.shadcn.com/schema/registry-item.json)),JSON 中内联了文件内容与写入目标,并声明:
38
+
39
+ - `registryDependencies` —— 依赖的基础项(如 `utils`、`tokens`),CLI 会先行安装
40
+ - `dependencies` —— 需要的 npm 依赖(如 Ark UI、TanStack 包),CLI 检测到后用当前包管理器安装
41
+
42
+ 默认 registry 数据源是文档站 Pages 上发布的 `https://gopowerteam.github.io/tu-design/r/vue`,由 [`@tu-design/vue` 的 `generate:registry`](../vue) 生成并随 Pages 部署更新,可用 `--registry` 指向自建服务。
43
+
44
+ ## 相关
45
+
46
+ - 组件库:[@tu-design/vue](../vue)
47
+ - 文档站:<https://gopowerteam.github.io/tu-design/>(含 CLI 指南)
48
+ - 仓库:<https://github.com/gopowerteam/tu-design>
49
+ - 许可:MIT
package/dist/index.mjs CHANGED
@@ -4,7 +4,6 @@ import { spawnSync } from "node:child_process";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
5
5
  import { Command } from "commander";
6
6
  import picocolors from "picocolors";
7
- import { detect } from "package-manager-detector";
8
7
  import { dirname, join } from "node:path";
9
8
  //#region src/io/node.ts
10
9
  const nodeIo = {
@@ -30,6 +29,20 @@ function npmItemPath(name) {
30
29
  return join(dirname(pkgJson), "dist/registry/vue", `${name}.json`);
31
30
  }
32
31
  //#endregion
32
+ //#region src/lib/json.ts
33
+ /**
34
+ * 统一 JSON 解析报错:裸 SyntaxError 不含文件名,用户无从下手;这里补上来源。
35
+ * label 用面向用户的文件名(如 `components.json`),而不是绝对路径。
36
+ */
37
+ function parseJson(text, label) {
38
+ try {
39
+ return JSON.parse(text);
40
+ } catch (error) {
41
+ const reason = error instanceof Error ? error.message : String(error);
42
+ throw new Error(`${label} 不是合法 JSON:${reason}`);
43
+ }
44
+ }
45
+ //#endregion
33
46
  //#region src/lib/config.ts
34
47
  /** init 未显式传 --registry 时写入 components.json 的默认 URL 通道(不可达时 add 走 npm 兜底)。 */
35
48
  const DEFAULT_REGISTRY = "https://gopowerteam.github.io/tu-design/r/vue";
@@ -75,7 +88,7 @@ function configPath(cwd) {
75
88
  function loadConfig(io, cwd) {
76
89
  const path = configPath(cwd);
77
90
  if (!io.exists(path)) throw new Error(`未找到 ${CONFIG_FILE},请先运行 \`tu-design init\``);
78
- return validateConfig(JSON.parse(io.readFile(path)));
91
+ return validateConfig(parseJson(io.readFile(path), CONFIG_FILE));
79
92
  }
80
93
  function saveConfig(io, cwd, config) {
81
94
  io.writeFile(configPath(cwd), `${JSON.stringify(config, null, 2)}\n`);
@@ -159,6 +172,16 @@ function applyAliases(io, cwd, aliasRoot) {
159
172
  //#endregion
160
173
  //#region src/lib/init-core.ts
161
174
  /**
175
+ * init 注入的源码(TOKENS_CSS_SOURCE / CN_UTIL_SOURCE)里出现的裸包说明符,
176
+ * 必须全部在此声明,否则 init 出来的项目首屏构建即失败(init-core.test.ts 强制校验)。
177
+ */
178
+ const RUNTIME_DEPS = [
179
+ "clsx",
180
+ "tailwind-merge",
181
+ "class-variance-authority",
182
+ "tw-animate-css"
183
+ ];
184
+ /**
162
185
  * 与 @tu-design/vue/src/styles/tokens.css 保持一致(init-core.test.ts 有防漂移守卫)。
163
186
  * 来源:packages/vue/src/styles/tokens.css
164
187
  */
@@ -192,6 +215,10 @@ const TOKENS_CSS_SOURCE = `@import "tw-animate-css";
192
215
  --input: oklch(0.922 0 0);
193
216
  --ring: oklch(0.708 0 0);
194
217
  --radius: 0.625rem;
218
+ /* 层叠序:表体 sticky < 表头 sticky < 浮层/弹窗(同级浮层按 DOM 挂载次序叠放) */
219
+ --z-sticky: 10;
220
+ --z-sticky-head: 20;
221
+ --z-overlay: 50;
195
222
  }
196
223
 
197
224
  .dark {
@@ -307,9 +334,11 @@ function runInit(io, cwd, opts) {
307
334
  const cssRel = probeCssPath(io, cwd, opts.css ?? config.tailwind.css);
308
335
  const cssPath = joinPosix(cwd, cssRel);
309
336
  const globalCss = io.exists(cssPath) ? io.readFile(cssPath) : "";
310
- if (!detectTailwindV4(JSON.parse(io.readFile(joinPosix(cwd, "package.json"))), globalCss)) throw new Error("未检测到 Tailwind CSS v4:需要 package.json 中的 tailwindcss ^4 依赖,以及全局 CSS 中的 @import \"tailwindcss\";");
337
+ const pkgPath = joinPosix(cwd, "package.json");
338
+ if (!io.exists(pkgPath)) throw new Error(`未找到 ${pkgPath},请在 npm 项目根目录运行 \`tu-design init\``);
339
+ if (!detectTailwindV4(parseJson(io.readFile(pkgPath), "package.json"), globalCss)) throw new Error("未检测到 Tailwind CSS v4:需要 package.json 中的 tailwindcss ^4 依赖,以及全局 CSS 中的 @import \"tailwindcss\";");
311
340
  const configPath = joinPosix(cwd, "components.json");
312
- if (io.exists(configPath)) validateConfig(JSON.parse(io.readFile(configPath)));
341
+ if (io.exists(configPath)) validateConfig(parseJson(io.readFile(configPath), "components.json"));
313
342
  else saveConfig(io, cwd, {
314
343
  ...config,
315
344
  tailwind: { css: cssRel }
@@ -334,11 +363,15 @@ const ITEM_TYPES = [
334
363
  "registry:lib",
335
364
  "registry:style"
336
365
  ];
337
- /** override(--registry)优先于 components.json。 */
366
+ /**
367
+ * override(--registry)优先于 components.json。
368
+ * 去掉尾部 `/`:拼接处是 `${url}/${name}.json`,用户从浏览器地址栏复制带斜杠的 URL
369
+ * 会拼出 `//button.json`,不少静态托管据此 404。
370
+ */
338
371
  function resolveRegistryUrl(config, override) {
339
- return override ?? config.registry;
372
+ return (override ?? config.registry).replace(/\/+$/, "");
340
373
  }
341
- /** registry item 最小结构校验(name/type/files)。 */
374
+ /** registry item 最小结构校验(name/type/files),files 逐文件校验形态。 */
342
375
  function validateRegistryItem(raw) {
343
376
  if (typeof raw !== "object" || raw === null) throw new Error("registry item 不是 JSON 对象");
344
377
  const obj = raw;
@@ -347,18 +380,28 @@ function validateRegistryItem(raw) {
347
380
  if (typeof obj.type !== "string" || !ITEM_TYPES.includes(obj.type)) missing.push("type");
348
381
  if (!Array.isArray(obj.files)) missing.push("files");
349
382
  if (missing.length > 0) throw new Error(`registry item 缺少字段:${missing.join("、")}`);
383
+ const badFile = obj.files.findIndex((f) => typeof f !== "object" || f === null || typeof f.path !== "string" || typeof f.target !== "string" || typeof f.content !== "string");
384
+ if (badFile !== -1) throw new Error(`registry item ${String(obj.name)} 的 files[${badFile}] 缺少 path/target/content 字符串字段`);
350
385
  return raw;
351
386
  }
387
+ function reasonOf(error) {
388
+ return error instanceof Error ? error.message : String(error);
389
+ }
352
390
  /**
353
391
  * 双通道解析:URL 优先(fetch `${registryUrl}/${name}.json`),
354
- * 失败 / 404 / 校验不过时回退 npm 通道;双失败抛错含组件名。
392
+ * 失败 / 404 / 校验不过时回退 npm 通道;双失败抛错含组件名与 URL 通道的真实原因
393
+ * (吞掉原因会让用户去查 npm,问题其实出在 registry 网络或 JSON 损坏)。
355
394
  */
356
395
  async function fetchItem(fetcher, registryUrl, npm, name) {
396
+ const url = `${registryUrl}/${name}.json`;
397
+ let urlFailure;
357
398
  try {
358
- return validateRegistryItem(await fetcher.fetchJson(`${registryUrl}/${name}.json`));
359
- } catch {}
399
+ return validateRegistryItem(await fetcher.fetchJson(url));
400
+ } catch (error) {
401
+ urlFailure = reasonOf(error);
402
+ }
360
403
  if (npm.hasItem(name)) return validateRegistryItem(npm.readItem(name));
361
- throw new Error(`无法获取组件 ${name}:URL 通道与 npm 通道(@tu-design/vue)均不可用`);
404
+ throw new Error(`无法获取组件 ${name}:URL 通道 ${url} 失败(${urlFailure}),npm 通道(@tu-design/vue)亦不可用`);
362
405
  }
363
406
  //#endregion
364
407
  //#region src/lib/pm.ts
@@ -368,19 +411,33 @@ const PM_NAMES = [
368
411
  "yarn",
369
412
  "bun"
370
413
  ];
371
- /** agent 形如 "pnpm@9.15.0";未知识别为 npm。 */
372
- function detectPackageManager(agent) {
373
- if (!agent) return "npm";
414
+ /** agent 形如 "pnpm@9.15.0";未知/缺失返回 null,由调用方决定降级方式。 */
415
+ function parsePackageManager(agent) {
416
+ if (!agent) return null;
374
417
  const name = agent.split("@")[0] ?? agent;
375
- return PM_NAMES.includes(name) ? name : "npm";
418
+ return PM_NAMES.includes(name) ? name : null;
376
419
  }
377
- /** 由 cwd 锁文件推断包管理器(package-manager-detector 的纯 IO 兜底路径)。 */
420
+ /** 由 cwd 锁文件推断包管理器(纯 IO 路径,可在 memIo 下测试)。 */
378
421
  function detectPackageManagerFromLockfiles(io, cwd) {
379
422
  if (io.exists(`${cwd}/pnpm-lock.yaml`)) return "pnpm";
380
423
  if (io.exists(`${cwd}/yarn.lock`)) return "yarn";
381
424
  if (io.exists(`${cwd}/bun.lockb`) || io.exists(`${cwd}/bun.lock`)) return "bun";
382
425
  return "npm";
383
426
  }
427
+ /**
428
+ * 项目包管理器的唯一判定口径(init 与 add 共用,避免两条命令对同一项目给出不同答案):
429
+ * `packageManager` 字段(Corepack 声明的意图)优先,其次锁文件(实际使用证据),最后 npm。
430
+ * package.json 缺失或不可解析时静默降级——报错是 init 自己的前置校验职责。
431
+ */
432
+ function detectPackageManagerForProject(io, cwd) {
433
+ const pkgPath = `${cwd}/package.json`;
434
+ if (io.exists(pkgPath)) try {
435
+ const raw = parseJson(io.readFile(pkgPath), "package.json");
436
+ const declared = parsePackageManager(typeof raw.packageManager === "string" ? raw.packageManager : void 0);
437
+ if (declared) return declared;
438
+ } catch {}
439
+ return detectPackageManagerFromLockfiles(io, cwd);
440
+ }
384
441
  function buildInstallCommand(pm, deps, dev) {
385
442
  const base = {
386
443
  pnpm: ["pnpm", "add"],
@@ -418,14 +475,40 @@ function findProjectRoot(io, cwd) {
418
475
  dir = up;
419
476
  }
420
477
  }
421
- /** registry target 恒为 POSIX /;纯逻辑层统一 POSIX 路径,真实 fs 由 node IO 兜底(Windows 同样接受 /)。 */
478
+ /**
479
+ * registry target 恒为 POSIX /;纯逻辑层统一 POSIX 路径,真实 fs 由 node IO 兜底(Windows 同样接受 /)。
480
+ *
481
+ * target 来自远端 JSON(registry 可被任意第三方托管),必须钳在 aliasRoot 内:
482
+ * 绝对路径、盘符路径、或逸出 aliasRoot 的 `..` 一律拒绝,否则一个恶意/损坏的
483
+ * registry 项能把源码写到项目外(`~/.bashrc`、`/etc/…`)。
484
+ * 逐段归一后仍留在 aliasRoot 内的 `..`(如 `components/ui/../../x.ts`)允许。
485
+ */
422
486
  function resolveTarget(target, config, aliasRoot) {
423
- return `${aliasRoot.replace(/\\/g, "/").replace(/\/+$/, "")}/${target}`;
487
+ const root = aliasRoot.replace(/\\/g, "/").replace(/\/+$/, "");
488
+ const unix = target.replace(/\\/g, "/");
489
+ if (unix.startsWith("/") || /^[A-Za-z]:\//.test(unix)) throw new Error(`registry target 必须是相对路径,得到 ${target}`);
490
+ const segs = [];
491
+ for (const part of unix.split("/")) {
492
+ if (part === "" || part === ".") continue;
493
+ if (part === "..") {
494
+ if (segs.length === 0) throw new Error(`registry target 越出项目目录:${target}`);
495
+ segs.pop();
496
+ continue;
497
+ }
498
+ segs.push(part);
499
+ }
500
+ if (segs.length === 0) throw new Error(`registry target 解析后为空:${target}`);
501
+ return `${root}/${segs.join("/")}`;
424
502
  }
425
503
  function planWrites(items, io, aliasRoot, config) {
426
504
  const plans = [];
427
505
  for (const item of items) for (const file of item.files) {
428
- const path = resolveTarget(file.target, config, aliasRoot);
506
+ let path;
507
+ try {
508
+ path = resolveTarget(file.target, config, aliasRoot);
509
+ } catch (error) {
510
+ throw new Error(`项 ${item.name} 的文件 ${file.path}:${error instanceof Error ? error.message : String(error)}`);
511
+ }
429
512
  plans.push({
430
513
  path,
431
514
  content: file.content,
@@ -499,7 +582,7 @@ async function runAdd(io, cwd, names, opts) {
499
582
  confirm: opts.confirm
500
583
  });
501
584
  const { dependencies, devDependencies } = collectDeps(items);
502
- const pm = detectPackageManagerFromLockfiles(io, root);
585
+ const pm = detectPackageManagerForProject(io, root);
503
586
  if (dependencies.length > 0) installDependencies(io, root, dependencies, false, pm);
504
587
  if (devDependencies.length > 0) installDependencies(io, root, devDependencies, true, pm);
505
588
  return {
@@ -518,20 +601,19 @@ function parsePkgVersion(raw) {
518
601
  }
519
602
  //#endregion
520
603
  //#region src/index.ts
521
- const RUNTIME_DEPS = [
522
- "clsx",
523
- "tailwind-merge",
524
- "class-variance-authority"
525
- ];
604
+ /** 唯一的子进程执行实现:init / add 都走它,失败原因由 stdio 直接透传给用户。 */
605
+ function execIn(cwd) {
606
+ return (cmd) => {
607
+ if (spawnSync(cmd[0], cmd.slice(1), {
608
+ cwd,
609
+ stdio: "inherit"
610
+ }).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
611
+ };
612
+ }
526
613
  function makeExecIo(cwd) {
527
614
  return {
528
615
  ...nodeIo,
529
- exec(cmd) {
530
- if (spawnSync(cmd[0], cmd.slice(1), {
531
- cwd,
532
- stdio: "inherit"
533
- }).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
534
- }
616
+ exec: execIn(cwd)
535
617
  };
536
618
  }
537
619
  const program = new Command();
@@ -546,7 +628,7 @@ program.command("init").description("初始化 components.json 并注入基础
546
628
  console.log(`✔ 已写入 ${summary.configPath}`);
547
629
  console.log(`✔ 已注入 cn 工具 ${summary.cnPath}`);
548
630
  console.log(summary.skippedCss ? `ℹ ${summary.cssPath} 已包含 tokens,跳过` : `✔ 已合并 tokens 至 ${summary.cssPath}`);
549
- const pm = detectPackageManager((await detect({ cwd }))?.agent);
631
+ const pm = detectPackageManagerForProject(nodeIo, cwd);
550
632
  console.log(`ℹ 使用 ${pm} 安装 ${RUNTIME_DEPS.join(" ")}`);
551
633
  installDependencies(makeExecIo(cwd), cwd, RUNTIME_DEPS, false, pm);
552
634
  console.log("✔ 依赖安装完成");
@@ -565,12 +647,7 @@ program.command("add <components...>").description("添加组件源码到项目"
565
647
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
566
648
  return res.json();
567
649
  },
568
- exec(cmd) {
569
- if (spawnSync(cmd[0], cmd.slice(1), {
570
- cwd,
571
- stdio: "inherit"
572
- }).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
573
- }
650
+ exec: execIn(cwd)
574
651
  }, cwd, components, {
575
652
  registry: opts.registry,
576
653
  overwrite: opts.overwrite,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tu-design/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "tu-design CLI:初始化并按 registry 分发组件源码到用户项目(shadcn 模式)。",
5
5
  "keywords": [
6
6
  "cli",
@@ -22,7 +22,8 @@
22
22
  "tu-design": "./dist/index.mjs"
23
23
  },
24
24
  "files": [
25
- "dist"
25
+ "dist",
26
+ "README.md"
26
27
  ],
27
28
  "type": "module",
28
29
  "exports": {
@@ -33,9 +34,8 @@
33
34
  "access": "public"
34
35
  },
35
36
  "dependencies": {
36
- "@tu-design/vue": "0.3.0",
37
+ "@tu-design/vue": "0.4.1",
37
38
  "commander": "^15",
38
- "package-manager-detector": "^1",
39
39
  "picocolors": "^1",
40
40
  "prompts": "^2"
41
41
  },