create-clis 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.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -0
  3. package/README.zh-CN.md +113 -0
  4. package/assets/manifest.json +99 -0
  5. package/assets/template/.editorconfig +12 -0
  6. package/assets/template/.gitattributes +18 -0
  7. package/assets/template/.github/ISSUE_TEMPLATE/bug_report.yml +86 -0
  8. package/assets/template/.github/ISSUE_TEMPLATE/feature_request.yml +45 -0
  9. package/assets/template/.github/PULL_REQUEST_TEMPLATE.md +26 -0
  10. package/assets/template/.github/workflows/ci.yml +42 -0
  11. package/assets/template/.github/workflows/release.yml +65 -0
  12. package/assets/template/.gitignorerc.json +21 -0
  13. package/assets/template/.nvmrc +1 -0
  14. package/assets/template/.oxlintrc.json +52 -0
  15. package/assets/template/.prettierignore +11 -0
  16. package/assets/template/.prettierrc +11 -0
  17. package/assets/template/.releaserc.json +17 -0
  18. package/assets/template/.vscode/extensions.json +8 -0
  19. package/assets/template/.vscode/launch.json +13 -0
  20. package/assets/template/.vscode/settings.json +14 -0
  21. package/assets/template/AGENTS.md +25 -0
  22. package/assets/template/CODE_OF_CONDUCT.md +91 -0
  23. package/assets/template/CONTRIBUTING.md +85 -0
  24. package/assets/template/CONTRIBUTING.zh-CN.md +85 -0
  25. package/assets/template/LICENSE +21 -0
  26. package/assets/template/README.md +22 -0
  27. package/assets/template/README.zh-CN.md +22 -0
  28. package/assets/template/SECURITY.md +21 -0
  29. package/assets/template/_gitignore +409 -0
  30. package/assets/template/_npmrc +6 -0
  31. package/assets/template/bunfig.toml +16 -0
  32. package/assets/template/docs/README.md +30 -0
  33. package/assets/template/docs/adrs/README.md +7 -0
  34. package/assets/template/docs/designs/README.md +11 -0
  35. package/assets/template/docs/designs/tech-debt.md +22 -0
  36. package/assets/template/docs/development.md +59 -0
  37. package/assets/template/lefthook.yml +55 -0
  38. package/assets/template/package.json +38 -0
  39. package/assets/template/packages/{{NAME}}/CHANGELOG.md +3 -0
  40. package/assets/template/packages/{{NAME}}/LICENSE +21 -0
  41. package/assets/template/packages/{{NAME}}/README.md +33 -0
  42. package/assets/template/packages/{{NAME}}/README.zh-CN.md +33 -0
  43. package/assets/template/packages/{{NAME}}/docs/README.md +21 -0
  44. package/assets/template/packages/{{NAME}}/package.json +40 -0
  45. package/assets/template/packages/{{NAME}}/scripts/build.ts +82 -0
  46. package/assets/template/packages/{{NAME}}/scripts/verify-release.test.ts +214 -0
  47. package/assets/template/packages/{{NAME}}/scripts/verify-release.ts +152 -0
  48. package/assets/template/packages/{{NAME}}/src/index.ts +15 -0
  49. package/assets/template/packages/{{NAME}}/tsconfig.build.json +12 -0
  50. package/assets/template/packages/{{NAME}}/tsconfig.json +5 -0
  51. package/assets/template/packages/{{NAME}}-cli/CHANGELOG.md +3 -0
  52. package/assets/template/packages/{{NAME}}-cli/LICENSE +21 -0
  53. package/assets/template/packages/{{NAME}}-cli/README.md +35 -0
  54. package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +35 -0
  55. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}} +30 -0
  56. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.cmd +30 -0
  57. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.d.mts +23 -0
  58. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.mjs +212 -0
  59. package/assets/template/packages/{{NAME}}-cli/docs/README.md +21 -0
  60. package/assets/template/packages/{{NAME}}-cli/package.json +48 -0
  61. package/assets/template/packages/{{NAME}}-cli/scripts/release-artifact.ts +141 -0
  62. package/assets/template/packages/{{NAME}}-cli/scripts/release.fixtures.ts +70 -0
  63. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.test.ts +444 -0
  64. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.ts +72 -0
  65. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.test.ts +126 -0
  66. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.ts +81 -0
  67. package/assets/template/packages/{{NAME}}-cli/src/cli.ts +36 -0
  68. package/assets/template/packages/{{NAME}}-cli/tsconfig.json +4 -0
  69. package/assets/template/scripts/ci.ts +163 -0
  70. package/assets/template/scripts/install-git-hooks.mjs +122 -0
  71. package/assets/template/scripts/install-git-hooks.test.ts +418 -0
  72. package/assets/template/scripts/lib/git-env.ts +21 -0
  73. package/assets/template/scripts/lib/release-verify.ts +431 -0
  74. package/assets/template/scripts/lib/tmp-root.ts +17 -0
  75. package/assets/template/scripts/lib/workspace.test.ts +92 -0
  76. package/assets/template/scripts/lib/workspace.ts +100 -0
  77. package/assets/template/scripts/lint-doc-examples.test.ts +129 -0
  78. package/assets/template/scripts/lint-doc-examples.ts +249 -0
  79. package/assets/template/scripts/lint-doc-references.test.ts +158 -0
  80. package/assets/template/scripts/lint-doc-references.ts +308 -0
  81. package/assets/template/scripts/lint-doc-shared.ts +59 -0
  82. package/assets/template/scripts/lint-stray-backups.test.ts +53 -0
  83. package/assets/template/scripts/lint-stray-backups.ts +39 -0
  84. package/assets/template/scripts/npm-trust-guard.test.ts +253 -0
  85. package/assets/template/scripts/npm-trust-guard.ts +533 -0
  86. package/assets/template/scripts/safe-install.ts +39 -0
  87. package/assets/template/scripts/transcription/api-harness.ts +219 -0
  88. package/assets/template/scripts/transcription/compare.ts +421 -0
  89. package/assets/template/scripts/transcription/corpus.ts +208 -0
  90. package/assets/template/scripts/transcription/fixture.ts +290 -0
  91. package/assets/template/scripts/transcription/make-mutants.ts +425 -0
  92. package/assets/template/scripts/transcription/report.ts +86 -0
  93. package/assets/template/scripts/transcription/run-conformance.ts +344 -0
  94. package/assets/template/scripts/transcription/validate-coverage.test.ts +119 -0
  95. package/assets/template/scripts/transcription/validate-coverage.ts +144 -0
  96. package/assets/template/scripts/transcription/validate.ts +366 -0
  97. package/assets/template/tsconfig.json +46 -0
  98. package/assets/template/turbo.jsonc +60 -0
  99. package/bin/create-clis +35 -0
  100. package/bin/create-clis.cmd +32 -0
  101. package/bin/create-clis.mjs +219 -0
  102. package/dist/create-clis.js +87682 -0
  103. package/dist/manifest.json +7 -0
  104. package/package.json +57 -0
