@icebreakers/monorepo 3.2.18 → 4.0.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.
@@ -0,0 +1,2744 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-twds-ZHy.mjs";
2
+ import { i as getWorkspacePackages, n as getWorkspaceData, r as getWorkspacePackageSummaries } from "./workspace-DS6LAL71.mjs";
3
+ import { _ as isIgnorableFsError, c as devDependencies$1, d as logger, g as fs$1, i as packageDir, l as name$1, n as assetsDir, o as templatesDir, s as dependencies, t as initToolingTargets, u as version$1 } from "./types-CveZChKu.mjs";
4
+ import { a as loadMonorepoConfig, c as resolveToolingConfig, i as getMonorepoConfigCandidates, o as loadMonorepoConfigDetails, s as resolveCommandConfig } from "./config-BGCo7USv.mjs";
5
+ import { f as defineTsconfigConfig } from "./tooling-DyUe-eiv.mjs";
6
+ import gitUrlParse from "git-url-parse";
7
+ import { simpleGit } from "simple-git";
8
+ import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
9
+ import path from "pathe";
10
+ import process from "node:process";
11
+ import { readdir } from "node:fs/promises";
12
+ import { execFileSync, spawnSync } from "node:child_process";
13
+ import fs from "node:fs";
14
+ import path$1 from "node:path";
15
+ import { checkbox, ensureTemplateAssetsPrepared, getAssetTargets, getTemplateChoices, isGitignoreFile, scaffoldTemplate, shouldSkipTemplatePath, suggestTemplateKey, templateChoices, toPublishGitignorePath, toWorkspaceGitignorePath } from "@icebreakers/monorepo-templates";
16
+ import YAML, { isSeq, parseDocument } from "yaml";
17
+ import crypto from "node:crypto";
18
+ import os from "node:os";
19
+ import pc from "picocolors";
20
+ import { coerce, gte, minVersion, satisfies } from "semver";
21
+ import { parse, stringify } from "comment-json";
22
+ import { Buffer } from "node:buffer";
23
+ import klaw from "klaw";
24
+ //#region src/core/git.ts
25
+ /**
26
+ * 对 simple-git 的轻量封装,集中处理配置缓存与常用查询。
27
+ */
28
+ var GitClient = class {
29
+ client;
30
+ #config;
31
+ constructor(options = {}) {
32
+ this.client = simpleGit(options);
33
+ }
34
+ /**
35
+ * 读取 Git 的 config 列表,原样返回 simple-git 的结果。
36
+ */
37
+ listConfig() {
38
+ return this.client.listConfig();
39
+ }
40
+ /**
41
+ * 初始化配置缓存,避免多次访问 Git 产生的性能损耗。
42
+ */
43
+ async init() {
44
+ const listConfig = await this.listConfig();
45
+ this.#config = listConfig.all;
46
+ return this.#config;
47
+ }
48
+ /**
49
+ * 获取缓存的配置,若未初始化则自动触发 init。
50
+ */
51
+ async getConfig() {
52
+ if (this.#config) return this.#config;
53
+ else return await this.init();
54
+ }
55
+ /**
56
+ * 解析 remote.origin.url,返回 git-url-parse 的结构,便于获取仓库元信息。
57
+ */
58
+ async getGitUrl() {
59
+ const x = (await this.getConfig())["remote.origin.url"];
60
+ if (typeof x === "string") return gitUrlParse(x);
61
+ }
62
+ /**
63
+ * 组合 owner/name,生成常用的仓库名表达。
64
+ */
65
+ async getRepoName() {
66
+ const url = await this.getGitUrl();
67
+ if (url) return `${url.owner}/${url.name}`;
68
+ }
69
+ /**
70
+ * 从 Git 配置中提取用户信息,用于填充 package.json author 字段。
71
+ */
72
+ async getUser() {
73
+ const config = await this.getConfig();
74
+ return {
75
+ name: config["user.name"],
76
+ email: config["user.email"]
77
+ };
78
+ }
79
+ /**
80
+ * 获取当前仓库的顶层目录路径。
81
+ */
82
+ async getRepoRoot() {
83
+ try {
84
+ const root = await this.client.revparse(["--show-toplevel"]);
85
+ return typeof root === "string" ? root.trim() : void 0;
86
+ } catch {
87
+ return;
88
+ }
89
+ }
90
+ };
91
+ //#endregion
92
+ //#region src/commands/ai.ts
93
+ const agenticSections = [
94
+ "目标/产物",
95
+ "约束(性能/风格/兼容/不可改动范围)",
96
+ "验收标准(要跑的命令、预期输出/文件)",
97
+ "仓库路径",
98
+ "允许操作(可/不可写文件,可运行的命令清单,可否联网)",
99
+ "上下文线索(日志/文件/模块/相关 issue)",
100
+ "里程碑(根因→设计→实现→验证)"
101
+ ];
102
+ const defaultAgenticBaseDir = "agentic/prompts";
103
+ function renderMarkdownTemplate() {
104
+ return `${agenticSections.map((title) => `## ${title}\n- `).join("\n\n")}\n`;
105
+ }
106
+ function renderJsonTemplate() {
107
+ const payload = {};
108
+ for (const title of agenticSections) payload[title] = "";
109
+ return `${JSON.stringify(payload, null, 2)}\n`;
110
+ }
111
+ function createTimestampFolderName(date = /* @__PURE__ */ new Date()) {
112
+ const pad = (value) => value.toString().padStart(2, "0");
113
+ return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}-${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`;
114
+ }
115
+ /**
116
+ * 生成 Agentic 任务提示词模板,默认写入 agentic/prompts/<timestamp>/prompt.md,可自定义输出路径。
117
+ */
118
+ async function generateAgenticTemplate(options = {}) {
119
+ const cwd = options.cwd ?? process.cwd();
120
+ const format = options.format ?? "md";
121
+ const baseDir = options.baseDir ?? "agentic/prompts";
122
+ if (format !== "md" && format !== "json") throw new Error(`不支持的模板格式:${format}`);
123
+ const template = format === "md" ? renderMarkdownTemplate() : renderJsonTemplate();
124
+ const ext = format === "json" ? "json" : "md";
125
+ let outputPath = options.output;
126
+ if (!outputPath && options.name) outputPath = path.join(baseDir, `${options.name}.${ext}`);
127
+ if (!outputPath) {
128
+ const folderName = options.folderName ?? createTimestampFolderName();
129
+ outputPath = path.join(baseDir, folderName, `prompt.${ext}`);
130
+ }
131
+ const targetPath = path.resolve(cwd, outputPath);
132
+ const targetDir = path.dirname(targetPath);
133
+ await fs$1.ensureDir(targetDir);
134
+ const exists = await fs$1.pathExists(targetPath);
135
+ if (exists && !options.force) throw new Error(`目标文件已存在:${path.relative(cwd, targetPath)}`);
136
+ await fs$1.outputFile(targetPath, template, "utf8");
137
+ const actionLabel = exists ? "已覆盖模板" : "已生成模板";
138
+ logger.success(`${actionLabel}:${path.relative(cwd, targetPath)}`);
139
+ return template;
140
+ }
141
+ async function loadAgenticTasks(filePath, cwd) {
142
+ const fullPath = path.resolve(cwd, filePath);
143
+ const tasks = await fs$1.readJson(fullPath);
144
+ if (!Array.isArray(tasks)) throw new TypeError("任务清单需要是数组");
145
+ return tasks;
146
+ }
147
+ async function generateAgenticTemplates(tasks, defaults = {}) {
148
+ const results = [];
149
+ for (const task of tasks) {
150
+ const normalized = typeof task === "string" ? {
151
+ ...defaults,
152
+ name: task
153
+ } : {
154
+ ...defaults,
155
+ ...task
156
+ };
157
+ results.push(await generateAgenticTemplate(normalized));
158
+ }
159
+ return results;
160
+ }
161
+ //#endregion
162
+ //#region src/commands/verify/index.ts
163
+ const zeroSha = "0".repeat(40);
164
+ const typecheckExtensions = new Set([
165
+ ".ts",
166
+ ".tsx",
167
+ ".mts",
168
+ ".cts",
169
+ ".vue"
170
+ ]);
171
+ const whitespacePattern = /\s+/;
172
+ const gitDirName = ".git";
173
+ const defaultWorkspaceOrder = [
174
+ "packages/create-icebreaker",
175
+ "packages/monorepo",
176
+ "packages/monorepo-templates",
177
+ "packages/repoctl",
178
+ "templates/cli",
179
+ "templates/client",
180
+ "templates/server",
181
+ "templates/tsdown",
182
+ "templates/vitepress",
183
+ "templates/vue-lib"
184
+ ].sort((left, right) => right.length - left.length);
185
+ function getPackageScripts(dir, cwd) {
186
+ const packageJsonPath = path$1.join(cwd, dir, "package.json");
187
+ if (!fs.existsSync(packageJsonPath)) return {};
188
+ return JSON.parse(fs.readFileSync(packageJsonPath, "utf8")).scripts ?? {};
189
+ }
190
+ function getRootLevelTasksForFile(filePath) {
191
+ const basename = path$1.basename(filePath);
192
+ if (filePath.startsWith(".github/")) return [
193
+ "build",
194
+ "test",
195
+ "tsd"
196
+ ];
197
+ if (filePath.startsWith(".husky/")) return [
198
+ "build",
199
+ "test",
200
+ "tsd"
201
+ ];
202
+ if (filePath === "package.json" || filePath === "pnpm-lock.yaml" || filePath === "turbo.json" || filePath === "pnpm-workspace.yaml") return [
203
+ "build",
204
+ "test",
205
+ "tsd"
206
+ ];
207
+ if (basename.startsWith("tsconfig") || filePath === "commitlint.config.ts" || filePath === "eslint.config.js" || filePath === "lint-staged.config.js" || filePath === "stylelint.config.js" || filePath === "vitest.config.ts" || filePath.startsWith("scripts/")) return [
208
+ "build",
209
+ "test",
210
+ "tsd"
211
+ ];
212
+ return [];
213
+ }
214
+ function resolveWorkspaceDir(filePath, workspaces) {
215
+ const normalized = filePath.split(path$1.sep).join("/");
216
+ for (const workspace of workspaces) if (normalized === workspace || normalized.startsWith(`${workspace}/`)) return workspace;
217
+ return null;
218
+ }
219
+ function getChangedFilesForRange(base, head, cwd, execFile) {
220
+ return execFile("git", [
221
+ "diff",
222
+ "--name-only",
223
+ "--diff-filter=ACMR",
224
+ `${base}...${head}`
225
+ ], {
226
+ cwd,
227
+ encoding: "utf8"
228
+ }).split("\n").filter(Boolean);
229
+ }
230
+ function getChangedFilesForNewRemote(head, cwd, execFile) {
231
+ return execFile("git", [
232
+ "diff",
233
+ "--name-only",
234
+ "--diff-filter=ACMR",
235
+ execFile("git", [
236
+ "hash-object",
237
+ "-t",
238
+ "tree",
239
+ "--stdin"
240
+ ], {
241
+ cwd,
242
+ encoding: "utf8",
243
+ input: ""
244
+ }).trim(),
245
+ head
246
+ ], {
247
+ cwd,
248
+ encoding: "utf8"
249
+ }).split("\n").filter(Boolean);
250
+ }
251
+ function runPnpmCommand(cwd, label, args, spawn) {
252
+ process.stdout.write(`${label}\n`);
253
+ const result = spawn("pnpm", args, {
254
+ cwd,
255
+ stdio: "inherit"
256
+ });
257
+ if (result.status !== 0) process.exit(result.status ?? 1);
258
+ }
259
+ function runShellCommand(cwd, label, command, spawn) {
260
+ process.stdout.write(`${label}\n`);
261
+ const result = spawn("sh", ["-lc", command], {
262
+ cwd,
263
+ stdio: "inherit"
264
+ });
265
+ if (result.status !== 0) process.exit(result.status ?? 1);
266
+ }
267
+ async function readHookStdin() {
268
+ if (process.stdin.isTTY) return "";
269
+ process.stdin.setEncoding("utf8");
270
+ let output = "";
271
+ try {
272
+ for await (const chunk of process.stdin) output += chunk;
273
+ } catch (error) {
274
+ if (error.code !== "EAGAIN") throw error;
275
+ }
276
+ return output.trim();
277
+ }
278
+ function hasTypecheckScript(dir) {
279
+ const packageJsonPath = path$1.join(dir, "package.json");
280
+ if (!fs.existsSync(packageJsonPath)) return false;
281
+ try {
282
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
283
+ return typeof packageJson.scripts?.typecheck === "string" && packageJson.scripts.typecheck.length > 0;
284
+ } catch {
285
+ return false;
286
+ }
287
+ }
288
+ function findRepositoryRoot(startDir) {
289
+ let current = path$1.resolve(startDir);
290
+ while (true) {
291
+ if (fs.existsSync(path$1.join(current, gitDirName))) return current;
292
+ const next = path$1.dirname(current);
293
+ if (next === current) return path$1.resolve(startDir);
294
+ current = next;
295
+ }
296
+ }
297
+ function resolveTypecheckWorkspaceDir(filePath, cwd) {
298
+ const workspaceRoot = findRepositoryRoot(cwd);
299
+ let current = path$1.dirname(path$1.resolve(cwd, filePath));
300
+ while (current.startsWith(workspaceRoot)) {
301
+ if (current !== cwd && hasTypecheckScript(current)) return current;
302
+ const next = path$1.dirname(current);
303
+ if (next === current) break;
304
+ current = next;
305
+ }
306
+ return workspaceRoot;
307
+ }
308
+ /**
309
+ * 执行 pre-push 校验。
310
+ *
311
+ * 该函数会根据 push 范围内的改动文件,推导需要运行的 workspace 任务:
312
+ * - workspace 内改动:按包执行 `build` / `test` / `tsd`
313
+ * - 根级配置改动:在仓库根执行 `build` / `test` / `tsd`
314
+ * - 无论改动范围如何,都会强制在仓库根执行整仓 `lint` 与 `typecheck`
315
+ *
316
+ * @param options pre-push 运行参数
317
+ * @returns Promise<void>
318
+ */
319
+ async function verifyPrePush(options = {}) {
320
+ const cwd = options.cwd ?? process.cwd();
321
+ const execFile = options.execFile ?? execFileSync;
322
+ const spawn = options.spawn ?? spawnSync;
323
+ const workspaces = options.workspaces ?? defaultWorkspaceOrder;
324
+ const hookStdin = options.stdinText ?? await readHookStdin();
325
+ const hookLines = hookStdin.length > 0 ? hookStdin.split("\n") : [];
326
+ const tasksByWorkspace = /* @__PURE__ */ new Map();
327
+ const rootTasks = new Set(["lint", "typecheck"]);
328
+ for (const line of hookLines) {
329
+ const [, localSha, , remoteSha] = line.trim().split(whitespacePattern);
330
+ if (!localSha || localSha === zeroSha) continue;
331
+ const changedFiles = remoteSha && remoteSha !== zeroSha ? getChangedFilesForRange(remoteSha, localSha, cwd, execFile) : getChangedFilesForNewRemote(localSha, cwd, execFile);
332
+ for (const file of changedFiles) {
333
+ const workspace = resolveWorkspaceDir(file, workspaces);
334
+ if (workspace) {
335
+ const tasks = tasksByWorkspace.get(workspace) ?? /* @__PURE__ */ new Set();
336
+ tasks.add("build");
337
+ tasks.add("test");
338
+ tasks.add("tsd");
339
+ tasksByWorkspace.set(workspace, tasks);
340
+ continue;
341
+ }
342
+ for (const task of getRootLevelTasksForFile(file)) rootTasks.add(task);
343
+ }
344
+ }
345
+ for (const [workspace, tasks] of tasksByWorkspace) {
346
+ const scripts = getPackageScripts(workspace, cwd);
347
+ for (const task of [...tasks]) if (typeof scripts[task] !== "string" || scripts[task].length === 0) tasks.delete(task);
348
+ }
349
+ if (tasksByWorkspace.size === 0 && rootTasks.size === 0) return;
350
+ for (const [workspace, tasks] of [...tasksByWorkspace.entries()].sort(([left], [right]) => left.localeCompare(right))) for (const task of [
351
+ "build",
352
+ "test",
353
+ "tsd"
354
+ ]) {
355
+ if (!tasks.has(task)) continue;
356
+ runPnpmCommand(cwd, `[pre-push:${task}] ${workspace}`, [
357
+ "--dir",
358
+ workspace,
359
+ task
360
+ ], spawn);
361
+ }
362
+ for (const task of [
363
+ "lint",
364
+ "typecheck",
365
+ "build",
366
+ "test",
367
+ "tsd"
368
+ ]) {
369
+ if (!rootTasks.has(task)) continue;
370
+ runPnpmCommand(cwd, `[pre-push:${task}] .`, [task], spawn);
371
+ }
372
+ }
373
+ /**
374
+ * 对暂存区中涉及类型检查的文件,按最近的 workspace 归属执行 `typecheck`。
375
+ *
376
+ * 当前识别的扩展名:`.ts`、`.tsx`、`.mts`、`.cts`、`.vue`。
377
+ *
378
+ * @param stagedFiles 暂存区文件路径列表
379
+ * @param options 运行参数
380
+ */
381
+ function verifyStagedTypecheck(stagedFiles, options = {}) {
382
+ const cwd = options.cwd ?? process.cwd();
383
+ const spawn = options.spawn ?? spawnSync;
384
+ const workspaceDirs = [...new Set(stagedFiles.filter((file) => typecheckExtensions.has(path$1.extname(file))).map((file) => resolveTypecheckWorkspaceDir(file, cwd)))];
385
+ if (workspaceDirs.length === 0) return;
386
+ for (const workspaceDir of workspaceDirs) runPnpmCommand(cwd, `[lint-staged:typecheck] ${path$1.relative(cwd, workspaceDir) || "."}`, [
387
+ "--dir",
388
+ workspaceDir,
389
+ "typecheck"
390
+ ], spawn);
391
+ }
392
+ /**
393
+ * 执行 commit-msg 校验。
394
+ *
395
+ * 优先读取 `tooling.husky.commitMsgCommand`;若未配置,则回退到
396
+ * `pnpm exec commitlint --edit <editFile>`。
397
+ *
398
+ * @param options commit-msg 运行参数
399
+ */
400
+ async function verifyCommitMsg(options) {
401
+ const cwd = options.cwd ?? process.cwd();
402
+ const spawn = options.spawn ?? spawnSync;
403
+ const command = (await resolveToolingConfig(cwd)).husky?.commitMsgCommand?.replaceAll("{editFile}", options.editFile);
404
+ if (command) {
405
+ runShellCommand(cwd, `[commit-msg] ${options.editFile}`, command, spawn);
406
+ return;
407
+ }
408
+ runPnpmCommand(cwd, `[commit-msg] ${options.editFile}`, [
409
+ "exec",
410
+ "commitlint",
411
+ "--edit",
412
+ options.editFile
413
+ ], spawn);
414
+ }
415
+ /**
416
+ * 执行 pre-commit 校验。
417
+ *
418
+ * 优先读取 `tooling.husky.preCommitCommand`;若未配置,则回退到
419
+ * `pnpm exec lint-staged`。
420
+ *
421
+ * @param options pre-commit 运行参数
422
+ */
423
+ async function verifyPreCommit(options = {}) {
424
+ const cwd = options.cwd ?? process.cwd();
425
+ const spawn = options.spawn ?? spawnSync;
426
+ const command = (await resolveToolingConfig(cwd)).husky?.preCommitCommand;
427
+ if (command) {
428
+ runShellCommand(cwd, "[pre-commit] lint-staged", command, spawn);
429
+ return;
430
+ }
431
+ runPnpmCommand(cwd, "[pre-commit] lint-staged", ["exec", "lint-staged"], spawn);
432
+ }
433
+ //#endregion
434
+ //#region src/commands/check.ts
435
+ function resolveRecommendedCheckPlan(options) {
436
+ const { cwd, full, staged, editFile } = options;
437
+ if (editFile) return {
438
+ cwd,
439
+ mode: "commit-msg",
440
+ commands: [{
441
+ name: "commit-msg",
442
+ command: `repo verify commit-msg ${editFile}`,
443
+ description: "校验 commit message 文件是否符合提交规范。"
444
+ }]
445
+ };
446
+ if (full) return {
447
+ cwd,
448
+ mode: "full",
449
+ commands: [{
450
+ name: "pre-push",
451
+ command: "repo verify pre-push",
452
+ description: "执行完整 pre-push 校验,包含整仓 lint/typecheck,并按变更范围运行 build/test/tsd。"
453
+ }]
454
+ };
455
+ if (staged) return {
456
+ cwd,
457
+ mode: "staged",
458
+ commands: [{
459
+ name: "pre-commit",
460
+ command: "repo verify pre-commit",
461
+ description: "执行 pre-commit 校验。"
462
+ }, {
463
+ name: "staged-typecheck",
464
+ command: "repo verify staged-typecheck <staged files>",
465
+ description: "按暂存 TypeScript/Vue 文件所在 workspace 路由 typecheck。"
466
+ }]
467
+ };
468
+ return {
469
+ cwd,
470
+ mode: "default",
471
+ commands: [{
472
+ name: "pre-commit",
473
+ command: "repo verify pre-commit",
474
+ description: "执行默认轻量本地校验。"
475
+ }]
476
+ };
477
+ }
478
+ function getKnownRepoCheckCommands() {
479
+ return new Set([
480
+ "repo verify pre-commit",
481
+ "repo verify pre-push",
482
+ "repo verify staged-typecheck",
483
+ "repo verify commit-msg"
484
+ ]);
485
+ }
486
+ function hasRootScript(pkgJson, name) {
487
+ return typeof pkgJson.scripts?.[name] === "string" && pkgJson.scripts[name].length > 0;
488
+ }
489
+ async function readRootScripts(cwd) {
490
+ const pkgJsonPath = `${cwd}/package.json`;
491
+ if (!await fs$1.pathExists(pkgJsonPath)) return {};
492
+ return (await fs$1.readJson(pkgJsonPath)).scripts ?? {};
493
+ }
494
+ async function resolveFullWorkspaceCheckPlan(cwd) {
495
+ const scripts = await readRootScripts(cwd);
496
+ return {
497
+ cwd,
498
+ mode: "full",
499
+ commands: [
500
+ "lint",
501
+ "typecheck",
502
+ "test",
503
+ "build"
504
+ ].filter((name) => hasRootScript({ scripts }, name)).map((name) => ({
505
+ name,
506
+ command: `pnpm ${name}`,
507
+ description: `运行根 package.json 的 ${name} 脚本。`,
508
+ available: true
509
+ }))
510
+ };
511
+ }
512
+ async function runFullWorkspaceCheck(cwd, spawn = spawnSync) {
513
+ const plan = await resolveFullWorkspaceCheckPlan(cwd);
514
+ for (const command of plan.commands) {
515
+ process.stdout.write(`[check:${command.name}] .\n`);
516
+ const result = spawn("pnpm", [command.name], {
517
+ cwd,
518
+ stdio: "inherit"
519
+ });
520
+ if (result.status !== 0) process.exit(result.status ?? 1);
521
+ }
522
+ }
523
+ async function runRecommendedCheck(options) {
524
+ const { cwd, full, staged, editFile, spawn } = options;
525
+ if (editFile) {
526
+ await verifyCommitMsg({
527
+ cwd,
528
+ editFile
529
+ });
530
+ return;
531
+ }
532
+ if (full) {
533
+ await runFullWorkspaceCheck(cwd, spawn);
534
+ return;
535
+ }
536
+ if (staged) {
537
+ await verifyPreCommit({ cwd });
538
+ verifyStagedTypecheck([], { cwd });
539
+ return;
540
+ }
541
+ await verifyPreCommit({ cwd });
542
+ }
543
+ //#endregion
544
+ //#region src/utils/github.ts
545
+ /**
546
+ * 将 Issue 模版里的 discussions 链接同步为当前仓库的 discussions 地址。
547
+ */
548
+ function updateIssueTemplateConfig(source, repoName) {
549
+ if (!repoName) return source;
550
+ let doc;
551
+ try {
552
+ doc = parseDocument(source);
553
+ } catch {
554
+ return source;
555
+ }
556
+ const contactLinks = doc.get("contact_links");
557
+ if (!isSeq(contactLinks)) return source;
558
+ const nextUrl = `https://github.com/${repoName}/discussions`;
559
+ let changed = false;
560
+ contactLinks.items.forEach((_, index) => {
561
+ const url = doc.getIn([
562
+ "contact_links",
563
+ index,
564
+ "url"
565
+ ]);
566
+ if (typeof url !== "string") return;
567
+ if (!url.includes("/discussions")) return;
568
+ if (url === nextUrl) return;
569
+ doc.setIn([
570
+ "contact_links",
571
+ index,
572
+ "url"
573
+ ], nextUrl);
574
+ changed = true;
575
+ });
576
+ if (!changed) return source;
577
+ return doc.toString();
578
+ }
579
+ //#endregion
580
+ //#region src/utils/hash.ts
581
+ /**
582
+ * 生成给定内容的 md5 摘要。
583
+ *
584
+ * @param data 任意 `crypto.BinaryLike` 内容
585
+ * @returns 32 位十六进制 md5 字符串
586
+ */
587
+ function getFileHash(data) {
588
+ const hashSum = crypto.createHash("md5");
589
+ hashSum.update(data);
590
+ return hashSum.digest("hex");
591
+ }
592
+ /**
593
+ * 对比两段内容的 md5,判断内容是否发生变化。
594
+ *
595
+ * @param src 当前内容
596
+ * @param dest 旧内容
597
+ * @returns 两者 md5 不一致时返回 `true`
598
+ */
599
+ function isFileChanged(src, dest) {
600
+ try {
601
+ return getFileHash(src) !== getFileHash(dest);
602
+ } catch (err) {
603
+ logger.error("Error calculating file hash:", err);
604
+ return false;
605
+ }
606
+ }
607
+ //#endregion
608
+ //#region src/utils/object.ts
609
+ const arrayIndexPattern = /^\d+$/;
610
+ function isArrayIndex(value) {
611
+ return arrayIndexPattern.test(value);
612
+ }
613
+ function parsePath(input) {
614
+ const segments = [];
615
+ let current = "";
616
+ let escaped = false;
617
+ for (const char of input) {
618
+ if (escaped) {
619
+ current += char;
620
+ escaped = false;
621
+ continue;
622
+ }
623
+ if (char === "\\") {
624
+ escaped = true;
625
+ continue;
626
+ }
627
+ if (char === ".") {
628
+ segments.push(current);
629
+ current = "";
630
+ continue;
631
+ }
632
+ current += char;
633
+ }
634
+ segments.push(current);
635
+ return segments;
636
+ }
637
+ function setByPath(target, path, value) {
638
+ const segments = typeof path === "string" ? parsePath(path) : [...path];
639
+ if (!segments.length) return target;
640
+ let current = target;
641
+ for (let index = 0; index < segments.length - 1; index++) {
642
+ const segment = segments[index];
643
+ const nextSegment = segments[index + 1];
644
+ const key = Array.isArray(current) && isArrayIndex(segment) ? Number(segment) : segment;
645
+ const existing = current[key];
646
+ if (typeof existing !== "object" || existing === null) current[key] = isArrayIndex(nextSegment) ? [] : {};
647
+ current = current[key];
648
+ }
649
+ const lastSegment = segments.at(-1);
650
+ const lastKey = Array.isArray(current) && isArrayIndex(lastSegment) ? Number(lastSegment) : lastSegment;
651
+ current[lastKey] = value;
652
+ return target;
653
+ }
654
+ //#endregion
655
+ //#region src/utils/regexp.ts
656
+ const regexpSpecialCharacterPattern = /[|\\{}()[\]^$+*?.]/g;
657
+ const hyphenPattern = /-/g;
658
+ /**
659
+ * 逃逸正则表达式中所有特殊字符,避免被当做模式解析。
660
+ */
661
+ function escapeStringRegexp(str) {
662
+ return str.replace(regexpSpecialCharacterPattern, "\\$&").replace(hyphenPattern, "\\x2d");
663
+ }
664
+ /**
665
+ * 判断字符串是否命中任意一个正则,用于过滤要同步的资产文件。
666
+ */
667
+ function isMatch(str, arr) {
668
+ for (const reg of arr) if (reg.test(str)) return true;
669
+ return false;
670
+ }
671
+ //#endregion
672
+ //#region src/commands/skills.ts
673
+ /**
674
+ * 内置 skills 目录名称。
675
+ */
676
+ const skillName = "icebreakers-monorepo-cli";
677
+ /**
678
+ * 当前支持的 skills 同步目标。
679
+ */
680
+ const skillTargets = ["codex", "claude"];
681
+ /**
682
+ * 包内 skills 模板源目录。
683
+ */
684
+ const skillSourceDir = path.join(packageDir, "resources", "skills", skillName);
685
+ /**
686
+ * 计算各个目标平台的 skills 安装路径。
687
+ *
688
+ * @param homeDir 用户 home 目录,默认取 `os.homedir()`
689
+ */
690
+ function getSkillTargetPaths(homeDir = os.homedir()) {
691
+ return {
692
+ codex: path.join(homeDir, ".codex", "skills", skillName),
693
+ claude: path.join(homeDir, ".claude", "skills", skillName)
694
+ };
695
+ }
696
+ function normalizeTargets(values) {
697
+ if (!values?.length) return;
698
+ return [...new Set(values)];
699
+ }
700
+ /**
701
+ * 将内置 skills 同步到一个或多个目标平台目录。
702
+ *
703
+ * @param options 同步选项
704
+ * @returns 成功同步的目标及落盘路径列表
705
+ */
706
+ async function syncSkills(options = {}) {
707
+ const cwd = options.cwd ?? process.cwd();
708
+ if (!await fs$1.pathExists(skillSourceDir)) {
709
+ const relative = path.relative(cwd, skillSourceDir);
710
+ throw new Error(`未找到技能目录:${relative || skillSourceDir}`);
711
+ }
712
+ let targets = normalizeTargets(options.targets);
713
+ if (!targets?.length) targets = normalizeTargets(await checkbox({
714
+ message: "请选择需要同步的技能目标",
715
+ choices: skillTargets.map((target) => ({
716
+ name: target,
717
+ value: target,
718
+ checked: true
719
+ }))
720
+ }));
721
+ if (!targets?.length) return [];
722
+ const targetPaths = getSkillTargetPaths();
723
+ const results = [];
724
+ for (const target of targets) {
725
+ const dest = targetPaths[target];
726
+ await fs$1.remove(dest);
727
+ await fs$1.ensureDir(path.dirname(dest));
728
+ await fs$1.copy(skillSourceDir, dest);
729
+ results.push({
730
+ target,
731
+ dest
732
+ });
733
+ }
734
+ return results;
735
+ }
736
+ //#endregion
737
+ //#region src/commands/clean.ts
738
+ const preferredPackageNames = ["repoctl", "@icebreakers/monorepo"];
739
+ function resolvePreferredToolPackageName$1(pkgJson) {
740
+ const devDependencies = pkgJson["devDependencies"];
741
+ if (!devDependencies || typeof devDependencies !== "object") return "repoctl";
742
+ for (const packageName of preferredPackageNames) if (Object.hasOwn(devDependencies, packageName)) return packageName;
743
+ return "repoctl";
744
+ }
745
+ function mergeCleanConfig(base, overrides) {
746
+ const normalizedBase = base ?? {};
747
+ if (!overrides) return normalizedBase;
748
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== void 0));
749
+ return {
750
+ ...normalizedBase,
751
+ ...definedOverrides
752
+ };
753
+ }
754
+ /**
755
+ * 交互式清理被选中的包目录,同时重写根 package.json 中的 @icebreakers/monorepo 版本。
756
+ */
757
+ async function cleanProjects(cwd, overrides) {
758
+ const cleanConfig = mergeCleanConfig(await resolveCommandConfig("clean", cwd), overrides);
759
+ const { packages, workspaceDir } = await getWorkspaceData(cwd, cleanConfig?.includePrivate ?? true ? { ignorePrivatePackage: false } : void 0);
760
+ const filteredPackages = packages.filter((pkg) => {
761
+ const name = pkg.manifest.name ?? "";
762
+ if (!name) return true;
763
+ if (!cleanConfig?.ignorePackages?.length) return true;
764
+ return !cleanConfig.ignorePackages.includes(name);
765
+ });
766
+ let cleanDirs = [];
767
+ if (cleanConfig?.autoConfirm) cleanDirs = filteredPackages.map((pkg) => pkg.rootDir);
768
+ else cleanDirs = await checkbox({
769
+ message: "请选择需要清理的目录",
770
+ choices: filteredPackages.map((x) => {
771
+ const baseChoice = {
772
+ name: path.relative(workspaceDir, x.rootDir),
773
+ value: x.rootDir,
774
+ checked: true
775
+ };
776
+ return x.manifest.name ? {
777
+ ...baseChoice,
778
+ description: x.manifest.name
779
+ } : baseChoice;
780
+ })
781
+ });
782
+ const readmeZh = path.resolve(workspaceDir, "README.zh-CN.md");
783
+ const qoderDir = path.resolve(workspaceDir, ".qoder");
784
+ const docsPlansDir = path.resolve(workspaceDir, "docs/plans");
785
+ const skillTargets = Object.values(getSkillTargetPaths());
786
+ const candidates = [...new Set([
787
+ ...cleanDirs.filter(Boolean),
788
+ readmeZh,
789
+ qoderDir,
790
+ docsPlansDir,
791
+ ...skillTargets
792
+ ])];
793
+ await Promise.all(candidates.map(async (dir) => {
794
+ if (await fs$1.pathExists(dir)) await fs$1.remove(dir);
795
+ }));
796
+ const name = path.resolve(workspaceDir, "package.json");
797
+ const pkgJson = await fs$1.readJson(name);
798
+ setByPath(pkgJson, `devDependencies.${resolvePreferredToolPackageName$1(pkgJson).replaceAll(".", "\\.")}`, cleanConfig?.pinnedVersion ?? "latest");
799
+ await fs$1.outputJson(name, pkgJson, { spaces: 2 });
800
+ }
801
+ //#endregion
802
+ //#region src/commands/config.ts
803
+ async function inspectMonorepoConfig(cwd) {
804
+ const { file, config } = await loadMonorepoConfigDetails(cwd);
805
+ return {
806
+ cwd,
807
+ file,
808
+ config
809
+ };
810
+ }
811
+ //#endregion
812
+ //#region src/commands/tooling-migration.ts
813
+ const legacyToolingLoaderImportPattern = /import\s+\{\s*load(?:Repoctl|Monorepo)ToolingModule\s*\}\s+from\s+['"][^'"]*tooling\/load-tooling-module\.mjs['"]\s*;?\n?/g;
814
+ const legacyToolingLoaderCallPattern = /const\s+\{\s*([\w$]+(?:\s*,\s*[\w$]+)*)\s*\}\s*=\s*await\s+load(?:Repoctl|Monorepo)ToolingModule\(\)\s*;?\n?/g;
815
+ const legacyToolingEntryPattern = /packages\/(?:monorepo|repoctl)\/dist\/tooling-entry\.mjs/;
816
+ function normalizeNamedImports(input) {
817
+ return [...new Set(input.split(",").map((item) => item.trim()).filter(Boolean))].sort((left, right) => left.localeCompare(right));
818
+ }
819
+ function hasLegacyToolingReference(content) {
820
+ return content.includes("tooling/load-tooling-module.mjs") || content.includes("loadRepoctlToolingModule") || content.includes("loadMonorepoToolingModule") || legacyToolingEntryPattern.test(content);
821
+ }
822
+ function migrateLegacyToolingReferences(content, importSource = "repoctl/tooling") {
823
+ if (!hasLegacyToolingReference(content)) return content;
824
+ const importNames = [];
825
+ let nextContent = content.replace(legacyToolingLoaderCallPattern, (_match, imports) => {
826
+ importNames.push(...normalizeNamedImports(imports));
827
+ return "";
828
+ });
829
+ if (importNames.length === 0) return nextContent.replace(legacyToolingLoaderImportPattern, "").replace(/\n{3,}/g, "\n\n");
830
+ nextContent = nextContent.replace(legacyToolingLoaderImportPattern, "");
831
+ return `${`import { ${normalizeNamedImports(importNames.join(",")).join(", ")} } from '${importSource}'\n`}${nextContent}`.replace(/\n{3,}/g, "\n\n").trimStart();
832
+ }
833
+ //#endregion
834
+ //#region src/commands/create/plan.ts
835
+ /**
836
+ * 内置模板映射表,source 指向 templates 根目录下的来源目录,target 为生成路径。
837
+ */
838
+ const templateMap = {
839
+ "tsdown": {
840
+ source: "tsdown",
841
+ target: "packages/tsdown"
842
+ },
843
+ "vue-lib": {
844
+ source: "vue-lib",
845
+ target: "packages/vue-lib"
846
+ },
847
+ "hono-server": {
848
+ source: "server",
849
+ target: "apps/server"
850
+ },
851
+ "vue-hono": {
852
+ source: "client",
853
+ target: "apps/client"
854
+ },
855
+ "vitepress": {
856
+ source: "vitepress",
857
+ target: "apps/website"
858
+ },
859
+ "cli": {
860
+ source: "cli",
861
+ target: "apps/cli"
862
+ }
863
+ };
864
+ /**
865
+ * `createNewProject()` 默认使用的模板类型。
866
+ * @default 'tsdown'
867
+ */
868
+ const defaultTemplate = "tsdown";
869
+ const baseChoices = templateChoices.map((choice) => {
870
+ const option = {
871
+ name: choice.label,
872
+ value: choice.key
873
+ };
874
+ if (choice.description) option.description = choice.description;
875
+ return option;
876
+ });
877
+ function normalizeTemplateDefinition(value) {
878
+ if (typeof value === "string") return {
879
+ source: value,
880
+ target: value
881
+ };
882
+ return value;
883
+ }
884
+ function formatUnknownTemplateError(template, availableTemplates) {
885
+ const suggestion = suggestTemplateKey(template, { keys: availableTemplates });
886
+ return `未知模板:${template}。${suggestion ? `你是不是想用 ${suggestion}? ` : ""}可用模板:${availableTemplates.join(", ")}`;
887
+ }
888
+ function getCreateChoices(choices) {
889
+ if (choices?.length) return choices;
890
+ return [...baseChoices];
891
+ }
892
+ function getTemplateMap(extra) {
893
+ const base = Object.fromEntries(Object.entries(templateMap).map(([key, value]) => [key, normalizeTemplateDefinition(value)]));
894
+ if (extra && Object.keys(extra).length) for (const [key, value] of Object.entries(extra)) base[key] = normalizeTemplateDefinition(value);
895
+ return base;
896
+ }
897
+ async function resolveCreateNewProjectPlan(options) {
898
+ const cwd = options?.cwd ?? process.cwd();
899
+ const createConfig = await resolveCommandConfig("create", cwd);
900
+ const renameJson = options?.renameJson ?? createConfig?.renameJson ?? false;
901
+ const rawName = options?.name ?? createConfig?.name;
902
+ const name = typeof rawName === "string" ? rawName.trim() : void 0;
903
+ const requestedTemplate = options?.type ?? createConfig?.type ?? createConfig?.defaultTemplate ?? "tsdown";
904
+ const templateDefinitions = getTemplateMap(createConfig?.templateMap);
905
+ const templatesRoot = createConfig?.templatesDir ? path.resolve(cwd, createConfig.templatesDir) : templatesDir;
906
+ const requestedTemplateName = String(requestedTemplate);
907
+ const availableTemplates = Object.keys(templateDefinitions).sort();
908
+ if (!templateDefinitions[requestedTemplateName]) throw new Error(formatUnknownTemplateError(requestedTemplateName, availableTemplates));
909
+ const template = requestedTemplateName;
910
+ const templateDefinition = templateDefinitions[template];
911
+ if (!templateDefinition) throw new Error(`未找到名为 ${template} 的模板,请检查 repoctl.config.ts 或 monorepo.config.ts`);
912
+ const sourceDir = path.join(templatesRoot, templateDefinition.source);
913
+ const targetName = name && name.length > 0 ? name : templateDefinition.target;
914
+ const targetDir = path.join(cwd, targetName);
915
+ const sourceJsonPath = path.resolve(sourceDir, "package.json");
916
+ const hasPackageJson = await fs$1.pathExists(sourceJsonPath);
917
+ const packageJsonFileName = renameJson ? "package.mock.json" : "package.json";
918
+ const packageName = name?.startsWith("@") ? name : path.basename(targetName);
919
+ return {
920
+ cwd,
921
+ requestedTemplate: requestedTemplateName,
922
+ template,
923
+ usedFallback: requestedTemplateName !== template,
924
+ sourceDir,
925
+ targetName,
926
+ targetDir,
927
+ targetExists: await fs$1.pathExists(targetDir),
928
+ renameJson,
929
+ hasPackageJson,
930
+ packageJsonFileName,
931
+ packageName,
932
+ templateDefinition
933
+ };
934
+ }
935
+ //#endregion
936
+ //#region src/commands/create/index.ts
937
+ const rootReferenceExtensions = new Set([
938
+ ".cjs",
939
+ ".cts",
940
+ ".js",
941
+ ".json",
942
+ ".mjs",
943
+ ".mts",
944
+ ".ts"
945
+ ]);
946
+ const rootReferenceReplacements = [{
947
+ from: "../../tsconfig.json",
948
+ to: "tsconfig.json"
949
+ }];
950
+ async function applyGitMetadata(pkgJson, repoDir, targetDir) {
951
+ try {
952
+ const git = new GitClient({ baseDir: repoDir });
953
+ const repoName = await git.getRepoName();
954
+ if (!repoName) return;
955
+ setByPath(pkgJson, ["bugs", "url"], `https://github.com/${repoName}/issues`);
956
+ const repository = {
957
+ type: "git",
958
+ url: `git+https://github.com/${repoName}.git`
959
+ };
960
+ const directoryBase = await git.getRepoRoot() ?? repoDir;
961
+ const relative = path.relative(directoryBase, targetDir);
962
+ if (relative && relative !== ".") repository.directory = relative.split(path.sep).join("/");
963
+ setByPath(pkgJson, "repository", repository);
964
+ const gitUser = await git.getUser();
965
+ if (gitUser?.name && gitUser?.email) setByPath(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
966
+ } catch {}
967
+ }
968
+ function sanitizeTemplatePackageJson(pkgJson) {
969
+ delete pkgJson.author;
970
+ delete pkgJson.bugs;
971
+ delete pkgJson.homepage;
972
+ delete pkgJson.repository;
973
+ }
974
+ function normalizeRelativeSpecifier(fromDir, targetPath) {
975
+ const relativePath = path.relative(fromDir, targetPath).split(path.sep).join("/");
976
+ if (relativePath.startsWith(".")) return relativePath;
977
+ return `./${relativePath}`;
978
+ }
979
+ async function rewriteTemplateRootReferences(targetDir, workspaceDir) {
980
+ let entries;
981
+ try {
982
+ entries = await readdir(targetDir, { withFileTypes: true });
983
+ } catch (error) {
984
+ if (error.code === "ENOENT") return;
985
+ throw error;
986
+ }
987
+ await Promise.all(entries.map(async (entry) => {
988
+ const entryPath = path.join(targetDir, entry.name);
989
+ if (entry.isDirectory()) {
990
+ await rewriteTemplateRootReferences(entryPath, workspaceDir);
991
+ return;
992
+ }
993
+ if (!entry.isFile() || !rootReferenceExtensions.has(path.extname(entry.name))) return;
994
+ const originalContent = await fs$1.readFile(entryPath, "utf8");
995
+ let nextContent = migrateLegacyToolingReferences(originalContent, "repoctl/tooling");
996
+ for (const replacement of rootReferenceReplacements) {
997
+ if (!nextContent.includes(replacement.from)) continue;
998
+ const targetPath = path.join(workspaceDir, replacement.to);
999
+ const rewrittenSpecifier = normalizeRelativeSpecifier(path.dirname(entryPath), targetPath);
1000
+ nextContent = nextContent.replaceAll(replacement.from, rewrittenSpecifier);
1001
+ }
1002
+ if (nextContent !== originalContent) await fs$1.writeFile(entryPath, nextContent, "utf8");
1003
+ }));
1004
+ }
1005
+ function inferWorkspacePattern(targetName) {
1006
+ const parts = targetName.split(path.sep).join("/").split("/").filter(Boolean);
1007
+ if (parts.length >= 2) return `${parts[0]}/*`;
1008
+ return "packages/*";
1009
+ }
1010
+ async function updateWorkspaceManifest(workspaceDir, targetName) {
1011
+ const workspacePath = path.resolve(workspaceDir, "pnpm-workspace.yaml");
1012
+ const manifest = await fs$1.pathExists(workspacePath) ? YAML.parse(await fs$1.readFile(workspacePath, "utf8")) ?? {} : {};
1013
+ const currentPackages = Array.isArray(manifest.packages) ? manifest.packages.filter((item) => typeof item === "string") : [];
1014
+ const pattern = inferWorkspacePattern(targetName);
1015
+ if (currentPackages.includes(pattern)) return;
1016
+ const nextManifest = {
1017
+ ...typeof manifest === "object" && manifest !== null ? manifest : {},
1018
+ packages: [...currentPackages, pattern]
1019
+ };
1020
+ await fs$1.outputFile(workspacePath, YAML.stringify(nextManifest, { singleQuote: true }), "utf8");
1021
+ }
1022
+ /**
1023
+ * 根据模板生成一个新项目目录,并自动补写 `package.json` 常用字段。
1024
+ *
1025
+ * 默认行为:
1026
+ * - 优先读取 `repoctl.config.ts -> commands.create`,兼容 `monorepo.config.ts`
1027
+ * - 模板类型默认回退到 `'tsdown'`
1028
+ * - 若目标目录已存在则直接抛错
1029
+ * - 若模板包含 `package.json`,会自动写入 `name`、`version` 与 Git 仓库信息
1030
+ *
1031
+ * @param options 运行时覆盖项
1032
+ * @returns Promise<void>
1033
+ */
1034
+ async function createNewProject(options) {
1035
+ const plan = await resolveCreateNewProjectPlan(options);
1036
+ if (plan.targetExists) throw new Error(`${pc.red("目标目录已存在")}: ${path.relative(plan.cwd, plan.targetDir)}`);
1037
+ await fs$1.ensureDir(plan.targetDir);
1038
+ await scaffoldTemplate({
1039
+ sourceDir: plan.sourceDir,
1040
+ targetDir: plan.targetDir,
1041
+ skipRootBasenames: ["package.json"]
1042
+ });
1043
+ await rewriteTemplateRootReferences(plan.targetDir, plan.cwd);
1044
+ if (plan.hasPackageJson) {
1045
+ const sourceJson = await fs$1.readJson(path.resolve(plan.sourceDir, "package.json"));
1046
+ sanitizeTemplatePackageJson(sourceJson);
1047
+ setByPath(sourceJson, "version", "0.0.0");
1048
+ setByPath(sourceJson, "name", plan.packageName);
1049
+ await applyGitMetadata(sourceJson, plan.cwd, plan.targetDir);
1050
+ await fs$1.outputJson(path.resolve(plan.targetDir, plan.packageJsonFileName), sourceJson, { spaces: 2 });
1051
+ }
1052
+ await updateWorkspaceManifest(plan.cwd, plan.targetName);
1053
+ logger.success(`${pc.bgGreenBright(pc.white(`[${plan.template}]`))} ${plan.targetName} 项目创建成功!`);
1054
+ }
1055
+ //#endregion
1056
+ //#region src/commands/doctor.ts
1057
+ function createCheck(check) {
1058
+ return check;
1059
+ }
1060
+ function summarizeChecks(checks) {
1061
+ return checks.reduce((summary, check) => {
1062
+ summary[check.status] += 1;
1063
+ return summary;
1064
+ }, {
1065
+ pass: 0,
1066
+ warn: 0,
1067
+ fail: 0
1068
+ });
1069
+ }
1070
+ function resolveToolPackageName(pkgJson) {
1071
+ return [
1072
+ typeof pkgJson.devDependencies?.["repoctl"] === "string" ? {
1073
+ name: "repoctl",
1074
+ version: pkgJson.devDependencies["repoctl"]
1075
+ } : null,
1076
+ typeof pkgJson.devDependencies?.["@icebreakers/monorepo"] === "string" ? {
1077
+ name: "@icebreakers/monorepo",
1078
+ version: pkgJson.devDependencies["@icebreakers/monorepo"]
1079
+ } : null,
1080
+ typeof pkgJson.dependencies?.["repoctl"] === "string" ? {
1081
+ name: "repoctl",
1082
+ version: pkgJson.dependencies["repoctl"]
1083
+ } : null,
1084
+ typeof pkgJson.dependencies?.["@icebreakers/monorepo"] === "string" ? {
1085
+ name: "@icebreakers/monorepo",
1086
+ version: pkgJson.dependencies["@icebreakers/monorepo"]
1087
+ } : null
1088
+ ].find((value) => value !== null) ?? null;
1089
+ }
1090
+ function hasScript(pkgJson, name) {
1091
+ return typeof pkgJson.scripts?.[name] === "string" && pkgJson.scripts[name].length > 0;
1092
+ }
1093
+ function getWorkspacePatterns(manifest) {
1094
+ if (typeof manifest !== "object" || manifest === null) return [];
1095
+ const packages = manifest.packages;
1096
+ return Array.isArray(packages) ? packages.filter((item) => typeof item === "string") : [];
1097
+ }
1098
+ function isWorkspacePatternCovered(relativeDir, patterns) {
1099
+ const normalized = relativeDir.split("\\").join("/");
1100
+ return patterns.some((pattern) => {
1101
+ if (pattern.startsWith("!")) return false;
1102
+ if (pattern.endsWith("/*")) {
1103
+ const base = pattern.slice(0, -2);
1104
+ return normalized.startsWith(`${base}/`) && normalized.slice(base.length + 1).split("/").length === 1;
1105
+ }
1106
+ if (pattern.endsWith("/**")) return normalized.startsWith(`${pattern.slice(0, -3)}/`);
1107
+ return normalized === pattern;
1108
+ });
1109
+ }
1110
+ async function isRepoctlSourceWorkspace(workspaceDir) {
1111
+ const [hasMonorepoSource, hasRepoctlSource] = await Promise.all([fs$1.pathExists(`${workspaceDir}/packages/monorepo/src/tooling/index.ts`), fs$1.pathExists(`${workspaceDir}/packages/repoctl/src/tooling-entry.ts`)]);
1112
+ return hasMonorepoSource && hasRepoctlSource;
1113
+ }
1114
+ async function findWorkspacePackageDirs(workspaceDir) {
1115
+ const result = [];
1116
+ for (const baseDir of [
1117
+ "apps",
1118
+ "packages",
1119
+ "examples"
1120
+ ]) {
1121
+ const absBaseDir = `${workspaceDir}/${baseDir}`;
1122
+ if (!await fs$1.pathExists(absBaseDir)) continue;
1123
+ const entries = await readdir(absBaseDir);
1124
+ await Promise.all(entries.map(async (entry) => {
1125
+ const packageJsonPath = `${absBaseDir}/${entry}/package.json`;
1126
+ if (await fs$1.pathExists(packageJsonPath)) result.push(`${baseDir}/${entry}`);
1127
+ }));
1128
+ }
1129
+ return result.sort((left, right) => left.localeCompare(right));
1130
+ }
1131
+ async function runDoctor(cwd) {
1132
+ const workspaceDir = await findWorkspaceDir(cwd) ?? cwd;
1133
+ const packageJsonPath = `${workspaceDir}/package.json`;
1134
+ const workspaceManifestPath = `${workspaceDir}/pnpm-workspace.yaml`;
1135
+ const repoctlConfigPath = `${workspaceDir}/repoctl.config.ts`;
1136
+ const monorepoConfigPath = `${workspaceDir}/monorepo.config.ts`;
1137
+ const huskyPreCommitPath = `${workspaceDir}/.husky/pre-commit`;
1138
+ const lintStagedConfigPath = `${workspaceDir}/lint-staged.config.js`;
1139
+ const [hasPackageJson, hasWorkspaceManifest, hasRepoctlConfig, hasMonorepoConfig, hasHuskyPreCommit, hasLintStagedConfig] = await Promise.all([
1140
+ fs$1.pathExists(packageJsonPath),
1141
+ fs$1.pathExists(workspaceManifestPath),
1142
+ fs$1.pathExists(repoctlConfigPath),
1143
+ fs$1.pathExists(monorepoConfigPath),
1144
+ fs$1.pathExists(huskyPreCommitPath),
1145
+ fs$1.pathExists(lintStagedConfigPath)
1146
+ ]);
1147
+ const pkgJson = hasPackageJson ? await fs$1.readJson(packageJsonPath) : {};
1148
+ const packageCount = hasWorkspaceManifest ? (await getWorkspacePackages(workspaceDir, { ignorePrivatePackage: false })).length : 0;
1149
+ const workspacePatterns = hasWorkspaceManifest ? getWorkspacePatterns(YAML.parse(await fs$1.readFile(workspaceManifestPath, "utf8"))) : [];
1150
+ const workspacePackageDirs = hasWorkspaceManifest ? await findWorkspacePackageDirs(workspaceDir) : [];
1151
+ const isSourceWorkspace = await isRepoctlSourceWorkspace(workspaceDir);
1152
+ const checks = [hasPackageJson ? createCheck({
1153
+ id: "package-json",
1154
+ title: "package.json",
1155
+ status: "pass",
1156
+ detail: `已找到根 package.json:${packageJsonPath}`
1157
+ }) : createCheck({
1158
+ id: "package-json",
1159
+ title: "package.json",
1160
+ status: "fail",
1161
+ detail: "当前目录缺少根 package.json。",
1162
+ fix: "请在 monorepo 根目录执行命令,或先完成脚手架初始化。"
1163
+ }), hasWorkspaceManifest ? createCheck({
1164
+ id: "workspace-manifest",
1165
+ title: "pnpm workspace",
1166
+ status: "pass",
1167
+ detail: `已找到 pnpm workspace,当前识别到 ${packageCount} 个 workspace 包。`
1168
+ }) : createCheck({
1169
+ id: "workspace-manifest",
1170
+ title: "pnpm workspace",
1171
+ status: "fail",
1172
+ detail: "缺少 pnpm-workspace.yaml,当前目录不像一个完整的 pnpm monorepo 根目录。",
1173
+ fix: "运行 repo setup --yes 补充 pnpm-workspace.yaml,或确认你当前就在仓库根目录。"
1174
+ })];
1175
+ const nodeRange = pkgJson.engines?.node;
1176
+ if (typeof nodeRange === "string" && nodeRange.length > 0) checks.push(satisfies(process.version, nodeRange) ? createCheck({
1177
+ id: "node-version",
1178
+ title: "Node 版本",
1179
+ status: "pass",
1180
+ detail: `当前 Node 版本 ${process.version} 满足要求 ${nodeRange}。`
1181
+ }) : createCheck({
1182
+ id: "node-version",
1183
+ title: "Node 版本",
1184
+ status: "fail",
1185
+ detail: `当前 Node 版本 ${process.version} 不满足要求 ${nodeRange}。`,
1186
+ fix: "切换到 package.json -> engines.node 要求的版本后再执行 install / build / check。"
1187
+ }));
1188
+ else checks.push(createCheck({
1189
+ id: "node-version",
1190
+ title: "Node 版本",
1191
+ status: "warn",
1192
+ detail: "根 package.json 未声明 engines.node,无法自动校验 Node 版本。",
1193
+ fix: "建议补充 package.json -> engines.node,避免团队成员使用不一致的运行时。"
1194
+ }));
1195
+ const toolPackage = resolveToolPackageName(pkgJson);
1196
+ checks.push(toolPackage ? createCheck({
1197
+ id: "tool-package",
1198
+ title: "repo CLI 依赖",
1199
+ status: "pass",
1200
+ detail: `已检测到 CLI 工具依赖:${toolPackage.name}@${toolPackage.version}`
1201
+ }) : createCheck({
1202
+ id: "tool-package",
1203
+ title: "repo CLI 依赖",
1204
+ status: "fail",
1205
+ detail: "根 package.json 中未发现 repoctl 或 @icebreakers/monorepo 依赖。",
1206
+ fix: "运行 repo setup --yes 添加 repoctl devDependency,或手动执行 pnpm add -D repoctl。"
1207
+ }));
1208
+ const hasSetup = hasScript(pkgJson, "setup");
1209
+ const hasNew = hasScript(pkgJson, "new");
1210
+ const hasCheck = hasScript(pkgJson, "check");
1211
+ const hasDoctor = hasScript(pkgJson, "doctor");
1212
+ if (hasSetup && hasNew && hasCheck && hasDoctor) checks.push(createCheck({
1213
+ id: "root-scripts",
1214
+ title: "根快捷脚本",
1215
+ status: "pass",
1216
+ detail: "已检测到 setup / new / check / doctor 根脚本,可以直接使用 pnpm setup / pnpm new / pnpm check / pnpm doctor。"
1217
+ }));
1218
+ else {
1219
+ const missing = [
1220
+ !hasSetup ? "setup" : null,
1221
+ !hasNew ? "new" : null,
1222
+ !hasCheck ? "check" : null,
1223
+ !hasDoctor ? "doctor" : null
1224
+ ].filter(Boolean).join(", ");
1225
+ checks.push(createCheck({
1226
+ id: "root-scripts",
1227
+ title: "根快捷脚本",
1228
+ status: "warn",
1229
+ detail: `缺少推荐的根脚本:${missing}。`,
1230
+ fix: "运行 repo setup --yes 同步推荐根脚本,或手动在 package.json 中补齐 setup / new / check / doctor。"
1231
+ }));
1232
+ }
1233
+ if (hasRepoctlConfig && hasMonorepoConfig) checks.push(createCheck({
1234
+ id: "config-file",
1235
+ title: "配置文件",
1236
+ status: "fail",
1237
+ detail: "同时存在 repoctl.config.ts 和 monorepo.config.ts,CLI 会拒绝加载。",
1238
+ fix: "保留一个配置文件即可,推荐只保留 repoctl.config.ts。"
1239
+ }));
1240
+ else if (hasRepoctlConfig || hasMonorepoConfig) checks.push(createCheck({
1241
+ id: "config-file",
1242
+ title: "配置文件",
1243
+ status: "pass",
1244
+ detail: `已检测到配置文件:${hasRepoctlConfig ? "repoctl.config.ts" : "monorepo.config.ts"}`
1245
+ }));
1246
+ else checks.push(createCheck({
1247
+ id: "config-file",
1248
+ title: "配置文件",
1249
+ status: "warn",
1250
+ detail: "当前仓库没有自定义配置文件,CLI 会完全使用默认行为。",
1251
+ fix: "运行 repo upgrade --yes 同步默认 repoctl.config.ts,或手动添加 repoctl.config.ts。"
1252
+ }));
1253
+ if (hasHuskyPreCommit && hasLintStagedConfig) checks.push(createCheck({
1254
+ id: "commit-hooks",
1255
+ title: "提交链路",
1256
+ status: "pass",
1257
+ detail: "已检测到 .husky/pre-commit 与 lint-staged.config.js,提交前校验链路完整。"
1258
+ }));
1259
+ else if (hasHuskyPreCommit || hasLintStagedConfig) checks.push(createCheck({
1260
+ id: "commit-hooks",
1261
+ title: "提交链路",
1262
+ status: "warn",
1263
+ detail: "提交校验链路只配置了一半,Husky 与 lint-staged 没有同时就绪。",
1264
+ fix: "运行 repo upgrade --yes 同步 .husky/pre-commit 与 lint-staged.config.js。"
1265
+ }));
1266
+ else checks.push(createCheck({
1267
+ id: "commit-hooks",
1268
+ title: "提交链路",
1269
+ status: "warn",
1270
+ detail: "当前仓库未检测到 Husky / lint-staged 提交校验入口。",
1271
+ fix: "运行 repo upgrade --yes 同步 Husky 与 lint-staged 默认配置。"
1272
+ }));
1273
+ const configFiles = [...isSourceWorkspace ? [] : [
1274
+ "eslint.config.js",
1275
+ "stylelint.config.js",
1276
+ "lint-staged.config.js",
1277
+ "vitest.config.ts"
1278
+ ], ...[
1279
+ "apps",
1280
+ "packages",
1281
+ "examples"
1282
+ ].flatMap((dir) => [`${dir}/*/eslint.config.js`, `${dir}/*/vitest.config.ts`])];
1283
+ const legacyToolingFiles = [];
1284
+ for (const filePattern of configFiles) {
1285
+ if (filePattern.includes("*")) {
1286
+ const [baseDir, rest] = filePattern.split("/*/");
1287
+ const absBaseDir = `${workspaceDir}/${baseDir}`;
1288
+ if (!await fs$1.pathExists(absBaseDir)) continue;
1289
+ const entries = await readdir(absBaseDir);
1290
+ await Promise.all(entries.map(async (entry) => {
1291
+ const candidate = `${absBaseDir}/${entry}/${rest}`;
1292
+ if (await fs$1.pathExists(candidate) && hasLegacyToolingReference(await fs$1.readFile(candidate, "utf8"))) legacyToolingFiles.push(`${baseDir}/${entry}/${rest}`);
1293
+ }));
1294
+ continue;
1295
+ }
1296
+ const candidate = `${workspaceDir}/${filePattern}`;
1297
+ if (await fs$1.pathExists(candidate) && hasLegacyToolingReference(await fs$1.readFile(candidate, "utf8"))) legacyToolingFiles.push(filePattern);
1298
+ }
1299
+ if (legacyToolingFiles.length === 0) checks.push(createCheck({
1300
+ id: "tooling-imports",
1301
+ title: "tooling imports",
1302
+ status: "pass",
1303
+ detail: "tooling 配置未引用本地源码仓库 loader。"
1304
+ }));
1305
+ else checks.push(createCheck({
1306
+ id: "tooling-imports",
1307
+ title: "tooling imports",
1308
+ status: "warn",
1309
+ detail: `以下配置引用了本地源码仓库 tooling loader:${legacyToolingFiles.join(", ")}。`,
1310
+ fix: "运行 repo upgrade --yes 迁移为直接 import repoctl/tooling。"
1311
+ }));
1312
+ const missingCommonPatterns = (await Promise.all([
1313
+ "apps",
1314
+ "packages",
1315
+ "examples"
1316
+ ].map(async (base) => ({
1317
+ base,
1318
+ exists: await fs$1.pathExists(`${workspaceDir}/${base}`)
1319
+ })))).filter((item) => item.exists).map((item) => item.base).map((base) => `${base}/*`).filter((pattern) => !workspacePatterns.includes(pattern));
1320
+ if (hasWorkspaceManifest && missingCommonPatterns.length === 0) checks.push(createCheck({
1321
+ id: "workspace-patterns",
1322
+ title: "workspace patterns",
1323
+ status: "pass",
1324
+ detail: "pnpm-workspace.yaml 已包含 apps/* / packages/* / examples/* 常见目录。"
1325
+ }));
1326
+ else if (hasWorkspaceManifest) checks.push(createCheck({
1327
+ id: "workspace-patterns",
1328
+ title: "workspace patterns",
1329
+ status: "warn",
1330
+ detail: `pnpm-workspace.yaml 缺少常见目录:${missingCommonPatterns.join(", ")}。`,
1331
+ fix: "运行 repo setup --yes 追加缺失 workspace patterns。"
1332
+ }));
1333
+ const uncoveredWorkspacePackages = workspacePackageDirs.filter((dir) => !isWorkspacePatternCovered(dir, workspacePatterns));
1334
+ if (hasWorkspaceManifest && uncoveredWorkspacePackages.length === 0) checks.push(createCheck({
1335
+ id: "workspace-package-coverage",
1336
+ title: "workspace package coverage",
1337
+ status: "pass",
1338
+ detail: "常见 workspace 目录下的 package.json 都已被 pnpm-workspace.yaml 覆盖。"
1339
+ }));
1340
+ else if (hasWorkspaceManifest) checks.push(createCheck({
1341
+ id: "workspace-package-coverage",
1342
+ title: "workspace package coverage",
1343
+ status: "warn",
1344
+ detail: `以下 package.json 未被 pnpm-workspace.yaml 覆盖:${uncoveredWorkspacePackages.join(", ")}。`,
1345
+ fix: "运行 repo setup --yes 追加缺失 workspace patterns。"
1346
+ }));
1347
+ return {
1348
+ cwd,
1349
+ workspaceDir,
1350
+ packageCount,
1351
+ checks,
1352
+ summary: summarizeChecks(checks)
1353
+ };
1354
+ }
1355
+ //#endregion
1356
+ //#region src/commands/env.ts
1357
+ function readPnpmVersion() {
1358
+ try {
1359
+ return execFileSync("pnpm", ["--version"], {
1360
+ encoding: "utf8",
1361
+ stdio: [
1362
+ "ignore",
1363
+ "pipe",
1364
+ "ignore"
1365
+ ]
1366
+ }).trim();
1367
+ } catch {
1368
+ return;
1369
+ }
1370
+ }
1371
+ async function createEnvPathEntry(workspaceDir, targetPath) {
1372
+ return {
1373
+ path: targetPath,
1374
+ relativePath: path.relative(workspaceDir, targetPath) || ".",
1375
+ exists: await fs$1.pathExists(targetPath)
1376
+ };
1377
+ }
1378
+ async function collectEnvInfo(cwd) {
1379
+ const workspace = await getWorkspacePackageSummaries(cwd, { ignorePrivatePackage: false });
1380
+ const packageJsonPath = path.join(workspace.workspaceDir, "package.json");
1381
+ const pkgJson = await fs$1.pathExists(packageJsonPath) ? await fs$1.readJson(packageJsonPath) : {};
1382
+ const pnpmVersion = readPnpmVersion();
1383
+ return {
1384
+ cwd: workspace.cwd,
1385
+ workspaceDir: workspace.workspaceDir,
1386
+ ...pkgJson.packageManager ? { packageManager: pkgJson.packageManager } : {},
1387
+ nodeVersion: process.version,
1388
+ ...pkgJson.engines?.node ? { nodeRange: pkgJson.engines.node } : {},
1389
+ ...pnpmVersion ? { pnpmVersion } : {},
1390
+ platform: os.platform(),
1391
+ arch: os.arch(),
1392
+ packageCount: workspace.packages.length
1393
+ };
1394
+ }
1395
+ async function collectEnvPaths(cwd) {
1396
+ const workspaceDir = await findWorkspaceDir(cwd) ?? cwd;
1397
+ const configCandidates = getMonorepoConfigCandidates(workspaceDir);
1398
+ const paths = {
1399
+ packageJson: path.join(workspaceDir, "package.json"),
1400
+ workspaceManifest: path.join(workspaceDir, "pnpm-workspace.yaml"),
1401
+ repoctlConfig: path.join(workspaceDir, "repoctl.config.ts"),
1402
+ legacyConfig: path.join(workspaceDir, "monorepo.config.ts"),
1403
+ toolingDir: path.join(workspaceDir, "tooling"),
1404
+ reportsDir: path.join(workspaceDir, "reports"),
1405
+ doctorReport: path.join(workspaceDir, "reports/doctor.json"),
1406
+ envReport: path.join(workspaceDir, "reports/env.json"),
1407
+ snapshotReport: path.join(workspaceDir, "reports/snapshot.json"),
1408
+ checkPlanReport: path.join(workspaceDir, "reports/check-plan.json")
1409
+ };
1410
+ return {
1411
+ cwd,
1412
+ workspaceDir,
1413
+ paths: {
1414
+ packageJson: await createEnvPathEntry(workspaceDir, paths.packageJson),
1415
+ workspaceManifest: await createEnvPathEntry(workspaceDir, paths.workspaceManifest),
1416
+ repoctlConfig: await createEnvPathEntry(workspaceDir, paths.repoctlConfig),
1417
+ repoctlConfigs: await Promise.all(configCandidates.repoctl.map((file) => createEnvPathEntry(workspaceDir, file))),
1418
+ legacyConfig: await createEnvPathEntry(workspaceDir, paths.legacyConfig),
1419
+ legacyConfigs: await Promise.all(configCandidates.monorepo.map((file) => createEnvPathEntry(workspaceDir, file))),
1420
+ toolingDir: await createEnvPathEntry(workspaceDir, paths.toolingDir),
1421
+ reportsDir: await createEnvPathEntry(workspaceDir, paths.reportsDir),
1422
+ doctorReport: await createEnvPathEntry(workspaceDir, paths.doctorReport),
1423
+ envReport: await createEnvPathEntry(workspaceDir, paths.envReport),
1424
+ snapshotReport: await createEnvPathEntry(workspaceDir, paths.snapshotReport),
1425
+ checkPlanReport: await createEnvPathEntry(workspaceDir, paths.checkPlanReport)
1426
+ }
1427
+ };
1428
+ }
1429
+ async function collectEnvSnapshot(cwd, now = /* @__PURE__ */ new Date()) {
1430
+ const [env, doctor] = await Promise.all([collectEnvInfo(cwd), runDoctor(cwd)]);
1431
+ return {
1432
+ generatedAt: now.toISOString(),
1433
+ env,
1434
+ doctor,
1435
+ checkPlan: resolveRecommendedCheckPlan({ cwd })
1436
+ };
1437
+ }
1438
+ async function collectEnvSupportBundle(cwd, now = /* @__PURE__ */ new Date()) {
1439
+ const [env, paths, config, doctor] = await Promise.all([
1440
+ collectEnvInfo(cwd),
1441
+ collectEnvPaths(cwd),
1442
+ inspectMonorepoConfig(cwd),
1443
+ runDoctor(cwd)
1444
+ ]);
1445
+ return {
1446
+ generatedAt: now.toISOString(),
1447
+ env,
1448
+ paths,
1449
+ config,
1450
+ doctor,
1451
+ checkPlan: resolveRecommendedCheckPlan({ cwd })
1452
+ };
1453
+ }
1454
+ //#endregion
1455
+ //#region src/core/context.ts
1456
+ /**
1457
+ * 构建命令执行上下文,封装常用的工作区、Git、配置等信息。
1458
+ */
1459
+ async function createContext(cwd) {
1460
+ const { packages, workspaceDir } = await getWorkspaceData(cwd);
1461
+ const git = new GitClient({ baseDir: workspaceDir });
1462
+ const workspaceFilepath = path.resolve(workspaceDir, "pnpm-workspace.yaml");
1463
+ return {
1464
+ cwd,
1465
+ git,
1466
+ gitUrl: await git.getGitUrl(),
1467
+ gitUser: await git.getUser(),
1468
+ workspaceDir,
1469
+ workspaceFilepath,
1470
+ packages,
1471
+ config: await loadMonorepoConfig(workspaceDir)
1472
+ };
1473
+ }
1474
+ //#endregion
1475
+ //#region src/commands/init/setChangeset.ts
1476
+ /**
1477
+ * 将 changeset 配置中的仓库地址指向当前项目,方便自动生成变更日志链接。
1478
+ */
1479
+ async function setChangeset_default(ctx) {
1480
+ const { gitUrl, workspaceFilepath } = ctx;
1481
+ if (gitUrl && await fs$1.exists(workspaceFilepath)) {
1482
+ const changesetConfigPath = path.resolve(path.dirname(workspaceFilepath), ".changeset/config.json");
1483
+ if (await fs$1.exists(changesetConfigPath)) {
1484
+ const changesetConfig = await fs$1.readJson(changesetConfigPath);
1485
+ if (gitUrl.full_name) {
1486
+ setByPath(changesetConfig, "changelog.1.repo", gitUrl.full_name);
1487
+ await fs$1.outputJson(changesetConfigPath, changesetConfig, { spaces: 2 });
1488
+ }
1489
+ }
1490
+ }
1491
+ }
1492
+ //#endregion
1493
+ //#region src/commands/init/setIssueTemplateConfig.ts
1494
+ /**
1495
+ * 同步 Issue 模版里的 discussions 链接到当前仓库。
1496
+ */
1497
+ async function setIssueTemplateConfig_default(ctx) {
1498
+ const repoName = ctx.gitUrl?.full_name;
1499
+ if (!repoName) return;
1500
+ const configPath = path.resolve(ctx.cwd, ".github/ISSUE_TEMPLATE/config.yml");
1501
+ if (!await fs$1.pathExists(configPath)) return;
1502
+ const source = await fs$1.readFile(configPath, "utf8");
1503
+ const next = updateIssueTemplateConfig(source, repoName);
1504
+ if (next !== source) await fs$1.writeFile(configPath, next, "utf8");
1505
+ }
1506
+ //#endregion
1507
+ //#region src/commands/init/setPkgJson.ts
1508
+ /**
1509
+ * 根据当前仓库信息同步 package.json 的仓库、作者等字段。
1510
+ */
1511
+ async function setPkgJson_default(ctx) {
1512
+ const { gitUrl, gitUser, packages, cwd, workspaceFilepath } = ctx;
1513
+ const workspaceExists = await fs$1.pathExists(workspaceFilepath);
1514
+ if (gitUrl && workspaceExists) await Promise.all(packages.map(async (pkg) => {
1515
+ if (!await fs$1.pathExists(pkg.pkgJsonPath)) return;
1516
+ const pkgJson = JSON.parse(JSON.stringify(pkg.manifest));
1517
+ const directory = path.relative(cwd, pkg.rootDir);
1518
+ setByPath(pkgJson, ["bugs", "url"], `https://github.com/${gitUrl.full_name}/issues`);
1519
+ const repository = {
1520
+ type: "git",
1521
+ url: `git+https://github.com/${gitUrl.full_name}.git`
1522
+ };
1523
+ if (directory) repository.directory = directory;
1524
+ setByPath(pkgJson, "repository", repository);
1525
+ if (gitUser?.name && gitUser?.email) setByPath(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
1526
+ const nextContent = `${JSON.stringify(pkgJson, void 0, 2)}\n`;
1527
+ if (await fs$1.readFile(pkg.pkgJsonPath, "utf8") !== nextContent) await fs$1.writeFile(pkg.pkgJsonPath, nextContent, "utf8");
1528
+ }));
1529
+ }
1530
+ //#endregion
1531
+ //#region src/commands/init/setReadme.ts
1532
+ async function getRows(ctx) {
1533
+ const { packages, gitUrl, gitUser, cwd } = ctx;
1534
+ const rows = [];
1535
+ if (gitUrl) rows.push(`# ${gitUrl.name}\n`);
1536
+ rows.push("## Packages\n");
1537
+ const sortedPackages = packages.toSorted((a, b) => {
1538
+ const left = a.manifest.name ?? "";
1539
+ const right = b.manifest.name ?? "";
1540
+ return left.localeCompare(right);
1541
+ });
1542
+ for (const pkg of sortedPackages) {
1543
+ const p = path.relative(cwd, pkg.rootDirRealPath);
1544
+ if (p) {
1545
+ const description = pkg.manifest.description ? `- ${pkg.manifest.description}` : "";
1546
+ rows.push(`- [${pkg.manifest.name}](${p}) ${description}`);
1547
+ }
1548
+ }
1549
+ if (gitUrl) {
1550
+ rows.push("\n## Contributing\n");
1551
+ rows.push("Contributions Welcome! You can contribute in the following ways.");
1552
+ rows.push("");
1553
+ rows.push("- Create an Issue - Propose a new feature. Report a bug.");
1554
+ rows.push("- Pull Request - Fix a bug and typo. Refactor the code.");
1555
+ rows.push("- Create third-party middleware - Instruct below.");
1556
+ rows.push("- Share - Share your thoughts on the Blog, X, and others.");
1557
+ rows.push(`- Make your application - Please try to use ${gitUrl.name}.`);
1558
+ rows.push("");
1559
+ rows.push("For more details, see [CONTRIBUTING.md](CONTRIBUTING.md).");
1560
+ rows.push("\n## Contributors\n");
1561
+ rows.push(`Thanks to [all contributors](https://github.com/${gitUrl.full_name}/graphs/contributors)!`);
1562
+ }
1563
+ rows.push("\n## Authors\n");
1564
+ if (gitUser?.name && gitUser?.email) rows.push(`${gitUser.name} <${gitUser.email}>`);
1565
+ rows.push("\n## License\n");
1566
+ rows.push("Distributed under the MIT License. See [LICENSE](LICENSE) for more information.");
1567
+ return rows;
1568
+ }
1569
+ /**
1570
+ * 生成标准化的 README 草稿,列出所有子包并补充贡献者、作者信息。
1571
+ */
1572
+ async function setReadme_default(ctx, options = {}) {
1573
+ const readmePath = path.resolve(ctx.cwd, "README.md");
1574
+ if (!options.force && await fs$1.pathExists(readmePath)) return;
1575
+ const rows = await getRows(ctx);
1576
+ await fs$1.writeFile(readmePath, `${rows.join("\n")}\n`);
1577
+ }
1578
+ //#endregion
1579
+ //#region ../../package.json
1580
+ var devDependencies = {
1581
+ "@changesets/cli": "^2.31.0",
1582
+ "@commitlint/cli": "^20.5.3",
1583
+ "@icebreakers/changelog-github": "^1.0.2",
1584
+ "@icebreakers/commitlint-config": "^2.0.0",
1585
+ "@icebreakers/eslint-config": "^4.0.10",
1586
+ "@icebreakers/monorepo": "workspace:*",
1587
+ "@icebreakers/stylelint-config": "^3.0.6",
1588
+ "@types/node": "^25.6.0",
1589
+ "@types/semver": "^7.7.1",
1590
+ "@vitest/coverage-v8": "~4.1.5",
1591
+ "ci-info": "^4.4.0",
1592
+ "cross-env": "^10.1.0",
1593
+ "defu": "^6.1.7",
1594
+ "es-toolkit": "^1.46.1",
1595
+ "eslint": "^10.3.0",
1596
+ "husky": "^9.1.7",
1597
+ "lint-staged": "^16.4.0",
1598
+ "only-allow": "^1.2.2",
1599
+ "pathe": "^2.0.3",
1600
+ "pkg-types": "^2.3.1",
1601
+ "repoctl": "workspace:*",
1602
+ "stylelint": "^17.11.0",
1603
+ "tailwindcss": "^4.2.4",
1604
+ "tsd": "^0.33.0",
1605
+ "tsdown": "0.21.10",
1606
+ "tslib": "^2.8.1",
1607
+ "tsx": "^4.21.0",
1608
+ "turbo": "^2.9.9",
1609
+ "type-fest": "^5.6.0",
1610
+ "typescript": "^6.0.3",
1611
+ "vitest": "~4.1.5",
1612
+ "yaml": "^2.8.4"
1613
+ };
1614
+ //#endregion
1615
+ //#region src/commands/init/tooling/presets.ts
1616
+ const packageDependencies = {
1617
+ ...{
1618
+ name: "monorepo-template",
1619
+ type: "module",
1620
+ version: "0.0.0",
1621
+ "private": true,
1622
+ packageManager: "pnpm@10.33.2",
1623
+ author: "ice breaker <hi@sonofmagic.top>",
1624
+ repository: {
1625
+ "type": "git",
1626
+ "url": "git+https://github.com/sonofmagic/monorepo-template.git"
1627
+ },
1628
+ bugs: { "url": "https://github.com/sonofmagic/monorepo-template/issues" },
1629
+ engines: { "node": ">=20.0.0" },
1630
+ scripts: {
1631
+ "build": "turbo run build",
1632
+ "tooling:build": "turbo run build --filter=@icebreakers/monorepo --filter=repoctl",
1633
+ "dev": "turbo run dev --parallel",
1634
+ "test": "vitest run",
1635
+ "test:dev": "vitest",
1636
+ "lint": "pnpm run tooling:build && turbo run lint",
1637
+ "tsd": "turbo run tsd",
1638
+ "audit": "pnpm audit --audit-level=moderate",
1639
+ "audit:fix": "pnpm audit --fix",
1640
+ "typecheck": "turbo run typecheck",
1641
+ "format": "eslint . --fix",
1642
+ "validate": "pnpm run build && pnpm run lint && pnpm run typecheck && pnpm run tsd && pnpm run test",
1643
+ "release": "changeset",
1644
+ "publish-packages": "pnpm run build && pnpm run lint && pnpm run test && changeset version && changeset publish",
1645
+ "------": "--------------",
1646
+ "preinstall": "npx only-allow pnpm",
1647
+ "prepare": "husky",
1648
+ "commit": "commit",
1649
+ "commitlint": "commitlint --edit",
1650
+ "-------": "---------------",
1651
+ "setup": "repo setup",
1652
+ "new": "repo new",
1653
+ "check": "repo check",
1654
+ "doctor": "repo doctor",
1655
+ "sync": "repo sync",
1656
+ "clean:repo": "repo clean",
1657
+ "mirror": "repo mirror",
1658
+ "------simple": "--------------",
1659
+ "pr:alpha": "changeset pre enter alpha",
1660
+ "pr:beta": "changeset pre enter beta",
1661
+ "pr:rc": "changeset pre enter rc",
1662
+ "pr:exit": "changeset pre exit",
1663
+ "--------": "----------------",
1664
+ "script:init": "repo init",
1665
+ "script:sync": "repo sync",
1666
+ "script:clean": "repo clean",
1667
+ "script:mirror": "repo mirror"
1668
+ },
1669
+ devDependencies,
1670
+ publishConfig: {
1671
+ "access": "public",
1672
+ "registry": "https://registry.npmjs.org"
1673
+ }
1674
+ }.dependencies ?? {},
1675
+ ...devDependencies ?? {},
1676
+ ...dependencies ?? {},
1677
+ ...devDependencies$1 ?? {}
1678
+ };
1679
+ function getDependencyVersion(name) {
1680
+ const version = packageDependencies[name];
1681
+ if (!version) throw new Error(`未找到依赖 ${name} 的版本信息`);
1682
+ return version;
1683
+ }
1684
+ function getToolingPackageVersion() {
1685
+ return `^${version$1}`;
1686
+ }
1687
+ function createConfigModule(functionName, source) {
1688
+ return [
1689
+ `import { ${functionName} } from '${source}'`,
1690
+ "",
1691
+ `export default await ${functionName}()`,
1692
+ ""
1693
+ ].join("\n");
1694
+ }
1695
+ function getToolingPackageDependency(toolingPackageName) {
1696
+ return { [toolingPackageName]: getToolingPackageVersion() };
1697
+ }
1698
+ function getRootDeps(pkgJson) {
1699
+ return {
1700
+ ...pkgJson.dependencies ?? {},
1701
+ ...pkgJson.devDependencies ?? {}
1702
+ };
1703
+ }
1704
+ function resolveToolingPackageName(pkgJson) {
1705
+ const deps = getRootDeps(pkgJson);
1706
+ if (typeof deps["repoctl"] === "string" && deps["repoctl"].length > 0) return "repoctl";
1707
+ if (typeof deps["@icebreakers/monorepo"] === "string" && deps["@icebreakers/monorepo"].length > 0) return "@icebreakers/monorepo";
1708
+ return "repoctl";
1709
+ }
1710
+ function resolveToolingImportSource(toolingPackageName) {
1711
+ return toolingPackageName === "repoctl" ? "repoctl/tooling" : "@icebreakers/monorepo/tooling";
1712
+ }
1713
+ const initToolingPresets = {
1714
+ "commitlint": {
1715
+ target: "commitlint",
1716
+ filepath: "commitlint.config.ts",
1717
+ getContent: ({ toolingImportSource }) => createConfigModule("defineCommitlintConfig", toolingImportSource),
1718
+ getDependencies: ({ toolingPackageName }) => ({
1719
+ ...getToolingPackageDependency(toolingPackageName),
1720
+ "@commitlint/cli": getDependencyVersion("@commitlint/cli"),
1721
+ "@icebreakers/commitlint-config": getDependencyVersion("@icebreakers/commitlint-config")
1722
+ })
1723
+ },
1724
+ "eslint": {
1725
+ target: "eslint",
1726
+ filepath: "eslint.config.js",
1727
+ getContent: ({ toolingImportSource }) => createConfigModule("defineEslintConfig", toolingImportSource),
1728
+ getDependencies: ({ toolingPackageName }) => ({
1729
+ ...getToolingPackageDependency(toolingPackageName),
1730
+ "@icebreakers/eslint-config": getDependencyVersion("@icebreakers/eslint-config"),
1731
+ "eslint": getDependencyVersion("eslint")
1732
+ })
1733
+ },
1734
+ "stylelint": {
1735
+ target: "stylelint",
1736
+ filepath: "stylelint.config.js",
1737
+ getContent: ({ toolingImportSource }) => createConfigModule("defineStylelintConfig", toolingImportSource),
1738
+ getDependencies: ({ toolingPackageName }) => ({
1739
+ ...getToolingPackageDependency(toolingPackageName),
1740
+ "@icebreakers/stylelint-config": getDependencyVersion("@icebreakers/stylelint-config"),
1741
+ "stylelint": getDependencyVersion("stylelint")
1742
+ })
1743
+ },
1744
+ "lint-staged": {
1745
+ target: "lint-staged",
1746
+ filepath: "lint-staged.config.js",
1747
+ getContent: ({ toolingImportSource }) => createConfigModule("defineLintStagedConfig", toolingImportSource),
1748
+ getDependencies: ({ toolingPackageName }) => ({
1749
+ ...getToolingPackageDependency(toolingPackageName),
1750
+ "lint-staged": getDependencyVersion("lint-staged")
1751
+ })
1752
+ },
1753
+ "tsconfig": {
1754
+ target: "tsconfig",
1755
+ filepath: "tsconfig.json",
1756
+ getContent: async ({ cwd }) => {
1757
+ const config = await defineTsconfigConfig({ cwd });
1758
+ return `${JSON.stringify(config, void 0, 2)}\n`;
1759
+ },
1760
+ getDependencies: ({ toolingPackageName }) => ({
1761
+ ...getToolingPackageDependency(toolingPackageName),
1762
+ typescript: getDependencyVersion("typescript")
1763
+ })
1764
+ },
1765
+ "vitest": {
1766
+ target: "vitest",
1767
+ filepath: "vitest.config.ts",
1768
+ getContent: ({ toolingImportSource }) => [
1769
+ `import { defineVitestConfig } from '${toolingImportSource}'`,
1770
+ `import { defineConfig } from 'vitest/config'`,
1771
+ "",
1772
+ "export default defineConfig(async () => await defineVitestConfig())",
1773
+ ""
1774
+ ].join("\n"),
1775
+ getDependencies: ({ toolingPackageName }) => ({
1776
+ ...getToolingPackageDependency(toolingPackageName),
1777
+ "@vitest/coverage-v8": getDependencyVersion("@vitest/coverage-v8"),
1778
+ "vitest": getDependencyVersion("vitest")
1779
+ })
1780
+ }
1781
+ };
1782
+ //#endregion
1783
+ //#region src/commands/init/tooling/index.ts
1784
+ function sortRecord(input) {
1785
+ return Object.fromEntries(Object.entries(input).filter((entry) => typeof entry[1] === "string" && entry[1].length > 0).sort(([left], [right]) => left.localeCompare(right)));
1786
+ }
1787
+ function mergeDevDependencies(pkgJson, additions) {
1788
+ const current = { ...pkgJson.devDependencies ?? {} };
1789
+ let changed = false;
1790
+ for (const [name, version] of Object.entries(additions)) {
1791
+ if (!version) continue;
1792
+ if (current[name] === version) continue;
1793
+ current[name] = version;
1794
+ changed = true;
1795
+ }
1796
+ if (!changed && pkgJson.devDependencies) return false;
1797
+ pkgJson.devDependencies = sortRecord(current);
1798
+ return true;
1799
+ }
1800
+ function resolveTargets(options) {
1801
+ if (options.all) return [...initToolingTargets];
1802
+ const inputTargets = options.targets ?? [];
1803
+ return [...new Set(inputTargets)].filter((target) => {
1804
+ return initToolingTargets.includes(target);
1805
+ });
1806
+ }
1807
+ function normalizeInitToolingTargets(input) {
1808
+ const unknown = input.filter((item) => !initToolingTargets.includes(item));
1809
+ if (unknown.length > 0) throw new Error(`未知的 init tooling 目标: ${unknown.join(", ")}`);
1810
+ return input;
1811
+ }
1812
+ async function initTooling(cwd, options = {}) {
1813
+ const selectedTargets = resolveTargets(options);
1814
+ if (selectedTargets.length === 0) return {
1815
+ selectedTargets: [],
1816
+ writtenFiles: [],
1817
+ skippedFiles: [],
1818
+ updatedPackageJson: false
1819
+ };
1820
+ const pkgJsonPath = path.resolve(cwd, "package.json");
1821
+ if (!await fs$1.pathExists(pkgJsonPath)) throw new Error(`未找到 package.json,无法初始化 tooling: ${pkgJsonPath}`);
1822
+ const packageJson = await fs$1.readJson(pkgJsonPath);
1823
+ const toolingPackageName = resolveToolingPackageName(packageJson);
1824
+ const toolingImportSource = resolveToolingImportSource(toolingPackageName);
1825
+ const additions = {};
1826
+ const writtenFiles = [];
1827
+ const skippedFiles = [];
1828
+ for (const target of selectedTargets) {
1829
+ const preset = initToolingPresets[target];
1830
+ const filepath = path.resolve(cwd, preset.filepath);
1831
+ const exists = await fs$1.pathExists(filepath);
1832
+ Object.assign(additions, preset.getDependencies({
1833
+ cwd,
1834
+ packageJson,
1835
+ toolingPackageName,
1836
+ toolingImportSource
1837
+ }));
1838
+ if (exists && !options.force) {
1839
+ skippedFiles.push(preset.filepath);
1840
+ logger.info(`skip existing init target: ${preset.filepath}`);
1841
+ continue;
1842
+ }
1843
+ const content = await preset.getContent({
1844
+ cwd,
1845
+ packageJson,
1846
+ toolingPackageName,
1847
+ toolingImportSource
1848
+ });
1849
+ await fs$1.outputFile(filepath, content, "utf8");
1850
+ writtenFiles.push(preset.filepath);
1851
+ }
1852
+ const updatedPackageJson = mergeDevDependencies(packageJson, additions);
1853
+ if (updatedPackageJson) await fs$1.writeFile(pkgJsonPath, `${JSON.stringify(packageJson, void 0, 2)}\n`, "utf8");
1854
+ return {
1855
+ selectedTargets,
1856
+ writtenFiles,
1857
+ skippedFiles,
1858
+ updatedPackageJson
1859
+ };
1860
+ }
1861
+ //#endregion
1862
+ //#region src/commands/init/index.ts
1863
+ const presetToolingMap = {
1864
+ minimal: ["tsconfig"],
1865
+ standard: [...initToolingTargets]
1866
+ };
1867
+ const defaultWorkspacePackages = [
1868
+ "apps/*",
1869
+ "packages/*",
1870
+ "examples/*"
1871
+ ];
1872
+ function mergeUniqueStrings(current, additions) {
1873
+ const values = Array.isArray(current) ? current.filter((item) => typeof item === "string" && item.length > 0) : [];
1874
+ const seen = new Set(values);
1875
+ for (const addition of additions) if (!seen.has(addition)) {
1876
+ seen.add(addition);
1877
+ values.push(addition);
1878
+ }
1879
+ return values;
1880
+ }
1881
+ async function ensureRootPackageJson(cwd) {
1882
+ const pkgJsonPath = path.resolve(cwd, "package.json");
1883
+ if (!await fs$1.pathExists(pkgJsonPath)) {
1884
+ const pkgJson = {
1885
+ name: path.basename(cwd),
1886
+ type: "module",
1887
+ version: "0.0.0",
1888
+ private: true,
1889
+ packageManager: "pnpm@10.0.0",
1890
+ engines: { node: ">=20.0.0" },
1891
+ scripts: {},
1892
+ devDependencies: {}
1893
+ };
1894
+ await fs$1.writeFile(pkgJsonPath, `${JSON.stringify(pkgJson, void 0, 2)}\n`, "utf8");
1895
+ }
1896
+ }
1897
+ async function ensureWorkspaceManifest(cwd) {
1898
+ const workspacePath = path.resolve(cwd, "pnpm-workspace.yaml");
1899
+ const existing = await fs$1.pathExists(workspacePath);
1900
+ const manifest = existing ? YAML.parse(await fs$1.readFile(workspacePath, "utf8")) ?? {} : {};
1901
+ const nextManifest = {
1902
+ ...typeof manifest === "object" && manifest !== null ? manifest : {},
1903
+ packages: mergeUniqueStrings(typeof manifest === "object" && manifest !== null ? manifest.packages : void 0, defaultWorkspacePackages)
1904
+ };
1905
+ const nextContent = YAML.stringify(nextManifest, { singleQuote: true });
1906
+ const previous = existing ? await fs$1.readFile(workspacePath, "utf8") : "";
1907
+ if (!existing || previous !== nextContent) await fs$1.writeFile(workspacePath, nextContent, "utf8");
1908
+ }
1909
+ async function runInitMetadata(cwd, options = {}) {
1910
+ await ensureRootPackageJson(cwd);
1911
+ await ensureWorkspaceManifest(cwd);
1912
+ const ctx = await createContext(cwd);
1913
+ const initConfig = ctx.config.commands?.init ?? {};
1914
+ const overwrite = options.overwrite ?? options.force ?? initConfig.force ?? false;
1915
+ if (!initConfig.skipChangeset) await setChangeset_default(ctx);
1916
+ if (!initConfig.skipPkgJson) await setPkgJson_default(ctx);
1917
+ if (!initConfig.skipReadme) await setReadme_default(ctx, { force: overwrite });
1918
+ if (!initConfig.skipIssueTemplateConfig) await setIssueTemplateConfig_default(ctx);
1919
+ return {
1920
+ ctx,
1921
+ initConfig
1922
+ };
1923
+ }
1924
+ async function initMetadata(cwd) {
1925
+ await runInitMetadata(cwd);
1926
+ }
1927
+ /**
1928
+ * 初始化命令入口,根据配置逐步生成基础文件。
1929
+ */
1930
+ async function init(cwd, options = {}) {
1931
+ const { initConfig } = await runInitMetadata(cwd, options);
1932
+ const preset = options.preset ?? initConfig.preset;
1933
+ const presetTargets = preset ? presetToolingMap[preset] : void 0;
1934
+ const configuredTargets = initConfig.tooling ?? [];
1935
+ const runtimeTargets = options.tooling?.length ? [...options.tooling] : presetTargets ?? configuredTargets;
1936
+ await initTooling(cwd, {
1937
+ targets: options.all ? [...initToolingTargets] : normalizeInitToolingTargets(runtimeTargets),
1938
+ force: options.force ?? options.overwrite ?? initConfig.force ?? false,
1939
+ ...options.all !== void 0 ? { all: options.all } : {}
1940
+ });
1941
+ }
1942
+ //#endregion
1943
+ //#region src/commands/mirror/sources.ts
1944
+ const chinaMirrorsEnvs = {
1945
+ COREPACK_NPM_REGISTRY: "https://registry.npmmirror.com",
1946
+ EDGEDRIVER_CDNURL: "https://npmmirror.com/mirrors/edgedriver",
1947
+ NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
1948
+ NVM_NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
1949
+ PHANTOMJS_CDNURL: "https://cdn.npmmirror.com/binaries/phantomjs",
1950
+ CHROMEDRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/chromedriver",
1951
+ OPERADRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/operadriver",
1952
+ CYPRESS_DOWNLOAD_PATH_TEMPLATE: "https://cdn.npmmirror.com/binaries/cypress/${version}/${platform}-${arch}/cypress.zip",
1953
+ ELECTRON_MIRROR: "https://cdn.npmmirror.com/binaries/electron/",
1954
+ ELECTRON_BUILDER_BINARIES_MIRROR: "https://cdn.npmmirror.com/binaries/electron-builder-binaries/",
1955
+ SASS_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-sass",
1956
+ SWC_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-swc",
1957
+ NWJS_URLBASE: "https://cdn.npmmirror.com/binaries/nwjs/v",
1958
+ PUPPETEER_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
1959
+ PUPPETEER_DOWNLOAD_BASE_URL: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
1960
+ PLAYWRIGHT_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/playwright",
1961
+ SENTRYCLI_CDNURL: "https://cdn.npmmirror.com/binaries/sentry-cli",
1962
+ SAUCECTL_INSTALL_BINARY_MIRROR: "https://cdn.npmmirror.com/binaries/saucectl",
1963
+ RE2_DOWNLOAD_MIRROR: "https://cdn.npmmirror.com/binaries/node-re2",
1964
+ RE2_DOWNLOAD_SKIP_PATH: "true",
1965
+ PRISMA_ENGINES_MIRROR: "https://cdn.npmmirror.com/binaries/prisma",
1966
+ npm_config_better_sqlite3_binary_host: "https://cdn.npmmirror.com/binaries/better-sqlite3",
1967
+ npm_config_keytar_binary_host: "https://cdn.npmmirror.com/binaries/keytar",
1968
+ npm_config_sharp_binary_host: "https://cdn.npmmirror.com/binaries/sharp",
1969
+ npm_config_sharp_libvips_binary_host: "https://cdn.npmmirror.com/binaries/sharp-libvips",
1970
+ npm_config_robotjs_binary_host: "https://cdn.npmmirror.com/binaries/robotjs"
1971
+ };
1972
+ //#endregion
1973
+ //#region src/commands/mirror/utils.ts
1974
+ /**
1975
+ * 在 vscode 里面设置镜像下载地址的环境变量,避免下载缓慢
1976
+ */
1977
+ function setMirror(obj, envs = chinaMirrorsEnvs) {
1978
+ const platforms = [
1979
+ "linux",
1980
+ "windows",
1981
+ "osx"
1982
+ ];
1983
+ const prefix = "terminal.integrated.env";
1984
+ if (typeof obj === "object" && obj) for (const platform of platforms) setByPath(obj, [prefix, platform].join(".").replaceAll(".", "\\."), envs);
1985
+ }
1986
+ //#endregion
1987
+ //#region src/commands/mirror/binaryMirror.ts
1988
+ /**
1989
+ * 根据中国大陆镜像源,自动向 VSCode settings.json 注入终端环境变量。
1990
+ */
1991
+ async function setVscodeBinaryMirror(cwd) {
1992
+ const mirrorConfig = await resolveCommandConfig("mirror", cwd);
1993
+ const targetJsonPath = path.resolve(cwd, ".vscode/settings.json");
1994
+ await fs$1.ensureFile(targetJsonPath);
1995
+ const json = parse(await fs$1.readFile(targetJsonPath, "utf8"), void 0, false);
1996
+ const env = mirrorConfig?.env ? {
1997
+ ...chinaMirrorsEnvs,
1998
+ ...mirrorConfig.env
1999
+ } : chinaMirrorsEnvs;
2000
+ json && typeof json === "object" && setMirror(json, env);
2001
+ await fs$1.writeFile(targetJsonPath, `${stringify(json, void 0, 2)}\n`, "utf8");
2002
+ }
2003
+ //#endregion
2004
+ //#region src/commands/templates.ts
2005
+ async function collectFiles(rootDir) {
2006
+ const files = [];
2007
+ async function walk(currentDir) {
2008
+ const entries = await readdir(currentDir, { withFileTypes: true });
2009
+ await Promise.all(entries.map(async (entry) => {
2010
+ const entryPath = path.join(currentDir, entry.name);
2011
+ if (entry.isDirectory()) {
2012
+ await walk(entryPath);
2013
+ return;
2014
+ }
2015
+ if (entry.isFile()) files.push(entryPath);
2016
+ }));
2017
+ }
2018
+ await walk(rootDir);
2019
+ return files;
2020
+ }
2021
+ function summarizeTemplateChecks(checks) {
2022
+ return checks.reduce((summary, check) => {
2023
+ summary[check.status] += 1;
2024
+ return summary;
2025
+ }, {
2026
+ pass: 0,
2027
+ warn: 0,
2028
+ fail: 0
2029
+ });
2030
+ }
2031
+ function checkDuplicates(choices, field) {
2032
+ const seen = /* @__PURE__ */ new Map();
2033
+ const duplicates = [];
2034
+ for (const choice of choices) {
2035
+ const value = choice[field];
2036
+ const previous = seen.get(value);
2037
+ if (previous) {
2038
+ duplicates.push([
2039
+ value,
2040
+ previous,
2041
+ choice.key
2042
+ ]);
2043
+ continue;
2044
+ }
2045
+ seen.set(value, choice.key);
2046
+ }
2047
+ return duplicates;
2048
+ }
2049
+ async function checkTemplates(options = {}) {
2050
+ const templatesDir$1 = options.templatesDir ?? templatesDir;
2051
+ const choices = getTemplateChoices();
2052
+ const checks = [];
2053
+ const sourceDuplicates = checkDuplicates(choices, "source");
2054
+ checks.push(sourceDuplicates.length ? {
2055
+ id: "unique-source",
2056
+ status: "fail",
2057
+ title: "模板 source 唯一性",
2058
+ detail: `存在重复 source:${sourceDuplicates.map(([value, first, second]) => `${value} (${first}, ${second})`).join(", ")}`,
2059
+ fix: "调整 template-data.mjs,确保每个模板 key 指向独立 source。"
2060
+ } : {
2061
+ id: "unique-source",
2062
+ status: "pass",
2063
+ title: "模板 source 唯一性",
2064
+ detail: "所有模板 source 都是唯一的。"
2065
+ });
2066
+ const targetDuplicates = checkDuplicates(choices, "target");
2067
+ checks.push(targetDuplicates.length ? {
2068
+ id: "unique-target",
2069
+ status: "fail",
2070
+ title: "模板 target 唯一性",
2071
+ detail: `存在重复 target:${targetDuplicates.map(([value, first, second]) => `${value} (${first}, ${second})`).join(", ")}`,
2072
+ fix: "调整 template-data.mjs,避免多个模板默认写入同一目标目录。"
2073
+ } : {
2074
+ id: "unique-target",
2075
+ status: "pass",
2076
+ title: "模板 target 唯一性",
2077
+ detail: "所有模板 target 都是唯一的。"
2078
+ });
2079
+ for (const choice of choices) {
2080
+ const sourceDir = path.join(templatesDir$1, choice.source);
2081
+ const packageJsonPath = path.join(sourceDir, "package.json");
2082
+ const sourceExists = await fs$1.pathExists(sourceDir);
2083
+ checks.push(sourceExists ? {
2084
+ id: "source-dir",
2085
+ template: choice.key,
2086
+ status: "pass",
2087
+ title: "模板目录",
2088
+ detail: `${choice.key} source exists: ${path.relative(templatesDir$1, sourceDir)}`
2089
+ } : {
2090
+ id: "source-dir",
2091
+ template: choice.key,
2092
+ status: "fail",
2093
+ title: "模板目录",
2094
+ detail: `${choice.key} 缺少 source 目录:${sourceDir}`,
2095
+ fix: "补齐模板目录,或修正 template-data.mjs 中的 source。"
2096
+ });
2097
+ checks.push(await fs$1.pathExists(packageJsonPath) ? {
2098
+ id: "package-json",
2099
+ template: choice.key,
2100
+ status: "pass",
2101
+ title: "模板 package.json",
2102
+ detail: `${choice.key} 包含 package.json。`
2103
+ } : {
2104
+ id: "package-json",
2105
+ template: choice.key,
2106
+ status: "fail",
2107
+ title: "模板 package.json",
2108
+ detail: `${choice.key} 缺少 package.json。`,
2109
+ fix: "模板根目录应包含 package.json,脚手架会基于它重写 name/version/repository。"
2110
+ });
2111
+ checks.push(choice.category && choice.description ? {
2112
+ id: "metadata",
2113
+ template: choice.key,
2114
+ status: "pass",
2115
+ title: "模板元数据",
2116
+ detail: `${choice.key} 已声明 category 和 description。`
2117
+ } : {
2118
+ id: "metadata",
2119
+ template: choice.key,
2120
+ status: "warn",
2121
+ title: "模板元数据",
2122
+ detail: `${choice.key} 缺少 category 或 description。`,
2123
+ fix: "补充 template-data.mjs 中的 category 和 description,方便 CLI 和文档展示。"
2124
+ });
2125
+ if (!sourceExists) continue;
2126
+ const skippedFiles = (await collectFiles(sourceDir)).filter((file) => shouldSkipTemplatePath(sourceDir, file)).map((file) => path.relative(sourceDir, file));
2127
+ checks.push(skippedFiles.length ? {
2128
+ id: "filtered-files",
2129
+ template: choice.key,
2130
+ status: "fail",
2131
+ title: "模板临时文件",
2132
+ detail: `${choice.key} 包含会被脚手架过滤的文件:${skippedFiles.join(", ")}`,
2133
+ fix: "删除模板源目录里的临时、缓存或生成文件。"
2134
+ } : {
2135
+ id: "filtered-files",
2136
+ template: choice.key,
2137
+ status: "pass",
2138
+ title: "模板临时文件",
2139
+ detail: `${choice.key} 没有检测到会被过滤的临时文件。`
2140
+ });
2141
+ }
2142
+ return {
2143
+ templatesDir: templatesDir$1,
2144
+ templateCount: choices.length,
2145
+ checks,
2146
+ summary: summarizeTemplateChecks(checks)
2147
+ };
2148
+ }
2149
+ //#endregion
2150
+ //#region src/commands/upgrade/agents.ts
2151
+ const crlfPattern$1 = /\r\n/g;
2152
+ const h2HeadingPrefixPattern = /^##\s+/;
2153
+ function normalizeEol$1(input) {
2154
+ return input.replace(crlfPattern$1, "\n");
2155
+ }
2156
+ function normalizeComparableContent(input) {
2157
+ return normalizeEol$1(input).trimEnd();
2158
+ }
2159
+ function normalizeHeadingKey(line) {
2160
+ return line.replace(h2HeadingPrefixPattern, "").trim().toLowerCase();
2161
+ }
2162
+ function trimEdgeEmptyLines(lines) {
2163
+ const next = [...lines];
2164
+ while (next.length) {
2165
+ const first = next[0];
2166
+ if (first === void 0 || first.trim().length > 0) break;
2167
+ next.shift();
2168
+ }
2169
+ while (next.length) {
2170
+ const last = next.at(-1);
2171
+ if (last === void 0 || last.trim().length > 0) break;
2172
+ next.pop();
2173
+ }
2174
+ return next;
2175
+ }
2176
+ function parseMarkdownByH2(content) {
2177
+ const lines = normalizeEol$1(content).split("\n");
2178
+ const preamble = [];
2179
+ const sections = [];
2180
+ let current;
2181
+ for (const line of lines) {
2182
+ if (h2HeadingPrefixPattern.test(line)) {
2183
+ if (current) sections.push(current);
2184
+ current = {
2185
+ key: normalizeHeadingKey(line),
2186
+ lines: [line]
2187
+ };
2188
+ continue;
2189
+ }
2190
+ if (current) {
2191
+ current.lines.push(line);
2192
+ continue;
2193
+ }
2194
+ preamble.push(line);
2195
+ }
2196
+ if (current) sections.push(current);
2197
+ return {
2198
+ preamble,
2199
+ sections
2200
+ };
2201
+ }
2202
+ function mergePlainText(source, target) {
2203
+ const sourceLines = trimEdgeEmptyLines(normalizeEol$1(source).split("\n"));
2204
+ const result = trimEdgeEmptyLines(normalizeEol$1(target).split("\n"));
2205
+ const seen = new Set(result);
2206
+ for (const line of sourceLines) {
2207
+ if (!line.trim()) continue;
2208
+ if (seen.has(line)) continue;
2209
+ seen.add(line);
2210
+ result.push(line);
2211
+ }
2212
+ return `${result.join("\n")}\n`;
2213
+ }
2214
+ function getSectionSignature(section) {
2215
+ return `${section.key}\n${trimEdgeEmptyLines(section.lines).join("\n")}`;
2216
+ }
2217
+ /**
2218
+ * Merge AGENTS instructions by keeping existing sections and filling missing sections
2219
+ * from source defaults. This avoids destructive overwrite while still syncing updates.
2220
+ */
2221
+ function mergeAgentsMarkdown(source, target) {
2222
+ const sourceParsed = parseMarkdownByH2(source);
2223
+ const targetParsed = parseMarkdownByH2(target);
2224
+ if (!sourceParsed.sections.length || !targetParsed.sections.length) return mergePlainText(source, target);
2225
+ const sourceSectionKeys = new Set(sourceParsed.sections.map((section) => section.key));
2226
+ const targetSectionMap = new Map(targetParsed.sections.map((section) => [section.key, section]));
2227
+ const mergedSections = [];
2228
+ for (const section of sourceParsed.sections) mergedSections.push(targetSectionMap.get(section.key) ?? section);
2229
+ const seenTargetOnlySectionSignatures = /* @__PURE__ */ new Set();
2230
+ for (const section of targetParsed.sections) if (!sourceSectionKeys.has(section.key)) {
2231
+ const signature = getSectionSignature(section);
2232
+ if (seenTargetOnlySectionSignatures.has(signature)) continue;
2233
+ seenTargetOnlySectionSignatures.add(signature);
2234
+ mergedSections.push(section);
2235
+ }
2236
+ const preamble = trimEdgeEmptyLines(targetParsed.preamble.length ? targetParsed.preamble : sourceParsed.preamble);
2237
+ const blocks = [];
2238
+ if (preamble.length) blocks.push(preamble.join("\n"));
2239
+ for (const section of mergedSections) blocks.push(trimEdgeEmptyLines(section.lines).join("\n"));
2240
+ return `${blocks.filter(Boolean).join("\n\n")}\n`;
2241
+ }
2242
+ /**
2243
+ * Compare AGENTS markdown with normalized EOL and trailing newline differences ignored.
2244
+ */
2245
+ function isAgentsMarkdownEquivalent(left, right) {
2246
+ return normalizeComparableContent(left) === normalizeComparableContent(right);
2247
+ }
2248
+ //#endregion
2249
+ //#region src/commands/upgrade/overwrite.ts
2250
+ function asBuffer(data) {
2251
+ return typeof data === "string" ? Buffer.from(data) : data;
2252
+ }
2253
+ async function evaluateWriteIntent(targetPath, options) {
2254
+ const { skipOverwrite, source } = options;
2255
+ if (!await fs$1.pathExists(targetPath)) return {
2256
+ type: "write",
2257
+ reason: "missing"
2258
+ };
2259
+ if (skipOverwrite) return {
2260
+ type: "skip",
2261
+ reason: "skipOverwrite"
2262
+ };
2263
+ const src = asBuffer(source);
2264
+ let destSize = 0;
2265
+ try {
2266
+ destSize = (await fs$1.stat(targetPath)).size;
2267
+ } catch {
2268
+ return {
2269
+ type: "write",
2270
+ reason: "missing"
2271
+ };
2272
+ }
2273
+ if (destSize !== src.length) return {
2274
+ type: "prompt",
2275
+ reason: "changed"
2276
+ };
2277
+ if (!isFileChanged(src, await fs$1.readFile(targetPath))) return {
2278
+ type: "skip",
2279
+ reason: "identical"
2280
+ };
2281
+ return {
2282
+ type: "prompt",
2283
+ reason: "changed"
2284
+ };
2285
+ }
2286
+ async function scheduleOverwrite(intent, options) {
2287
+ const { relPath, targetPath, action, pending } = options;
2288
+ if (intent.type === "write") {
2289
+ await action();
2290
+ return;
2291
+ }
2292
+ if (intent.type === "prompt") pending.push({
2293
+ relPath,
2294
+ targetPath,
2295
+ action
2296
+ });
2297
+ }
2298
+ async function flushPendingOverwrites(pending, options = {}) {
2299
+ if (!pending.length) return;
2300
+ if (options.noOverwrite) {
2301
+ for (const item of pending) logger.info(`skip changed file: ${item.relPath}`);
2302
+ return;
2303
+ }
2304
+ if (options.yes || options.overwrite) {
2305
+ for (const item of pending) await item.action();
2306
+ return;
2307
+ }
2308
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
2309
+ for (const item of pending) logger.info(`skip changed file in non-interactive mode: ${item.relPath}`);
2310
+ return;
2311
+ }
2312
+ const selected = await checkbox({
2313
+ message: "检测到以下文件内容与当前仓库不同,选择需要覆盖的文件",
2314
+ choices: pending.map((item) => ({
2315
+ name: pc.greenBright(item.relPath),
2316
+ value: item.targetPath,
2317
+ checked: false
2318
+ })),
2319
+ loop: false
2320
+ });
2321
+ const selectedSet = new Set(selected);
2322
+ for (const item of pending) if (selectedSet.has(item.targetPath)) await item.action();
2323
+ }
2324
+ const scriptsEntries = Object.entries({
2325
+ "setup": "repo setup",
2326
+ "new": "repo new",
2327
+ "check": "repo check",
2328
+ "doctor": "repo doctor",
2329
+ "sync": "repo sync",
2330
+ "clean:repo": "repo clean",
2331
+ "mirror": "repo mirror",
2332
+ "script:init": "repo init",
2333
+ "script:sync": "repo sync",
2334
+ "script:clean": "repo clean",
2335
+ "script:mirror": "repo mirror",
2336
+ "commitlint": "commitlint --edit"
2337
+ });
2338
+ //#endregion
2339
+ //#region src/commands/upgrade/pkg-json.ts
2340
+ const NON_OVERRIDABLE_PREFIXES = ["workspace:", "catalog:"];
2341
+ const toolPackageNames = ["repoctl", name$1];
2342
+ function parseVersion(input) {
2343
+ if (typeof input !== "string" || input.trim().length === 0) return null;
2344
+ try {
2345
+ return minVersion(input) ?? coerce(input);
2346
+ } catch {
2347
+ return null;
2348
+ }
2349
+ }
2350
+ function hasNonOverridablePrefix(version) {
2351
+ if (typeof version !== "string") return false;
2352
+ return NON_OVERRIDABLE_PREFIXES.some((prefix) => version.startsWith(prefix));
2353
+ }
2354
+ function shouldAssignVersion(currentVersion, nextVersion) {
2355
+ if (typeof currentVersion !== "string" || currentVersion.trim().length === 0) return true;
2356
+ if (currentVersion === nextVersion) return false;
2357
+ const current = parseVersion(currentVersion);
2358
+ const next = parseVersion(nextVersion);
2359
+ if (!current || !next) return true;
2360
+ return !gte(current, next);
2361
+ }
2362
+ function resolvePreferredToolPackageName(sourceDevDeps, targetDevDeps) {
2363
+ for (const depName of toolPackageNames) if (typeof targetDevDeps[depName] === "string" && targetDevDeps[depName].length > 0) return depName;
2364
+ for (const depName of toolPackageNames) if (typeof sourceDevDeps[depName] === "string" && sourceDevDeps[depName].length > 0) return depName;
2365
+ return "repoctl";
2366
+ }
2367
+ /**
2368
+ * 将内置 package.json 内容合并进目标工程:
2369
+ * - 同步依赖(保留 workspace: 前缀的版本)
2370
+ * - 确保 @icebreakers/monorepo 使用最新版本
2371
+ * - 写入预置脚本
2372
+ */
2373
+ function setPkgJson(sourcePkgJson, targetPkgJson, options) {
2374
+ const packageManager = sourcePkgJson.packageManager ?? "";
2375
+ const sourceDeps = sourcePkgJson.dependencies ?? {};
2376
+ const sourceDevDeps = sourcePkgJson.devDependencies ?? {};
2377
+ const targetDeps = { ...targetPkgJson.dependencies ?? {} };
2378
+ const targetDevDeps = { ...targetPkgJson.devDependencies ?? {} };
2379
+ const preferredToolPackageName = resolvePreferredToolPackageName(sourceDevDeps, targetDevDeps);
2380
+ if (packageManager && !targetPkgJson.packageManager) targetPkgJson.packageManager = packageManager;
2381
+ for (const [depName, depVersion] of Object.entries(sourceDeps)) {
2382
+ if (typeof depVersion !== "string") continue;
2383
+ const targetVersion = targetDeps[depName];
2384
+ if (hasNonOverridablePrefix(targetVersion)) continue;
2385
+ if (shouldAssignVersion(targetVersion, depVersion)) targetDeps[depName] = depVersion;
2386
+ }
2387
+ if (Object.keys(targetDeps).length) targetPkgJson.dependencies = targetDeps;
2388
+ for (const [depName, depVersion] of Object.entries(sourceDevDeps)) {
2389
+ if (typeof depVersion !== "string") continue;
2390
+ if (toolPackageNames.includes(depName)) {
2391
+ if (depName !== preferredToolPackageName) continue;
2392
+ const nextVersion = `^${version$1}`;
2393
+ const targetVersion = targetDevDeps[depName];
2394
+ if (!hasNonOverridablePrefix(targetVersion) && shouldAssignVersion(targetVersion, nextVersion)) targetDevDeps[depName] = nextVersion;
2395
+ } else {
2396
+ const targetVersion = targetDevDeps[depName];
2397
+ if (hasNonOverridablePrefix(targetVersion)) continue;
2398
+ if (shouldAssignVersion(targetVersion, depVersion)) targetDevDeps[depName] = depVersion;
2399
+ }
2400
+ }
2401
+ for (const depName of toolPackageNames) if (depName !== preferredToolPackageName && depName in targetDevDeps && preferredToolPackageName in targetDevDeps) delete targetDevDeps[depName];
2402
+ if (Object.keys(targetDevDeps).length) targetPkgJson.devDependencies = targetDevDeps;
2403
+ const scriptPairs = options?.scripts ? Object.entries(options.scripts) : scriptsEntries;
2404
+ if (scriptPairs.length) {
2405
+ const scripts = { ...targetPkgJson.scripts ?? {} };
2406
+ for (const [scriptName, scriptCmd] of scriptPairs) scripts[scriptName] = scriptCmd;
2407
+ targetPkgJson.scripts = scripts;
2408
+ }
2409
+ }
2410
+ //#endregion
2411
+ //#region src/commands/upgrade/workspace.ts
2412
+ function isPlainObject(value) {
2413
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2414
+ }
2415
+ function normalizeQuotedString(value) {
2416
+ const trimmed = value.trim();
2417
+ const first = trimmed[0];
2418
+ if ((first === "'" || first === "\"") && trimmed.endsWith(first)) return trimmed.slice(1, -1);
2419
+ return trimmed;
2420
+ }
2421
+ function normalizeWorkspaceManifest(manifest) {
2422
+ if (isPlainObject(manifest)) return { ...manifest };
2423
+ return {};
2424
+ }
2425
+ function mergeUniqueArray(target, source) {
2426
+ const seen = new Set(target.map((item) => {
2427
+ return typeof item === "string" ? normalizeQuotedString(item) : item;
2428
+ }));
2429
+ const result = [...target];
2430
+ for (const item of source) {
2431
+ const key = typeof item === "string" ? normalizeQuotedString(item) : item;
2432
+ if (!seen.has(key)) {
2433
+ seen.add(key);
2434
+ result.push(item);
2435
+ }
2436
+ }
2437
+ return result;
2438
+ }
2439
+ /**
2440
+ * Merge pnpm workspace manifests by filling missing fields only.
2441
+ * Existing values take precedence; arrays are deduped while keeping target order.
2442
+ */
2443
+ function mergeWorkspaceManifest(source, target) {
2444
+ const normalizedSource = normalizeWorkspaceManifest(source);
2445
+ const normalizedTarget = normalizeWorkspaceManifest(target);
2446
+ const result = { ...normalizedTarget };
2447
+ for (const [key, value] of Object.entries(normalizedSource)) {
2448
+ const current = normalizedTarget[key];
2449
+ if (current === void 0) {
2450
+ result[key] = value;
2451
+ continue;
2452
+ }
2453
+ if (Array.isArray(current) && Array.isArray(value)) {
2454
+ result[key] = mergeUniqueArray(current, value);
2455
+ continue;
2456
+ }
2457
+ if (isPlainObject(current) && isPlainObject(value)) {
2458
+ result[key] = mergeWorkspaceManifest(value, current);
2459
+ continue;
2460
+ }
2461
+ result[key] = current;
2462
+ }
2463
+ return result;
2464
+ }
2465
+ //#endregion
2466
+ //#region src/commands/upgrade/index.ts
2467
+ const crlfPattern = /\r\n/g;
2468
+ function normalizeEol(input) {
2469
+ return input.replace(crlfPattern, "\n");
2470
+ }
2471
+ function normalizeGitignoreLine(line) {
2472
+ const trimmed = line.trim();
2473
+ if (!trimmed) return "";
2474
+ if (trimmed.startsWith("#")) return `#${trimmed.slice(1).trim()}`;
2475
+ return trimmed;
2476
+ }
2477
+ function isTextEquivalent(left, right) {
2478
+ return normalizeEol(left).trimEnd() === normalizeEol(right).trimEnd();
2479
+ }
2480
+ function mergeGitignore(source, target) {
2481
+ const sourceLines = normalizeEol(source).split("\n");
2482
+ const result = normalizeEol(target).split("\n");
2483
+ const seen = new Set(result.map((line) => normalizeGitignoreLine(line)).filter(Boolean));
2484
+ for (const line of sourceLines) {
2485
+ const normalized = normalizeGitignoreLine(line);
2486
+ if (!normalized || seen.has(normalized)) continue;
2487
+ seen.add(normalized);
2488
+ result.push(line);
2489
+ }
2490
+ while (result.length) {
2491
+ const last = result.at(-1);
2492
+ if (last === void 0 || last.trim().length > 0) break;
2493
+ result.pop();
2494
+ }
2495
+ return `${result.join("\n")}\n`;
2496
+ }
2497
+ /**
2498
+ * 将 assets 目录的模版文件同步到工程中,实现一键升级脚手架能力。
2499
+ */
2500
+ async function upgradeMonorepo(opts) {
2501
+ await ensureTemplateAssetsPrepared();
2502
+ const cwd = opts.cwd ?? process.cwd();
2503
+ const upgradeConfig = await resolveCommandConfig("upgrade", cwd);
2504
+ const merged = {
2505
+ cwd,
2506
+ outDir: "",
2507
+ ...upgradeConfig ?? {},
2508
+ ...opts
2509
+ };
2510
+ const outDir = merged.outDir ?? "";
2511
+ const absOutDir = path.isAbsolute(outDir) ? outDir : path.join(cwd, outDir);
2512
+ const repoName = await new GitClient({ baseDir: cwd }).getRepoName();
2513
+ const useCoreAssets = merged.core ?? false;
2514
+ merged.core = useCoreAssets;
2515
+ const baseTargets = getAssetTargets(useCoreAssets);
2516
+ const configTargets = upgradeConfig?.targets ?? [];
2517
+ const mergeTargets = upgradeConfig?.mergeTargets;
2518
+ let targets = configTargets.length ? mergeTargets === false ? [...configTargets] : [...new Set([...baseTargets, ...configTargets])] : baseTargets;
2519
+ if (merged.interactive) if (!process.stdin.isTTY || !process.stdout.isTTY) logger.info("skip interactive target selection in non-interactive mode");
2520
+ else targets = await checkbox({
2521
+ message: "选择你需要的文件",
2522
+ choices: targets.map((x) => {
2523
+ return {
2524
+ value: x,
2525
+ checked: true
2526
+ };
2527
+ })
2528
+ });
2529
+ const regexpArr = targets.map((x) => {
2530
+ return new RegExp(`^${escapeStringRegexp(x)}`);
2531
+ });
2532
+ const skipChangesetMarkdown = upgradeConfig?.skipChangesetMarkdown ?? true;
2533
+ const scriptOverrides = upgradeConfig?.scripts;
2534
+ const skipOverwrite = merged.noOverwrite ? true : merged.skipOverwrite;
2535
+ const buildWriteIntentOptions = (source) => {
2536
+ return skipOverwrite === void 0 ? { source } : {
2537
+ skipOverwrite,
2538
+ source
2539
+ };
2540
+ };
2541
+ const pendingOverwrites = [];
2542
+ for await (const file of klaw(assetsDir, { filter(p) {
2543
+ return isMatch(toWorkspaceGitignorePath(path.relative(assetsDir, p)), regexpArr);
2544
+ } })) {
2545
+ if (!file.stats.isFile()) continue;
2546
+ const relPath = toWorkspaceGitignorePath(path.relative(assetsDir, file.path));
2547
+ if (skipChangesetMarkdown && relPath.startsWith(".changeset/") && relPath.endsWith(".md")) continue;
2548
+ const targetPath = path.resolve(absOutDir, relPath);
2549
+ try {
2550
+ if (relPath === "package.json") {
2551
+ if (!await fs$1.pathExists(targetPath)) continue;
2552
+ const sourcePkgJson = await fs$1.readJson(file.path);
2553
+ const targetPkgJson = await fs$1.readJson(targetPath);
2554
+ setPkgJson(sourcePkgJson, targetPkgJson, scriptOverrides ? { scripts: scriptOverrides } : void 0);
2555
+ const data = `${JSON.stringify(targetPkgJson, void 0, 2)}\n`;
2556
+ const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
2557
+ const action = async () => {
2558
+ await fs$1.outputFile(targetPath, data, "utf8");
2559
+ logger.success(targetPath);
2560
+ };
2561
+ await scheduleOverwrite(intent, {
2562
+ relPath,
2563
+ targetPath,
2564
+ action,
2565
+ pending: pendingOverwrites
2566
+ });
2567
+ continue;
2568
+ }
2569
+ if (relPath === "pnpm-workspace.yaml") {
2570
+ const sourceManifest = normalizeWorkspaceManifest(YAML.parse(await fs$1.readFile(file.path, "utf8")));
2571
+ const exists = await fs$1.pathExists(targetPath);
2572
+ const targetManifest = exists ? normalizeWorkspaceManifest(YAML.parse(await fs$1.readFile(targetPath, "utf8"))) : normalizeWorkspaceManifest({});
2573
+ const mergedManifest = exists ? mergeWorkspaceManifest(sourceManifest, targetManifest) : sourceManifest;
2574
+ const data = YAML.stringify(mergedManifest, { singleQuote: true });
2575
+ const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
2576
+ const action = async () => {
2577
+ await fs$1.outputFile(targetPath, data, "utf8");
2578
+ logger.success(targetPath);
2579
+ };
2580
+ await scheduleOverwrite(intent, {
2581
+ relPath,
2582
+ targetPath,
2583
+ action,
2584
+ pending: pendingOverwrites
2585
+ });
2586
+ continue;
2587
+ }
2588
+ if (relPath === ".gitignore") {
2589
+ const source = await fs$1.readFile(file.path, "utf8");
2590
+ const exists = await fs$1.pathExists(targetPath);
2591
+ const target = exists ? await fs$1.readFile(targetPath, "utf8") : "";
2592
+ const data = exists ? mergeGitignore(source, target) : source;
2593
+ if (exists && isTextEquivalent(target, data)) continue;
2594
+ const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
2595
+ const action = async () => {
2596
+ await fs$1.outputFile(targetPath, data, "utf8");
2597
+ logger.success(targetPath);
2598
+ };
2599
+ await scheduleOverwrite(intent, {
2600
+ relPath,
2601
+ targetPath,
2602
+ action,
2603
+ pending: pendingOverwrites
2604
+ });
2605
+ continue;
2606
+ }
2607
+ if (relPath === "AGENTS.md") {
2608
+ const source = await fs$1.readFile(file.path, "utf8");
2609
+ const exists = await fs$1.pathExists(targetPath);
2610
+ const target = exists ? await fs$1.readFile(targetPath, "utf8") : "";
2611
+ const data = exists ? mergeAgentsMarkdown(source, target) : source;
2612
+ if (exists && isAgentsMarkdownEquivalent(target, data)) continue;
2613
+ const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
2614
+ const action = async () => {
2615
+ await fs$1.outputFile(targetPath, data, "utf8");
2616
+ logger.success(targetPath);
2617
+ };
2618
+ await scheduleOverwrite(intent, {
2619
+ relPath,
2620
+ targetPath,
2621
+ action,
2622
+ pending: pendingOverwrites
2623
+ });
2624
+ continue;
2625
+ }
2626
+ if (relPath === ".changeset/config.json" && repoName) {
2627
+ const changesetJson = await fs$1.readJson(file.path);
2628
+ setByPath(changesetJson, "changelog.1.repo", repoName);
2629
+ const data = `${JSON.stringify(changesetJson, void 0, 2)}\n`;
2630
+ const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
2631
+ const action = async () => {
2632
+ await fs$1.outputFile(targetPath, data, "utf8");
2633
+ logger.success(targetPath);
2634
+ };
2635
+ await scheduleOverwrite(intent, {
2636
+ relPath,
2637
+ targetPath,
2638
+ action,
2639
+ pending: pendingOverwrites
2640
+ });
2641
+ continue;
2642
+ }
2643
+ if (relPath === "LICENSE") {
2644
+ const source = await fs$1.readFile(file.path);
2645
+ const intent = await evaluateWriteIntent(targetPath, {
2646
+ skipOverwrite: true,
2647
+ source
2648
+ });
2649
+ const action = async () => {
2650
+ await fs$1.outputFile(targetPath, source);
2651
+ logger.success(targetPath);
2652
+ };
2653
+ await scheduleOverwrite(intent, {
2654
+ relPath,
2655
+ targetPath,
2656
+ action,
2657
+ pending: pendingOverwrites
2658
+ });
2659
+ continue;
2660
+ }
2661
+ if (relPath === ".github/ISSUE_TEMPLATE/config.yml") {
2662
+ const data = updateIssueTemplateConfig(await fs$1.readFile(file.path, "utf8"), repoName);
2663
+ const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
2664
+ const action = async () => {
2665
+ await fs$1.outputFile(targetPath, data);
2666
+ logger.success(targetPath);
2667
+ };
2668
+ await scheduleOverwrite(intent, {
2669
+ relPath,
2670
+ targetPath,
2671
+ action,
2672
+ pending: pendingOverwrites
2673
+ });
2674
+ continue;
2675
+ }
2676
+ let source = await fs$1.readFile(file.path);
2677
+ if (/\.(?:js|mjs|ts|mts|cjs|cts)$/.test(relPath)) source = Buffer.from(migrateLegacyToolingReferences(source.toString("utf8"), "repoctl/tooling"));
2678
+ const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(source));
2679
+ const action = async () => {
2680
+ await fs$1.outputFile(targetPath, source);
2681
+ logger.success(targetPath);
2682
+ };
2683
+ await scheduleOverwrite(intent, {
2684
+ relPath,
2685
+ targetPath,
2686
+ action,
2687
+ pending: pendingOverwrites
2688
+ });
2689
+ } catch (error) {
2690
+ if (isIgnorableFsError(error)) continue;
2691
+ throw error;
2692
+ }
2693
+ }
2694
+ await flushPendingOverwrites(pendingOverwrites, {
2695
+ ...merged.yes !== void 0 ? { yes: merged.yes } : {},
2696
+ ...merged.overwrite !== void 0 ? { overwrite: merged.overwrite } : {},
2697
+ ...merged.noOverwrite !== void 0 ? { noOverwrite: merged.noOverwrite } : {}
2698
+ });
2699
+ }
2700
+ //#endregion
2701
+ //#region src/commands/index.ts
2702
+ var commands_exports = /* @__PURE__ */ __exportAll({
2703
+ GitClient: () => GitClient,
2704
+ checkTemplates: () => checkTemplates,
2705
+ cleanProjects: () => cleanProjects,
2706
+ collectEnvInfo: () => collectEnvInfo,
2707
+ collectEnvPaths: () => collectEnvPaths,
2708
+ collectEnvSnapshot: () => collectEnvSnapshot,
2709
+ collectEnvSupportBundle: () => collectEnvSupportBundle,
2710
+ createNewProject: () => createNewProject,
2711
+ createTimestampFolderName: () => createTimestampFolderName,
2712
+ defaultAgenticBaseDir: () => defaultAgenticBaseDir,
2713
+ generateAgenticTemplate: () => generateAgenticTemplate,
2714
+ generateAgenticTemplates: () => generateAgenticTemplates,
2715
+ getCreateChoices: () => getCreateChoices,
2716
+ getKnownRepoCheckCommands: () => getKnownRepoCheckCommands,
2717
+ getSkillTargetPaths: () => getSkillTargetPaths,
2718
+ getTemplateMap: () => getTemplateMap,
2719
+ getWorkspaceData: () => getWorkspaceData,
2720
+ getWorkspacePackages: () => getWorkspacePackages,
2721
+ init: () => init,
2722
+ initMetadata: () => initMetadata,
2723
+ initTooling: () => initTooling,
2724
+ initToolingTargets: () => initToolingTargets,
2725
+ inspectMonorepoConfig: () => inspectMonorepoConfig,
2726
+ loadAgenticTasks: () => loadAgenticTasks,
2727
+ normalizeInitToolingTargets: () => normalizeInitToolingTargets,
2728
+ resolveCreateNewProjectPlan: () => resolveCreateNewProjectPlan,
2729
+ resolveFullWorkspaceCheckPlan: () => resolveFullWorkspaceCheckPlan,
2730
+ resolveRecommendedCheckPlan: () => resolveRecommendedCheckPlan,
2731
+ runDoctor: () => runDoctor,
2732
+ runRecommendedCheck: () => runRecommendedCheck,
2733
+ setVscodeBinaryMirror: () => setVscodeBinaryMirror,
2734
+ skillTargets: () => skillTargets,
2735
+ syncSkills: () => syncSkills,
2736
+ templateMap: () => templateMap,
2737
+ upgradeMonorepo: () => upgradeMonorepo,
2738
+ verifyCommitMsg: () => verifyCommitMsg,
2739
+ verifyPreCommit: () => verifyPreCommit,
2740
+ verifyPrePush: () => verifyPrePush,
2741
+ verifyStagedTypecheck: () => verifyStagedTypecheck
2742
+ });
2743
+ //#endregion
2744
+ export { isFileChanged as A, verifyPreCommit as B, getSkillTargetPaths as C, isMatch as D, escapeStringRegexp as E, getKnownRepoCheckCommands as F, generateAgenticTemplate as G, verifyStagedTypecheck as H, resolveFullWorkspaceCheckPlan as I, GitClient as J, generateAgenticTemplates as K, resolveRecommendedCheckPlan as L, toPublishGitignorePath as M, toWorkspaceGitignorePath as N, setByPath as O, updateIssueTemplateConfig as P, runRecommendedCheck as R, cleanProjects as S, syncSkills as T, createTimestampFolderName as U, verifyPrePush as V, defaultAgenticBaseDir as W, getCreateChoices as _, init as a, templateMap as b, normalizeInitToolingTargets as c, collectEnvPaths as d, collectEnvSnapshot as f, defaultTemplate as g, createNewProject as h, setVscodeBinaryMirror as i, isGitignoreFile as j, getFileHash as k, createContext as l, runDoctor as m, upgradeMonorepo as n, initMetadata as o, collectEnvSupportBundle as p, loadAgenticTasks as q, checkTemplates as r, initTooling as s, commands_exports as t, collectEnvInfo as u, getTemplateMap as v, skillTargets as w, inspectMonorepoConfig as x, resolveCreateNewProjectPlan as y, verifyCommitMsg as z };