ztheme-cli 0.0.8 → 0.0.9

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 CHANGED
@@ -4,7 +4,7 @@
4
4
  > CLI 是本仓原创代码,与 upstream tweakcn 无关。
5
5
 
6
6
  不依赖 shadcn 的主题 CLI。只走 HTTP,不需要 shadcn CLI、不需要 MCP、不需要登录。
7
- 当前版本 **0.0.8**(`npm i -g ztheme-cli` 或 `npx ztheme-cli@0.0.8` 都行,下文统一写 `ztheme`)。
7
+ 当前版本 **0.0.9**(`npm i -g ztheme-cli` 或 `npx ztheme-cli@0.0.9` 都行,下文统一写 `ztheme`)。
8
8
 
9
9
  ## 前提:告诉它站点在哪
10
10
 
@@ -88,7 +88,7 @@ ztheme init modern-minimal --dir . # 显式指定项目根
88
88
  |---|---|
89
89
  | `ztheme/<slug>.css` | `:root` + `.dark` 两段 CSS 变量 |
90
90
  | `AGENTS.md` | 一个幂等标记块:令牌表 + 可判定断言 + 禁用组合 + **改完必须跑的那条命令** |
91
- | `.ztheme/theme-lock.json` | slug + 主题 digest + 阈值 + 断言 + 锁定时刻的判定结果 |
91
+ | `.ztheme/theme-lock.json` | slug + 主题 digest + 令牌快照 + 阈值 + 断言 + 锁定时刻的判定结果(与验证结论) |
92
92
 
93
93
  `AGENTS.md` 里写的是**相对项目根**的路径(`ztheme/<slug>.css`),可以直接提交进仓库。
94
94
  (0.0.4 曾把本机绝对路径写进去,换台机器就跑不了;0.0.5 修了,并有测试守着。)
@@ -103,10 +103,33 @@ ztheme check --lock --file ztheme/modern-minimal.css --strict
103
103
  报两类漂移:① 本地 CSS 比锁定版本变差;② 站点上那套主题的 digest 变了。
104
104
  正常时输出「无漂移:主题与锁定版本一致」;`--strict` 下有漂移即 exit 1。
105
105
 
106
+ 只想知道「上游改了什么、会不会把对比度弄坏」时,用 `upgrade --check`:
107
+
108
+ ```bash
109
+ ztheme upgrade --check # 读 .ztheme/theme-lock.json
110
+ ztheme upgrade --check --strict # 有漂移即 exit 1(CI 用)
111
+ ```
112
+
113
+ 它逐项列出 light / dark 的令牌增删改,并按**锁定时的断言**重判站点当前版本,
114
+ 报告新增问题、已修复、新增无法判定的数量。旧锁文件没有令牌快照时只报 digest 漂移,
115
+ 提示重跑 `init` 升级锁格式;不会拿 digest 反推内容,也不自动改写任何文件。
116
+
117
+ 确认要跟之后,用 `upgrade --pr` 生成本地分支:
118
+
119
+ ```bash
120
+ ztheme upgrade --pr # 默认 dry-run:只打印计划
121
+ ztheme upgrade --pr --write # 建分支 ztheme/upgrade-<slug>、重写 ztheme/<slug>.css、更新锁并提交
122
+ ```
123
+
124
+ 要求工作区干净(脏了会让「这次升级改了什么」混进无关改动),不会 push、不会合入;
125
+ 下一步由你 `git push -u origin <branch>` 后开 PR 人审。生成文件头写着「勿手改」,
126
+ 所以升级会整份重写;如果本地 CSS 与锁定令牌不一致(可能手改过),默认拒绝,
127
+ 确认要覆盖时加 `--force`。
128
+
106
129
  ## 7. CI 里最小接入
107
130
 
108
131
  ```yaml
109
- - run: npx ztheme-cli@0.0.8 check --file app/globals.css --rules 你的主题 --strict
132
+ - run: npx ztheme-cli@0.0.9 check --file app/globals.css --rules 你的主题 --strict
110
133
  env:
111
134
  ZTHEME_BASE: https://你的生产站点
112
135
  ```
@@ -238,12 +261,14 @@ workflow 按 `<!-- ztheme-audit -->` 更新同一条评论,不刷屏;完整
238
261
  | `check --file <path> --rules <slug>` | 同时校验该主题的规则断言 |
239
262
  | `init <slug> [--dir .]` | 生成 CSS + `AGENTS.md` 片段 + 主题锁 |