@@ -0,0 +1,431 @@
1
+ /**
2
+ * 发布自证闸门的共享实现: 两包 (CLI / API) 的同名闸门共用本模块, 差异经 VerifyProfile
3
+ * 参数注入 (产物文件名 / 清单摘要字段名 / schema 版本 / 面包白名单) 与专属判定钩子
4
+ * (如 API 的 d.ts specifier 复查) 表达; 判定是纯函数, 事实可注入 (测试不依赖工作树)。
5
+ *
6
+ * 判定序 (两包统一, 顺序即口径): 先证「检出可信」(git 可读 / 有提交 / 工作树干净),
7
+ * 再证产物就位 (存在 / 非空 / 可读), 然后让清单与提交、产物三者逐项对上, 专属判定,
8
+ * 最后对发行面包内文件与白名单。
9
+ */
10
+ import { execFileSync } from 'node:child_process';
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, readFileSync, statSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+
15
+ import { cleanGitEnv } from './git-env.ts';
16
+
17
+ /** 一侧闸门的坐标与口径 (差异面全部收口于此) */
18
+ export interface VerifyProfile {
19
+ /** 产物主文件名 (dist/ 下): 如 'cli.js' / 'index.js' */
20
+ entryFile: string;
21
+ /** 清单文件名 (dist/ 下) */
22
+ manifestFile: string;
23
+ /** 清单里记录产物摘要的字段名 ('cliSha256' / 'entrySha256'; 字段名不统一以保发布物契约) */
24
+ shaField: string;
25
+ /** 清单 schema 版本 */
26
+ schemaVersion: number;
27
+ /** 发行面包白名单 (files 白名单的物化 + npm 强制包含项) */
28
+ packExpected: readonly string[];
29
+ }
30
+
31
+ /** 发布闸门判定输入: git 事实与产物现状分离采集, 判定是纯函数 (事实可注入, 测试不依赖工作树) */
32
+ export interface ReleaseFacts {
33
+ /** git status --porcelain 原文; null = 读不到 */
34
+ gitStatus: string | null;
35
+ /** HEAD 提交的完整哈希 (已经 normalizeCommit 归一); null = 读不到 */
36
+ gitHead: string | null;
37
+ /** 产物目录现状 */
38
+ dist: DistState;
39
+ /** 发行面包内文件清单的采集结果 (白名单判定用) */
40
+ pack: PackFacts;
41
+ }
42
+
43
+ /** 产物目录的磁盘现状 (缺失与形状不符都落成显式字段, 供判定与报错逐条取用) */
44
+ export interface DistState {
45
+ /** 产物主文件是否为常规文件 */
46
+ entryExists: boolean;
47
+ /** 产物字节数 (缺失为 0) */
48
+ entrySize: number;
49
+ /** 产物 sha256 (缺失 / 不可读 / 零字节为 null) */
50
+ entrySha256: string | null;
51
+ /** 清单是否存在 */
52
+ manifestExists: boolean;
53
+ /** 解析且形状合格后的清单; null = 不可用 (原因见 manifestIssue) */
54
+ manifest: Record<string, unknown> | null;
55
+ /** 清单不可用的原因 (人话); null = 清单可用 */
56
+ manifestIssue: string | null;
57
+ }
58
+
59
+ /** 发行面包内文件清单的采集结果 (采不到与「采到空包」必须可区分) */
60
+ export interface PackFacts {
61
+ /** 包内文件路径集 (相对包根); null = 采集失败, 原因见 issue */
62
+ files: string[] | null;
63
+ /** 采集失败的原因 (人话); null = 采集成功 */
64
+ issue: string | null;
65
+ }
66
+
67
+ /** 判定结论: 通过时带上被判定的提交与摘要 (供输出), 否则带人话拒绝原因 */
68
+ export type ReleaseVerdict =
69
+ { ok: true; commit: string; sha256: string } | { ok: false; reason: string };
70
+
71
+ /** sha256 十六进制 (同步读全文件: 产物是单文件 JS, 量级几十 KB) */
72
+ export const sha256File = (path: string): string =>
73
+ createHash('sha256').update(readFileSync(path)).digest('hex');
74
+
75
+ /** 完整提交哈希的形状 (git rev-parse 的输出形态; 短哈希形态也收, 阈值取 7) */
76
+ const isCommitHash = (value: unknown): value is string =>
77
+ typeof value === 'string' && /^[0-9a-f]{7,64}$/.test(value);
78
+
79
+ /** sha256 十六进制的形状 */
80
+ const isSha256 = (value: unknown): value is string =>
81
+ typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
82
+
83
+ /** 短哈希展示 (前 12 位; null 显示为占位符, 供人读诊断) */
84
+ export const shortHash = (value: string | null): string =>
85
+ value === null ? '(无)' : value.slice(0, 12);
86
+
87
+ /**
88
+ * 归一提交哈希: 去掉命令行输出自带的换行后校验形状; 形状不符 (含空串 / 多行) 一律视为读不到。
89
+ * 归一后值只可能是十六进制串, 可安全进人读文案 (低信任输入不落进输出面)。
90
+ */
91
+ export const normalizeCommit = (raw: string | null): string | null => {
92
+ if (raw === null) return null;
93
+ const trimmed = raw.trim();
94
+ return isCommitHash(trimmed) ? trimmed : null;
95
+ };
96
+
97
+ /** 未提交改动条数 (porcelain 一行一条; 空行不计) */
98
+ export const countDirtyEntries = (porcelain: string): number =>
99
+ porcelain.split('\n').filter((line) => line.trim() !== '').length;
100
+
101
+ /**
102
+ * 未提交改动的路径预览: porcelain 行剥状态前缀 ("XY "), 至多 `limit` 条, 超出以省略号收敛。
103
+ * 路径属仓库内已知文件, 落进人读文案可安全诊断「脏在哪里」; 不回显任何内容片段。
104
+ */
105
+ export const previewDirtyEntries = (porcelain: string, limit = 3): string => {
106
+ const paths = porcelain
107
+ .split('\n')
108
+ .filter((line) => line.trim() !== '')
109
+ .map((line) => line.slice(3).trim());
110
+ const shown = paths.slice(0, limit);
111
+ return shown.join(', ') + (paths.length > limit ? ' …' : '');
112
+ };
113
+
114
+ /**
115
+ * 跑一条只读 git 命令并收 stdout 原文; 失败返回 null (不抛)。
116
+ * 失败与「输出为空」必须可区分: 非 git 检出是「不知道」, 空输出是「没有改动」。
117
+ * 缓冲区取宽: 脏树可能列出成千上万条, 挤爆默认 1 MB 会把「工作树不干净」误报成「读不到状态」。
118
+ * env 经 cleanGitEnv (见 git-env.ts): 调用点给的 root 是唯一坐标, 宿主的 GIT_DIR 等不得
119
+ * 把只读探测改道到别的仓库 (在钩子环境里跑测试时, 宿主坐标曾让本模块读错仓库)。
120
+ */
121
+ export const readGitText = (root: string, args: string[]): string | null => {
122
+ try {
123
+ return execFileSync('git', args, {
124
+ cwd: root,
125
+ encoding: 'utf8',
126
+ stdio: ['ignore', 'pipe', 'ignore'],
127
+ maxBuffer: 32 * 1024 * 1024,
128
+ env: cleanGitEnv(),
129
+ });
130
+ } catch {
131
+ return null;
132
+ }
133
+ };
134
+
135
+ /**
136
+ * 清单形状体检: 合格返回 null, 否则返回人话病灶。
137
+ * 只判字段形状与版本, 不判内容对错 (内容与提交 / 产物的对账归 judgeRelease); 值一律不回显,
138
+ * 防清单里的低信任文本落进输出面。
139
+ */
140
+ const manifestShapeProblem = (
141
+ value: unknown,
142
+ profile: VerifyProfile,
143
+ ): string | null => {
144
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
145
+ return '清单应为 JSON 对象';
146
+ }
147
+ const fields = value as Record<string, unknown>;
148
+ if (fields.schemaVersion !== profile.schemaVersion) {
149
+ return `清单 schemaVersion 不受支持 (期望 ${profile.schemaVersion})`;
150
+ }
151
+ if (fields.commit !== null && !isCommitHash(fields.commit)) {
152
+ return '清单 commit 字段形状不符';
153
+ }
154
+ if (fields.dirty !== null && typeof fields.dirty !== 'boolean') {
155
+ return '清单 dirty 字段形状不符';
156
+ }
157
+ if (!isSha256(fields[profile.shaField])) {
158
+ return `清单 ${profile.shaField} 字段形状不符`;
159
+ }
160
+ if (typeof fields.builtAt !== 'string' || fields.builtAt === '') {
161
+ return '清单 builtAt 字段形状不符';
162
+ }
163
+ return null;
164
+ };
165
+
166
+ /** 读清单: 缺失 / 读取失败 / 非 JSON / 形状不符都落成显式字段, 不抛错 (判定层据字段决定拒绝口径) */
167
+ export const readManifest = (
168
+ path: string,
169
+ profile: VerifyProfile,
170
+ ): {
171
+ exists: boolean;
172
+ manifest: Record<string, unknown> | null;
173
+ issue: string | null;
174
+ } => {
175
+ if (!existsSync(path)) return { exists: false, manifest: null, issue: null };
176
+ let raw: string;
177
+ try {
178
+ raw = readFileSync(path, 'utf8');
179
+ } catch {
180
+ return { exists: true, manifest: null, issue: '清单读取失败' };
181
+ }
182
+ let parsed: unknown;
183
+ try {
184
+ parsed = JSON.parse(raw);
185
+ } catch {
186
+ return { exists: true, manifest: null, issue: '清单不是合法 JSON' };
187
+ }
188
+ const problem = manifestShapeProblem(parsed, profile);
189
+ if (problem !== null) return { exists: true, manifest: null, issue: problem };
190
+ return {
191
+ exists: true,
192
+ manifest: parsed as Record<string, unknown>,
193
+ issue: null,
194
+ };
195
+ };
196
+
197
+ /**
198
+ * 读产物目录现状: 逐项探测产物主文件与清单, 缺失 / 不可读 / 形状不符一律落成显式字段;
199
+ * 本函数只取事实, 不下判定 (判定归 judgeRelease)。
200
+ */
201
+ export const readDistState = (
202
+ distDir: string,
203
+ profile: VerifyProfile,
204
+ ): DistState => {
205
+ const entryPath = join(distDir, profile.entryFile);
206
+ let entryExists = false;
207
+ let entrySize = 0;
208
+ let entrySha256: string | null = null;
209
+ try {
210
+ const info = statSync(entryPath);
211
+ entryExists = info.isFile();
212
+ entrySize = info.size;
213
+ if (entryExists && entrySize > 0) entrySha256 = sha256File(entryPath);
214
+ } catch {
215
+ // 缺失 / 不可达: 保持缺失态; 具体病灶由 judgeRelease 按字段报出, 此处不抢跑
216
+ }
217
+ const loaded = readManifest(join(distDir, profile.manifestFile), profile);
218
+ return {
219
+ entryExists,
220
+ entrySize,
221
+ entrySha256,
222
+ manifestExists: loaded.exists,
223
+ manifest: loaded.manifest,
224
+ manifestIssue: loaded.issue,
225
+ };
226
+ };
227
+
228
+ /**
229
+ * 解析 `npm pack --json` 的输出: 取首个元素的 files[].path。
230
+ * 形状不符 (非数组 / 无 files / 条目缺 path) 一律返回 null, 不猜结构 (交由采集层落 issue)。
231
+ */
232
+ export const parsePackFiles = (raw: string): string[] | null => {
233
+ let parsed: unknown;
234
+ try {
235
+ parsed = JSON.parse(raw);
236
+ } catch {
237
+ return null;
238
+ }
239
+ if (!Array.isArray(parsed)) return null;
240
+ const first: unknown = parsed[0];
241
+ if (typeof first !== 'object' || first === null) return null;
242
+ const { files } = first as { files?: unknown };
243
+ if (!Array.isArray(files)) return null;
244
+ const paths: string[] = [];
245
+ for (const entry of files as unknown[]) {
246
+ if (typeof entry !== 'object' || entry === null) return null;
247
+ const { path } = entry as { path?: unknown };
248
+ if (typeof path !== 'string' || path === '') return null;
249
+ paths.push(path);
250
+ }
251
+ return paths;
252
+ };
253
+
254
+ /**
255
+ * 跑 `npm pack --dry-run --json --ignore-scripts` 收发行面包内文件清单 (只读, 不落 tarball)。
256
+ *
257
+ * 两个旗标各有硬理由: --dry-run 不写盘; --ignore-scripts 必须带, 否则 pack 过程会再进一次
258
+ * 脚本链 (在 prepublishOnly 语境下自我递归, 已实测)。为什么用 npm 而非 bun pm pack:
259
+ * bun pm pack 只有人读文本输出、无 JSON 旗标 (bun 1.4.2 的 --help 实测), 清单解析没有稳定契约。
260
+ * 采集失败 (npm 不在 PATH / 非零退出 / 输出非 JSON) 一律落 issue, 不抛: 判定层按「采不到就拒」处理。
261
+ */
262
+ export const readPackFiles = (root: string): PackFacts => {
263
+ // Windows 的 npm 是 npm.cmd, execFile 不走 shell 时不会自动补扩展名
264
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
265
+ let raw: string;
266
+ try {
267
+ raw = execFileSync(
268
+ npm,
269
+ ['pack', '--dry-run', '--json', '--ignore-scripts'],
270
+ {
271
+ cwd: root,
272
+ encoding: 'utf8',
273
+ stdio: ['ignore', 'pipe', 'ignore'],
274
+ maxBuffer: 32 * 1024 * 1024,
275
+ },
276
+ );
277
+ } catch {
278
+ return {
279
+ files: null,
280
+ issue: 'npm pack 跑不起来 (需要 npm: 不在 PATH 或非零退出)',
281
+ };
282
+ }
283
+ const files = parsePackFiles(raw);
284
+ if (files === null) {
285
+ return { files: null, issue: 'npm pack 的输出不是预期的 JSON 形状' };
286
+ }
287
+ // 排序稳定化 (npm 输出顺序无契约; 判定是集合相等, 排序只为输出与测试的可复现)
288
+ return { files: files.sort(), issue: null };
289
+ };
290
+
291
+ /**
292
+ * 差异路径的人话呈现: 剔控制字符、超 5 项截断计总数。
293
+ * 路径来自 npm 输出 (低信任输入), 直接回显会把不受控文本带进输出面, 故先降噪再列。
294
+ */
295
+ const describePaths = (paths: string[]): string => {
296
+ const cleaned = paths.map((path) => path.replace(/\p{Cc}/gu, '?'));
297
+ const head = cleaned.slice(0, 5).join(', ');
298
+ return cleaned.length > 5 ? `${head} 等 ${cleaned.length} 项` : head;
299
+ };
300
+
301
+ /**
302
+ * 发行面包内文件清单的判定 (纯函数): 集合相等才算过, 差异分「多出」「缺少」两向人话列出。
303
+ * 「多出」是杂质溜进发行面 (如仓库根的 README 备份), 「缺少」是发行面残缺 (如漏收产物)。
304
+ */
305
+ export const judgePackFiles = (
306
+ files: string[],
307
+ expected: readonly string[],
308
+ ): { ok: true } | { ok: false; reason: string } => {
309
+ const actual = new Set(files);
310
+ const expectedSet = new Set(expected);
311
+ const extra = [...actual].filter((path) => !expectedSet.has(path)).sort();
312
+ const missing = expected.filter((path) => !actual.has(path));
313
+ if (extra.length === 0 && missing.length === 0) return { ok: true };
314
+ const parts: string[] = [];
315
+ if (extra.length > 0) parts.push(`多出 ${describePaths(extra)}`);
316
+ if (missing.length > 0) parts.push(`缺少 ${describePaths(missing)}`);
317
+ return {
318
+ ok: false,
319
+ reason: `发行面包内文件与白名单不符: ${parts.join('; ')}`,
320
+ };
321
+ };
322
+
323
+ /**
324
+ * 发布闸门判定 (纯函数, 不碰文件系统): 按固定次序短路, 首条不过即拒。
325
+ * extraJudge 是侧专属判定 (在产物链检查之后、面包白名单之前调用; 返回 null 即通过, 返回人话即拒)。
326
+ *
327
+ * ### 数据追踪示例
328
+ * ```text
329
+ * Input(真实 Payload)
330
+ * facts.dist.entrySha256 = "9f2c…", facts.dist.manifest = { commit: "a2109d72f4…", dirty: false, cliSha256: "9f2c…" }
331
+ * facts.gitHead = "a2109d72f4…", facts.gitStatus = ""
332
+ * facts.pack.files = ["LICENSE", …, "dist/cli.js"]
333
+ * profile = { entryFile: "cli.js", shaField: "cliSha256", packExpected: [...] }
334
+ *
335
+ * 步骤 1:检出可信 (git 可读 / 有提交 / 干净) → 全部通过
336
+ * 步骤 2:产物就位 (存在 / 非空 / 可读) → 全部通过
337
+ * 步骤 3:清单对账 (dirty=false; commit == HEAD; shaField == 实测摘要) → 全部通过
338
+ * 步骤 4:专属判定 (extraJudge) → null (通过)
339
+ * 步骤 5:面包白名单 (集合相等) → 通过
340
+ *
341
+ * Output(数据契约)
342
+ * return { ok: true, commit: "a2109d72f4…", sha256: "9f2c…" }
343
+ * ```
344
+ */
345
+ export const judgeRelease = (
346
+ facts: ReleaseFacts,
347
+ profile: VerifyProfile,
348
+ extraJudge?: () => string | null,
349
+ ): ReleaseVerdict => {
350
+ const { gitStatus, gitHead, dist } = facts;
351
+ if (gitStatus === null) {
352
+ return {
353
+ ok: false,
354
+ reason:
355
+ '读不到 git 状态 (非 git 检出, 或 git 不可用), 产物无法与提交对应',
356
+ };
357
+ }
358
+ if (gitHead === null) {
359
+ return {
360
+ ok: false,
361
+ reason: '读不到 HEAD 提交 (仓库尚无提交, 或 git 不可用)',
362
+ };
363
+ }
364
+ if (gitStatus.trim() !== '') {
365
+ return {
366
+ ok: false,
367
+ reason: `工作树不干净 (未提交改动 ${countDirtyEntries(gitStatus)} 项: ${previewDirtyEntries(gitStatus)}), 产物无法与任何提交对应`,
368
+ };
369
+ }
370
+ if (!dist.entryExists) {
371
+ return {
372
+ ok: false,
373
+ reason: `产物缺失 (dist/${profile.entryFile} 不存在)`,
374
+ };
375
+ }
376
+ if (dist.entrySize === 0) {
377
+ return {
378
+ ok: false,
379
+ reason: `产物为空 (dist/${profile.entryFile} 是零字节文件)`,
380
+ };
381
+ }
382
+ if (dist.entrySha256 === null) {
383
+ return {
384
+ ok: false,
385
+ reason: `产物不可读 (dist/${profile.entryFile} 的摘要算不出)`,
386
+ };
387
+ }
388
+ if (!dist.manifestExists) {
389
+ return {
390
+ ok: false,
391
+ reason: `产物清单缺失 (dist/${profile.manifestFile} 不存在)`,
392
+ };
393
+ }
394
+ if (dist.manifest === null) {
395
+ return {
396
+ ok: false,
397
+ reason: `产物清单不可用: ${dist.manifestIssue ?? '原因不明'}`,
398
+ };
399
+ }
400
+ if (dist.manifest.dirty !== false) {
401
+ return {
402
+ ok: false,
403
+ reason: '产物清单记录的是脏工作树构建 (dirty=true), 产物不对应任何提交',
404
+ };
405
+ }
406
+ if (dist.manifest.commit !== gitHead) {
407
+ return {
408
+ ok: false,
409
+ reason: `产物清单记录的提交 ${shortHash(String(dist.manifest.commit))} 与 HEAD ${shortHash(gitHead)} 不一致, 产物不是本次提交构建的`,
410
+ };
411
+ }
412
+ if (dist.manifest[profile.shaField] !== dist.entrySha256) {
413
+ return {
414
+ ok: false,
415
+ reason: '产物摘要与清单记录不符, 产物与清单不是同一次构建的产物',
416
+ };
417
+ }
418
+ if (extraJudge !== undefined) {
419
+ const reason = extraJudge();
420
+ if (reason !== null) return { ok: false, reason };
421
+ }
422
+ if (facts.pack.files === null) {
423
+ return {
424
+ ok: false,
425
+ reason: `发行面包内文件清单采不到 (${facts.pack.issue ?? '原因不明'}), 该项检查需要 npm`,
426
+ };
427
+ }
428
+ const packVerdict = judgePackFiles(facts.pack.files, profile.packExpected);
429
+ if (!packVerdict.ok) return { ok: false, reason: packVerdict.reason };
430
+ return { ok: true, commit: gitHead, sha256: dist.entrySha256 };
431
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 临时根工厂: 在 ~/tmp 下建独占临时目录, 测试与闸门生产代码统一经此创建。
3
+ *
4
+ * 动机: 套件惯例是临时目录落 ~/tmp (不用系统 /tmp), 本地 ~/tmp 常备而 CI runner
5
+ * 的 HOME 下没有 tmp 目录, 直接 mkdtemp 会因父目录缺失报 ENOENT (2026-09-30 CI
6
+ * 实翻, 6 处调用点集体挂红); 前置补建在此一处兜底, 调用点不再各自假设目录已存在。
7
+ */
8
+ import { mkdirSync, mkdtempSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+
12
+ /** 在 ~/tmp 下建独占临时目录, 返回其绝对路径; 父目录缺失时先补建 */
13
+ export function makeTmpRoot(prefix: string): string {
14
+ const tmpBase = join(homedir(), 'tmp');
15
+ mkdirSync(tmpBase, { recursive: true });
16
+ return mkdtempSync(join(tmpBase, prefix));
17
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * 工作区坐标派生单测: 临时根上验证派生规则 (CLI = 带 bin 且引用仓内无 bin 包;
3
+ * API = 被它引用的无 bin 包) 与两类异常路径。
4
+ */
5
+ import { afterAll, describe, expect, test } from 'bun:test';
6
+
7
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+
10
+ import { makeTmpRoot } from './tmp-root.ts';
11
+ import { listWorkspacePackages, resolveCliAndApi } from './workspace.ts';
12
+
13
+ const roots: string[] = [];
14
+ function makeRoot(files: Record<string, unknown>): string {
15
+ const root = makeTmpRoot('workspace-');
16
+ roots.push(root);
17
+ for (const [rel, content] of Object.entries(files)) {
18
+ const abs = join(root, rel);
19
+ mkdirSync(dirname(abs), { recursive: true });
20
+ writeFileSync(abs, JSON.stringify(content, null, 2));
21
+ }
22
+ return root;
23
+ }
24
+ afterAll(() => {
25
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
26
+ });
27
+
28
+ describe('resolveCliAndApi', () => {
29
+ test('派生两包: cli = 带 bin 者, api = cli devDeps 引的仓内包', () => {
30
+ const root = makeRoot({
31
+ 'package.json': { workspaces: ['packages/*'] },
32
+ 'packages/tool-cli/package.json': {
33
+ name: '@x/tool-cli',
34
+ bin: { tool: 'bin/tool.mjs' },
35
+ devDependencies: { '@x/tool': '1.0.0' },
36
+ },
37
+ 'packages/tool/package.json': { name: '@x/tool' },
38
+ });
39
+ const { cli, api } = resolveCliAndApi(root);
40
+ expect(cli.name).toBe('@x/tool-cli');
41
+ expect(cli.dir).toBe('packages/tool-cli');
42
+ expect(api.name).toBe('@x/tool');
43
+ expect(api.dir).toBe('packages/tool');
44
+ });
45
+
46
+ test('仓内出现第二个带 bin 包时, 主产品两包仍唯一确定', () => {
47
+ const root = makeRoot({
48
+ 'package.json': { workspaces: ['packages/*'] },
49
+ 'packages/tool/package.json': {
50
+ name: 'tool',
51
+ bin: { tool: 'bin/tool.mjs' },
52
+ devDependencies: { lib: '1.0.0' },
53
+ },
54
+ 'packages/lib/package.json': { name: 'lib' },
55
+ // 第二个带 bin 包 (不依赖仓内包): 旧判据 (find bin !== undefined) 会因目录序歧义
56
+ 'packages/create-x/package.json': {
57
+ name: 'create-x',
58
+ bin: { 'create-x': 'bin.mjs' },
59
+ },
60
+ });
61
+ const { cli, api } = resolveCliAndApi(root);
62
+ expect(cli.name).toBe('tool');
63
+ expect(api.name).toBe('lib');
64
+ });
65
+
66
+ test('无 bin 包时报错', () => {
67
+ const root = makeRoot({
68
+ 'package.json': { workspaces: ['packages/*'] },
69
+ 'packages/only-lib/package.json': { name: '@x/only-lib' },
70
+ });
71
+ expect(() => resolveCliAndApi(root)).toThrow(/未找到主 CLI 包/);
72
+ });
73
+
74
+ test('cli 未依赖任何仓内包时报错', () => {
75
+ const root = makeRoot({
76
+ 'package.json': { workspaces: ['packages/*'] },
77
+ 'packages/tool-cli/package.json': {
78
+ name: '@x/tool-cli',
79
+ bin: { tool: 'bin/tool.mjs' },
80
+ devDependencies: { lodash: '4.0.0' },
81
+ },
82
+ });
83
+ expect(() => resolveCliAndApi(root)).toThrow(/未找到主 CLI 包/);
84
+ });
85
+
86
+ test('不支持的 workspaces 形态显式报错', () => {
87
+ const root = makeRoot({
88
+ 'package.json': { workspaces: ['apps/**'] },
89
+ });
90
+ expect(() => listWorkspacePackages(root)).toThrow(/暂不支持派生/);
91
+ });
92
+ });
@@ -0,0 +1,100 @@
1
+ /**
2
+ * 工作区坐标派生 (单一事实来源: 根 package.json 的 workspaces)。
3
+ *
4
+ * 派生规则 (与「依赖方向纪律」同构): **CLI 包** = 带 `bin` 且其 devDependencies 引用某个无
5
+ * `bin` 仓内包的包; **API 包** = 被它引用的那个无 `bin` 包 (工具 → 库 单向唯一确定)。仓内可有
6
+ * 多个带 `bin` 的工具包 (如生成器包), 主产品线以依赖关系锚定; 包目录改名或包名变更时, 依赖
7
+ * 本模块的脚本 (ci.ts / make-mutants.ts) 零修改。
8
+ *
9
+ * 已知的单点同步 (无法运行时派生): `tsconfig.json` 的 paths 是静态配置, 改包名时需在此一处
10
+ * 手动同步 (见 docs/designs/collection-relocation.md 的重建清单)。
11
+ */
12
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+
15
+ /** 工作区内的一个包 */
16
+ export interface WorkspacePackage {
17
+ /** 包名 (如 @scope/name) */
18
+ name: string;
19
+ /** 仓库相对目录 (如 packages/name) */
20
+ dir: string;
21
+ /** 解析后的 package.json (供需要字段的调用方复用) */
22
+ manifest: Record<string, unknown>;
23
+ }
24
+
25
+ /** 读根 package.json 的 workspaces 并展开为包清单 (支持 'dir/*' 形态; 其它形态显式报错) */
26
+ export function listWorkspacePackages(root: string): WorkspacePackage[] {
27
+ const rootManifest = JSON.parse(
28
+ readFileSync(join(root, 'package.json'), 'utf8'),
29
+ ) as { workspaces?: unknown };
30
+ const patterns = Array.isArray(rootManifest.workspaces)
31
+ ? rootManifest.workspaces
32
+ : [];
33
+ const packages: WorkspacePackage[] = [];
34
+ for (const pattern of patterns) {
35
+ const match =
36
+ typeof pattern === 'string' ? pattern.match(/^([^/*]+)\/\*$/) : null;
37
+ if (match === null) {
38
+ throw new Error(
39
+ `workspaces 形态暂不支持派生: ${String(pattern)} (需形如 packages/*)`,
40
+ );
41
+ }
42
+ const parent = match[1]!;
43
+ for (const entry of readdirSync(join(root, parent), {
44
+ withFileTypes: true,
45
+ })) {
46
+ if (!entry.isDirectory()) continue;
47
+ const dir = `${parent}/${entry.name}`;
48
+ const manifestPath = join(root, dir, 'package.json');
49
+ if (!existsSync(manifestPath)) continue;
50
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Record<
51
+ string,
52
+ unknown
53
+ >;
54
+ if (typeof manifest.name !== 'string') continue;
55
+ packages.push({ name: manifest.name, dir, manifest });
56
+ }
57
+ }
58
+ return packages;
59
+ }
60
+
61
+ /**
62
+ * 派生主产品两包: 带 bin 且依赖某个无 bin 仓内包的, 是主 CLI 包; 被它引用的无 bin 包是 API 包。
63
+ * (判据依据: 「依赖方向纪律」工具 → 库单向; 仓内可有多个带 bin 的工具包, 主产品线以依赖关系锚定。)
64
+ */
65
+ export function resolveCliAndApi(root: string): {
66
+ cli: WorkspacePackage;
67
+ api: WorkspacePackage;
68
+ } {
69
+ const packages = listWorkspacePackages(root);
70
+ const cli = packages.find((pkg) => {
71
+ if (pkg.manifest.bin === undefined) return false;
72
+ const devDeps = (pkg.manifest.devDependencies ?? {}) as Record<
73
+ string,
74
+ unknown
75
+ >;
76
+ return packages.some(
77
+ (other) =>
78
+ other !== pkg &&
79
+ other.manifest.bin === undefined &&
80
+ other.name in devDeps,
81
+ );
82
+ });
83
+ if (cli === undefined) {
84
+ throw new Error('未找到主 CLI 包 (带 bin 且依赖仓内无 bin 包)');
85
+ }
86
+ const devDeps = (cli.manifest.devDependencies ?? {}) as Record<
87
+ string,
88
+ unknown
89
+ >;
90
+ const api = packages.find(
91
+ (pkg) =>
92
+ pkg.name !== cli.name &&
93
+ pkg.manifest.bin === undefined &&
94
+ pkg.name in devDeps,
95
+ );
96
+ if (api === undefined) {
97
+ throw new Error(`未找到 CLI 包 (${cli.name}) 所依赖的仓内 API 包`);
98
+ }
99
+ return { cli, api };
100
+ }