240
263
  | `check --lock [--file <css>]` | 与锁文件比对,报漂移 |
264
+ | `upgrade --check [--lock <json>] [--strict]` | 与锁文件比对站点当前主题:令牌 diff + 对比度影响 |
265
+ | `upgrade --pr [--write]` | 生成本地升级分支:重写主题 CSS、更新锁并提交(默认 dry-run) |
241
266
  | `audit [path] [--json] [--theme <slug>] [--max-warnings n]` | 扫组件源码里的硬编码颜色与任意值 |
242
267
  | `audit [path] --fix [--write]` | 打印可审阅的 patch;`--write` 才落盘 |
243
268
  | `--help` | 打印用法 |
244
269
 
245
270
  退出码:`0` 通过;`1` `--strict` 下出现「建议修」或「无法判定」,或有漂移,或 audit 有
246
- error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
271
+ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误,或 upgrade 的参数 / 锁文件错误。
247
272
 
248
273
  ## 为什么这么小
249
274
 
@@ -255,6 +280,17 @@ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
255
280
 
256
281
  ## 变更记录
257
282
 
283
+ ### 0.0.9
284
+
285
+ - 新增 `upgrade --check`:与锁文件比对站点当前主题,逐项列出 light / dark 令牌增删改,
286
+ 并按锁定时的断言重判对比度影响(新增问题 / 修复 / 新增无法判定分开报);`--strict` 判失败。
287
+ - 新增 `upgrade --pr`:默认 dry-run;`--write` 时要求工作区干净,建分支
288
+ `ztheme/upgrade-<slug>`、重写生成的 CSS、更新锁并提交,不 push、不自动合入。
289
+ 本地 CSS 与锁定令牌不一致时拒绝覆盖,`--force` 才继续。
290
+ - 锁文件增加 `tokens` 令牌快照;站点返回验证结论时记录 `verifiedOk` 与 `verifiedAt`。
291
+ 旧锁文件仍可读,只是没有令牌快照时无法逐项 diff。
292
+ - 新增 `cli/upgrade.mjs`(纯函数:`diffTokens` / `summarizeChanges` / `contrastImpact` / `localDrift`)。
293
+
258
294
  ### 0.0.8
259
295
 
260
296
  - 新增 `audit --fix`:把建议落成可审阅的逐行 patch,**默认不写盘**,`--write` 才落盘。
@@ -302,6 +338,7 @@ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
302
338
 
303
339
  ## 尚未做
304
340
 
341
+ - 锁文件 `schemaVersion`:目前靠字段存在与否兼容旧格式。
305
342
  - Tailwind v4 的 `@theme inline` 映射片段(当前给的是 `:root` / `.dark` 变量,
306
343
  v4 项目照 `docs/presets/README` 的 `@theme inline` 写法接一下即可)
307
344
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ztheme-cli",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "description": "Ztheme 主题 CLI:从站点拉取主题 CSS 变量,并在仓库里扫设计漂移",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,7 @@
12
12
  "color.mjs",
13
13
  "rules.mjs",
14
14
  "fix.mjs",
15
+ "upgrade.mjs",
15
16
  "README.md",
16
17
  "LICENSE"
17
18
  ],
package/upgrade.mjs ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 主题锁升级的纯函数部分(批次 D)。
3
+ *
4
+ * 只做「比较」:把锁定时的令牌快照与站点当前令牌逐项对比,再把两次对比度
5
+ * 判定的结果差分。不做网络、不读文件——CLI 负责取数,这里负责给出可复核的事实。
6
+ */
7
+
8
+ /**
9
+ * 逐项比较 { light, dark } 两份令牌表。
10
+ * 返回按 (mode, token) 稳定排序的增删改;值相同的不出现。
11
+ */
12
+ export function diffTokens(before, after) {
13
+ const changes = [];
14
+ for (const mode of ["light", "dark"]) {
15
+ const a = before?.[mode] ?? {};
16
+ const b = after?.[mode] ?? {};
17
+ const tokens = new Set([...Object.keys(a), ...Object.keys(b)]);
18
+ for (const token of [...tokens].sort()) {
19
+ const had = Object.prototype.hasOwnProperty.call(a, token);
20
+ const has = Object.prototype.hasOwnProperty.call(b, token);
21
+ if (had && has && a[token] === b[token]) continue;
22
+ if (!had) {
23
+ changes.push({ mode, token, kind: "added", before: null, after: b[token] });
24
+ } else if (!has) {
25
+ changes.push({ mode, token, kind: "removed", before: a[token], after: null });
26
+ } else {
27
+ changes.push({ mode, token, kind: "changed", before: a[token], after: b[token] });
28
+ }
29
+ }
30
+ }
31
+ return changes;
32
+ }
33
+
34
+ export function summarizeChanges(changes) {
35
+ const count = (kind) => changes.filter((change) => change.kind === kind).length;
36
+ return {
37
+ added: count("added"),
38
+ removed: count("removed"),
39
+ changed: count("changed"),
40
+ total: changes.length,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * 本地 CSS 与锁定令牌的差异(手改检测)。
46
+ *
47
+ * 生成文件头写着「勿手改」,但人总会改。升级前先比对本地当前值与锁定快照,
48
+ * 有差异就要求显式 --force,避免把本地调整一口吞掉。
49
+ */
50
+ export function localDrift(localVars, lockedTokens) {
51
+ const drift = [];
52
+ for (const mode of ["light", "dark"]) {
53
+ const local = localVars?.[mode] ?? {};
54
+ const locked = lockedTokens?.[mode] ?? {};
55
+ const tokens = new Set([...Object.keys(local), ...Object.keys(locked)]);
56
+ for (const token of [...tokens].sort()) {
57
+ if (local[token] === locked[token]) continue;
58
+ drift.push({
59
+ mode,
60
+ token,
61
+ local: local[token] ?? null,
62
+ locked: locked[token] ?? null,
63
+ });
64
+ }
65
+ }
66
+ return drift;
67
+ }
68
+
69
+ const listOf = (value) => (Array.isArray(value) ? value : []);
70
+
71
+ /** 对比度判定的差分:新出现的问题与已修复的问题分开列,不许混成净变化数。 */
72
+ export function contrastImpact(before = {}, after = {}) {
73
+ const added = (key) => listOf(after[key]).filter((item) => !listOf(before[key]).includes(item));
74
+ const resolved = (key) =>
75
+ listOf(before[key]).filter((item) => !listOf(after[key]).includes(item));
76
+ return {
77
+ newFails: added("fails"),
78
+ resolvedFails: resolved("fails"),
79
+ newWarns: added("warns"),
80
+ resolvedWarns: resolved("warns"),
81
+ newUnknown: added("unknown"),
82
+ resolvedUnknown: resolved("unknown"),
83
+ };
84
+ }
package/ztheme.mjs CHANGED
@@ -15,12 +15,14 @@
15
15
  * 默认站点取 ZTHEME_BASE 环境变量,否则 http://localhost:3001。
16
16
  */
17
17
  import { createHash } from "node:crypto";
18
+ import { execFileSync } from "node:child_process";
18
19
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
19
20
  import { join, resolve } from "node:path";
20
21
 
21
22
  import { auditProject, formatHuman, formatJson } from "./audit.mjs";
22
23
  import { applyFixes, diffLines } from "./fix.mjs";
23
24
  import { validateRules } from "./rules.mjs";
25
+ import { contrastImpact, diffTokens, localDrift, summarizeChanges } from "./upgrade.mjs";
24
26
 
25
27
  const BASE = (process.env.ZTHEME_BASE ?? "http://localhost:3001").replace(/\/$/, "");
26
28
 
@@ -452,6 +454,10 @@ const main = async () => {
452
454
  ztheme init <slug> [--dir .] 生成 ztheme/<slug>.css + AGENTS.md 片段 + .ztheme/theme-lock.json
453
455
  ztheme check --lock [--file x.css]
454
456
  与锁文件比对:本地 CSS 变差、或站点主题已更新时报警(--strict 判失败)
457
+ ztheme upgrade --check [--lock x.json] [--strict]
458
+ 与锁文件比对站点当前主题:列出令牌增删改与对比度影响(--strict 判失败)
459
+ ztheme upgrade --pr [--write] [--force]
460
+ 按站点当前版本生成本地升级分支(默认 dry-run;不 push、不合入)
455
461
  ztheme audit [path] [--json] [--theme <slug>] [--max-warnings <n>] [--quiet]
456
462
  ztheme audit [path] --fix [--write] 打印可审阅的 patch;--write 才落盘
457
463
  扫描 TSX/JSX/TS/JS 里的硬编码颜色与任意值;
@@ -607,6 +613,11 @@ const main = async () => {
607
613
  base: BASE,
608
614
  lockedAt: new Date().toISOString(),
609
615
  themeDigest: digestOf(item.cssVars),
616
+ // 批次 D:锁住令牌快照,upgrade --check 才能逐项 diff;站点返回验证结论时一并记录
617
+ tokens: { light: lightVars, dark: darkVars },
618
+ ...(rulesRes.verified
619
+ ? { verifiedOk: !!rulesRes.verified.ok, verifiedAt: new Date().toISOString() }
620
+ : {}),
610
621
  boundary: checks.boundary ?? 2.6,
611
622
  pairs: checks.pairs,
612
623
  assertions,
@@ -628,6 +639,169 @@ const main = async () => {
628
639
  return;
629
640
  }
630
641
 
642
+ if (cmd === "upgrade") {
643
+ const doCheck = flags.has("check");
644
+ const doPr = flags.has("pr");
645
+ if (!doCheck && !doPr) failWith("用法:ztheme upgrade --check 或 upgrade --pr [--write]", 2);
646
+ if (doCheck && doPr) failWith("--check 与 --pr 只能选一个", 2);
647
+
648
+ const lockPath = valueOf("lock") ?? LOCK_FILE;
649
+ if (!existsSync(lockPath)) {
650
+ failWith("找不到锁文件:" + lockPath + "(先跑 ztheme init <slug>)", 2);
651
+ }
652
+
653
+ let lock;
654
+ try {
655
+ lock = JSON.parse(readFileSync(lockPath, "utf8"));
656
+ } catch (error) {
657
+ failWith("无法解析锁文件 " + lockPath + ":" + (error?.message ?? error), 2);
658
+ }
659
+ if (!lock?.slug) failWith("锁文件缺少 slug:" + lockPath, 2);
660
+
661
+ const site = await getJson("/r/themes/" + lock.slug);
662
+ const siteVars = site.cssVars ?? {};
663
+ const siteDigest = digestOf(siteVars);
664
+
665
+ if (siteDigest === lock.themeDigest) {
666
+ console.log(
667
+ doPr
668
+ ? `无漂移,不需要升级:站点上的 ${lock.slug} 与锁定版本一致(digest ${siteDigest})`
669
+ : `无漂移:站点上的 ${lock.slug} 与锁定版本一致(digest ${siteDigest})`
670
+ );
671
+ return;
672
+ }
673
+
674
+ console.log(
675
+ `漂移:站点上的 ${lock.slug} 已更新(锁定 ${lock.themeDigest},当前 ${siteDigest})`
676
+ );
677
+
678
+ let now = null;
679
+ if (!lock.tokens) {
680
+ // 旧锁文件只存 digest,逐项 diff 需要令牌快照;不拿 digest 反推,也不假装能比
681
+ console.log(
682
+ ` 锁文件里没有令牌快照(旧格式),无法逐项列出改动;重跑 ztheme init ${lock.slug} 可升级锁格式。`
683
+ );
684
+ if (doPr) {
685
+ failWith("没有令牌快照就无法生成升级分支;先重跑 ztheme init " + lock.slug, 2);
686
+ }
687
+ } else {
688
+ const variables = { light: siteVars.light ?? {}, dark: siteVars.dark ?? {} };
689
+ const changes = diffTokens(lock.tokens, variables);
690
+ const summary = summarizeChanges(changes);
691
+ console.log(
692
+ ` 令牌变化:新增 ${summary.added} / 删除 ${summary.removed} / 修改 ${summary.changed}`
693
+ );
694
+ for (const change of changes) {
695
+ console.log(
696
+ ` · ${change.mode} --${change.token}:${change.before ?? "—"} → ${change.after ?? "—"}`
697
+ );
698
+ }
699
+
700
+ // 影响必须按「锁定时的断言」重判当前站点,而不是拿新主题自己跟自己比
701
+ now = await postCheck(variables, lock.assertions ?? []);
702
+ const impact = contrastImpact(lock.result ?? {}, now);
703
+ console.log(
704
+ ` 对比度影响:新增问题 ${impact.newFails.length}、修复 ${impact.resolvedFails.length}、新增无法判定 ${impact.newUnknown.length}`
705
+ );
706
+ for (const item of impact.newFails) console.log(" × " + item);
707
+ for (const item of impact.resolvedFails) console.log(" ✓ " + item);
708
+ for (const item of impact.newUnknown) console.log(" ? " + item);
709
+ }
710
+
711
+ if (doCheck) {
712
+ console.log(` 跟随更新:重跑 ztheme init ${lock.slug};保持现状:忽略此提示。`);
713
+ if (flags.has("strict")) process.exit(1);
714
+ return;
715
+ }
716
+
717
+ // ---- upgrade --pr ----
718
+ const cssFile = valueOf("file") ?? join("ztheme", lock.slug + ".css");
719
+ if (!existsSync(cssFile)) {
720
+ failWith("找不到生成的主题 CSS:" + cssFile + "(先跑 ztheme init " + lock.slug + ")", 2);
721
+ }
722
+
723
+ const localVars = parseCssVars(readFileSync(cssFile, "utf8"));
724
+ const drift = localDrift(localVars, lock.tokens);
725
+ if (drift.length && !flags.has("force")) {
726
+ console.log(`本地 CSS 与锁定令牌不一致(${drift.length} 处),可能手改过:`);
727
+ for (const item of drift.slice(0, 10)) {
728
+ console.log(
729
+ ` · ${item.mode} --${item.token}:本地 ${item.local ?? "—"},锁定 ${item.locked ?? "—"}`
730
+ );
731
+ }
732
+ if (drift.length > 10) console.log(` · …共 ${drift.length} 处`);
733
+ failWith("拒绝覆盖本地修改;确认要按站点当前版本重写,请加 --force", 2);
734
+ }
735
+ if (drift.length) {
736
+ console.log(`已加 --force:本地修改将被站点当前版本覆盖(${drift.length} 处)`);
737
+ }
738
+
739
+ const branch = "ztheme/upgrade-" + lock.slug;
740
+ if (!flags.has("write")) {
741
+ console.log(
742
+ `[dry-run] 将重写 ${cssFile}、更新 ${lockPath},并创建分支 ${branch};加 --write 执行。`
743
+ );
744
+ return;
745
+ }
746
+
747
+ let status = "";
748
+ try {
749
+ status = execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" });
750
+ } catch {
751
+ failWith("当前目录不是 git 仓库:upgrade --pr --write 需要 git", 2);
752
+ }
753
+ if (status.trim()) {
754
+ failWith("工作区不干净:先提交或暂存现有改动,再跑 upgrade --pr --write", 2);
755
+ }
756
+
757
+ try {
758
+ execFileSync("git", ["switch", "-c", branch], { encoding: "utf8", stdio: "pipe" });
759
+ } catch {
760
+ failWith("创建分支失败:" + branch + "(可能已存在或工作区受限)", 2);
761
+ }
762
+
763
+ const rulesRes = await tryGetJson("/r/themes/" + lock.slug + "/rules");
764
+ const siteVerified = rulesRes?.verified ?? null;
765
+ const nextLock = {
766
+ ...lock,
767
+ tokens: { light: siteVars.light ?? {}, dark: siteVars.dark ?? {} },
768
+ themeDigest: siteDigest,
769
+ lockedAt: new Date().toISOString(),
770
+ result: {
771
+ fails: now.fails,
772
+ warns: now.warns,
773
+ unknown: now.unknown,
774
+ assertionFails: (now.assertionResults ?? []).filter((r) => !r.ok).map((r) => r.about),
775
+ },
776
+ ...(siteVerified
777
+ ? { verifiedOk: !!siteVerified.ok, verifiedAt: new Date().toISOString() }
778
+ : {}),
779
+ };
780
+
781
+ writeFileSync(cssFile, toCss(lock.slug, site));
782
+ writeFileSync(lockPath, JSON.stringify(nextLock, null, 2) + "\n");
783
+ execFileSync("git", ["add", cssFile, lockPath], { encoding: "utf8" });
784
+ execFileSync(
785
+ "git",
786
+ [
787
+ "commit",
788
+ "-m",
789
+ "chore(ztheme): 升级 " +
790
+ lock.slug +
791
+ "(" +
792
+ String(lock.themeDigest).slice(0, 8) +
793
+ " → " +
794
+ siteDigest.slice(0, 8) +
795
+ ")",
796
+ ],
797
+ { encoding: "utf8", stdio: "pipe" }
798
+ );
799
+ console.log(
800
+ `已创建分支 ${branch} 并提交。下一步:git push -u origin ${branch},然后开 PR 人审。`
801
+ );
802
+ return;
803
+ }
804
+
631
805
  if (cmd === "check") {
632
806
  const strict = flags.has("strict");
633
807
  const fileAt = argv.indexOf("--file");