@icebreakers/monorepo 5.6.0 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +2 -0
  2. package/dist/baseline-DPfotf4y.mjs +146 -0
  3. package/dist/bundle-B9vRch4R.mjs +49 -0
  4. package/dist/catalog-CDEyc1uA.mjs +299 -0
  5. package/dist/cli.mjs +1487 -156
  6. package/dist/commands-TS8ABFdP.mjs +13820 -0
  7. package/dist/config-C38c_Q8L.mjs +66 -0
  8. package/dist/{create-flow-CXRhfGbb.mjs → create-flow-CCr2hfSY.mjs} +90 -24
  9. package/dist/deps-CUdI2DaB.mjs +47 -0
  10. package/dist/execute-PX1hT0qv.mjs +68 -0
  11. package/dist/execute-Vi4qHe-D.mjs +663 -0
  12. package/dist/format-DZ7L34rf.mjs +28 -0
  13. package/dist/index-CoCTFWZJ.d.mts +2150 -0
  14. package/dist/index.d.mts +1738 -112
  15. package/dist/index.mjs +60 -7
  16. package/dist/inputs-_xIVONmB.mjs +50 -0
  17. package/dist/npm-B25nrSyz.mjs +82 -0
  18. package/dist/plan-B5aE_WNF.mjs +75 -0
  19. package/dist/run-Lu7y1bNf.mjs +165 -0
  20. package/dist/save-CdCf630Z.mjs +79 -0
  21. package/dist/scan-4nboHNXP.mjs +293 -0
  22. package/dist/template-drift-BBhnrHY1.mjs +2740 -0
  23. package/dist/tooling-entry.d.mts +1 -1
  24. package/dist/tooling-entry.mjs +2 -2
  25. package/dist/transaction-DAhY8EpG.mjs +168 -0
  26. package/dist/tsconfig-CGntrzBM.mjs +1483 -0
  27. package/dist/{vitest-Blzbh8xZ.mjs → vitest-DkGh4Ygo.mjs} +1 -1
  28. package/dist/workspace-tasks-CnB8kkS0.mjs +4435 -0
  29. package/package.json +22 -4
  30. package/resources/api-report/runner.cjs +76 -0
  31. package/resources/devcontainer/setup.mjs +36 -0
  32. package/resources/knip/reporter.mjs +46 -0
  33. package/resources/maintenance/migration-lanes.mjs +141 -0
  34. package/resources/maintenance/migration-lock.mjs +119 -0
  35. package/resources/maintenance/migrations.mjs +215 -0
  36. package/resources/maintenance/presets.mjs +130 -0
  37. package/resources/maintenance/validate.mjs +233 -0
  38. package/resources/maintenance/workflow.yml +151 -0
  39. package/resources/skills/repoctl/SKILL.md +2 -0
  40. package/resources/skills/repoctl/references/commands.md +224 -13
  41. package/resources/skills/repoctl/references/config.md +70 -6
  42. package/resources/skills/repoctl/references/dependencies.md +37 -0
  43. package/resources/skills/repoctl/references/knip.md +34 -0
  44. package/resources/skills/repoctl/references/templates.md +23 -0
  45. package/dist/commands-D4xZQ5t-.mjs +0 -5685
  46. package/dist/config-p842Knhq.mjs +0 -114
  47. package/dist/index-Bl_PB2Ch.d.mts +0 -1039
  48. package/dist/tsconfig-BrjI_5yI.mjs +0 -75
  49. package/dist/types-MAUIQpfp.mjs +0 -499
  50. package/dist/workspace-MCKewElu.mjs +0 -123
@@ -0,0 +1,663 @@
1
+ import { H as signalExitCode, J as getWorkspaceGraph, St as localize, V as executeCheckTask, Z as getWorkspaceImpact, jt as fs$1, tt as resolveWorkspaceGraphNode } from "./workspace-tasks-CnB8kkS0.mjs";
2
+ import { d as loadMonorepoConfig, m as resolveToolingConfig } from "./tsconfig-CGntrzBM.mjs";
3
+ import process from "node:process";
4
+ import { createConsola } from "consola";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
+ import fs, { existsSync, readFileSync, realpathSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import crossSpawn from "cross-spawn";
10
+ import { parse } from "comment-json";
11
+ import { performance } from "node:perf_hooks";
12
+ //#region src/core/logger.ts
13
+ /**
14
+ * 统一的日志实例,便于在命令行中输出带有前缀和颜色的消息。
15
+ */
16
+ const logger = createConsola();
17
+ //#endregion
18
+ //#region src/commands/verify/run.ts
19
+ function runPnpmCommand(cwd, label, args, spawn) {
20
+ process.stdout.write(`${label}\n`);
21
+ const options = {
22
+ cwd,
23
+ stdio: "inherit"
24
+ };
25
+ const result = (spawn === spawnSync ? crossSpawn.sync : spawn)("pnpm", args, options);
26
+ if (result.status !== 0) process.exit(result.status ?? 1);
27
+ }
28
+ //#endregion
29
+ //#region src/commands/verify/staged.ts
30
+ const gitDirName = ".git";
31
+ const typecheckExtensions = /* @__PURE__ */ new Set([
32
+ ".ts",
33
+ ".tsx",
34
+ ".mts",
35
+ ".cts",
36
+ ".vue",
37
+ ".astro",
38
+ ".mdx"
39
+ ]);
40
+ const typecheckBasenames = /* @__PURE__ */ new Set(["package.json"]);
41
+ function hasTypecheckScript(dir) {
42
+ const packageJsonPath = path.join(dir, "package.json");
43
+ if (!fs.existsSync(packageJsonPath)) return false;
44
+ try {
45
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
46
+ return typeof packageJson.scripts?.typecheck === "string" && packageJson.scripts.typecheck.length > 0;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+ function findRepositoryRoot(startDir) {
52
+ let current = path.resolve(startDir);
53
+ while (true) {
54
+ if (fs.existsSync(path.join(current, gitDirName))) return current;
55
+ const next = path.dirname(current);
56
+ if (next === current) return path.resolve(startDir);
57
+ current = next;
58
+ }
59
+ }
60
+ function resolveTypecheckWorkspaceDir(filePath, cwd) {
61
+ const workspaceRoot = findRepositoryRoot(cwd);
62
+ let current = path.dirname(path.resolve(cwd, filePath));
63
+ while (current.startsWith(workspaceRoot)) {
64
+ if (current !== cwd && hasTypecheckScript(current)) return current;
65
+ const next = path.dirname(current);
66
+ if (next === current) break;
67
+ current = next;
68
+ }
69
+ return workspaceRoot;
70
+ }
71
+ /**
72
+ * 对暂存区中涉及类型检查的文件,按最近的 workspace 归属执行 `typecheck`。
73
+ *
74
+ * 当前识别的扩展名:`.ts`、`.tsx`、`.mts`、`.cts`、`.vue`、`.astro`、`.mdx`。
75
+ *
76
+ * @param stagedFiles 暂存区文件路径列表
77
+ * @param options 运行参数
78
+ */
79
+ function verifyStagedTypecheck(stagedFiles, options = {}) {
80
+ const cwd = options.cwd ?? process.cwd();
81
+ const spawn = options.spawn ?? spawnSync;
82
+ let workspaceDirs = [...new Set(stagedFiles.filter((file) => {
83
+ const basename = path.basename(file);
84
+ return typecheckExtensions.has(path.extname(file)) || typecheckBasenames.has(basename);
85
+ }).map((file) => resolveTypecheckWorkspaceDir(file, cwd)))];
86
+ if (workspaceDirs.length === 0) return;
87
+ if (workspaceDirs.includes(cwd)) workspaceDirs = [cwd];
88
+ for (const workspaceDir of workspaceDirs) runPnpmCommand(cwd, `[lint-staged:typecheck] ${path.relative(cwd, workspaceDir) || "."}`, [
89
+ "--dir",
90
+ workspaceDir,
91
+ "typecheck"
92
+ ], spawn);
93
+ }
94
+ //#endregion
95
+ //#region src/commands/verify/index.ts
96
+ function runShellCommand(cwd, label, command, spawn) {
97
+ process.stdout.write(`${label}\n`);
98
+ const result = spawn("sh", ["-lc", command], {
99
+ cwd,
100
+ stdio: "inherit"
101
+ });
102
+ if (result.status !== 0) process.exit(result.status ?? 1);
103
+ }
104
+ /**
105
+ * 执行 commit-msg 校验。
106
+ *
107
+ * 优先读取 `tooling.husky.commitMsgCommand`;若未配置,则回退到
108
+ * `pnpm exec commitlint --edit <editFile>`。
109
+ *
110
+ * @param options commit-msg 运行参数
111
+ */
112
+ async function verifyCommitMsg(options) {
113
+ const cwd = options.cwd ?? process.cwd();
114
+ const spawn = options.spawn ?? spawnSync;
115
+ const command = (await resolveToolingConfig(cwd)).husky?.commitMsgCommand?.replaceAll("{editFile}", options.editFile);
116
+ if (command) {
117
+ runShellCommand(cwd, `[commit-msg] ${options.editFile}`, command, spawn);
118
+ return;
119
+ }
120
+ runPnpmCommand(cwd, `[commit-msg] ${options.editFile}`, [
121
+ "exec",
122
+ "commitlint",
123
+ "--edit",
124
+ options.editFile
125
+ ], spawn);
126
+ }
127
+ /**
128
+ * 执行 pre-commit 校验。
129
+ *
130
+ * 优先读取 `tooling.husky.preCommitCommand`;若未配置,则回退到
131
+ * `pnpm exec lint-staged`。
132
+ *
133
+ * @param options pre-commit 运行参数
134
+ */
135
+ async function verifyPreCommit(options = {}) {
136
+ const cwd = options.cwd ?? process.cwd();
137
+ const spawn = options.spawn ?? spawnSync;
138
+ const command = (await resolveToolingConfig(cwd)).husky?.preCommitCommand;
139
+ if (command) {
140
+ runShellCommand(cwd, "[pre-commit] lint-staged", command, spawn);
141
+ return;
142
+ }
143
+ runPnpmCommand(cwd, "[pre-commit] lint-staged", ["exec", "lint-staged"], spawn);
144
+ }
145
+ //#endregion
146
+ //#region src/commands/check.ts
147
+ function resolveRecommendedCheckPlan(options) {
148
+ const { cwd, full, staged, editFile } = options;
149
+ if (editFile) return {
150
+ cwd,
151
+ mode: "commit-msg",
152
+ commands: [{
153
+ name: "commit-msg",
154
+ command: `repo verify commit-msg ${editFile}`,
155
+ description: localize("Validate a commit message file.", "校验 commit message 文件是否符合提交规范。")
156
+ }]
157
+ };
158
+ if (full) return {
159
+ cwd,
160
+ mode: "full",
161
+ commands: [{
162
+ name: "pre-push",
163
+ command: "repo verify pre-push",
164
+ description: localize("Run full pre-push verification with lint, typecheck, build, test, and tsd.", "执行完整 pre-push 校验,包含整仓 lint/typecheck,并按变更范围运行 build/test/tsd。")
165
+ }]
166
+ };
167
+ if (staged) return {
168
+ cwd,
169
+ mode: "staged",
170
+ commands: [{
171
+ name: "pre-commit",
172
+ command: "repo verify pre-commit",
173
+ description: localize("Run pre-commit verification.", "执行 pre-commit 校验。")
174
+ }, {
175
+ name: "staged-typecheck",
176
+ command: "repo verify staged-typecheck <staged files>",
177
+ description: localize("Route typecheck to workspaces containing staged TypeScript or Vue files.", "按暂存 TypeScript/Vue 文件所在 workspace 路由 typecheck。")
178
+ }]
179
+ };
180
+ return {
181
+ cwd,
182
+ mode: "default",
183
+ commands: [{
184
+ name: "pre-commit",
185
+ command: "repo verify pre-commit",
186
+ description: localize("Run the default lightweight local verification.", "执行默认轻量本地校验。")
187
+ }]
188
+ };
189
+ }
190
+ function getKnownRepoCheckCommands() {
191
+ return /* @__PURE__ */ new Set([
192
+ "repo verify pre-commit",
193
+ "repo verify pre-push",
194
+ "repo verify staged-typecheck",
195
+ "repo verify commit-msg"
196
+ ]);
197
+ }
198
+ function hasRootScript(pkgJson, name) {
199
+ return typeof pkgJson.scripts?.[name] === "string" && pkgJson.scripts[name].length > 0;
200
+ }
201
+ async function readRootScripts(cwd) {
202
+ const pkgJsonPath = `${cwd}/package.json`;
203
+ if (!await fs$1.pathExists(pkgJsonPath)) return {};
204
+ return (await fs$1.readJson(pkgJsonPath)).scripts ?? {};
205
+ }
206
+ async function resolveFullWorkspaceCheckPlan(cwd) {
207
+ const scripts = await readRootScripts(cwd);
208
+ return {
209
+ cwd,
210
+ mode: "full",
211
+ commands: [
212
+ "lint",
213
+ "typecheck",
214
+ "test",
215
+ "build"
216
+ ].filter((name) => hasRootScript({ scripts }, name)).map((name) => ({
217
+ name,
218
+ command: `pnpm ${name}`,
219
+ description: localize(`Run the ${name} script from the root package.json.`, `运行根 package.json 的 ${name} 脚本。`),
220
+ available: true
221
+ }))
222
+ };
223
+ }
224
+ async function runFullWorkspaceCheck(cwd, spawn = spawnSync) {
225
+ await loadMonorepoConfig(cwd);
226
+ const plan = await resolveFullWorkspaceCheckPlan(cwd);
227
+ for (const command of plan.commands) {
228
+ process.stdout.write(`[check:${command.name}] .\n`);
229
+ const result = spawn("pnpm", [command.name], {
230
+ cwd,
231
+ stdio: "inherit"
232
+ });
233
+ if (result.status !== 0) process.exit(result.status ?? 1);
234
+ }
235
+ }
236
+ async function runRecommendedCheck(options) {
237
+ const { cwd, full, staged, editFile, spawn } = options;
238
+ if (editFile) {
239
+ await verifyCommitMsg({
240
+ cwd,
241
+ editFile
242
+ });
243
+ return;
244
+ }
245
+ if (full) {
246
+ await runFullWorkspaceCheck(cwd, spawn);
247
+ return;
248
+ }
249
+ if (staged) {
250
+ await verifyPreCommit({ cwd });
251
+ verifyStagedTypecheck([], { cwd });
252
+ return;
253
+ }
254
+ await verifyPreCommit({ cwd });
255
+ }
256
+ //#endregion
257
+ //#region src/commands/check/affected/selection.ts
258
+ function selectAffectedPackages(graph, files, full, filters) {
259
+ const packages = graph.nodes.map((node) => ({
260
+ id: node.id,
261
+ ...node.name ? { name: node.name } : {},
262
+ selected: false,
263
+ reasons: []
264
+ }));
265
+ const byId = new Map(packages.map((pkg) => [pkg.id, pkg]));
266
+ for (const pkg of packages) {
267
+ const direct = files.filter((file) => file.owner === pkg.id).map((file) => file.path);
268
+ if (direct.length) {
269
+ pkg.reasons.push({
270
+ code: "direct_change",
271
+ files: direct
272
+ });
273
+ for (const consumer of getWorkspaceImpact(graph, `./${pkg.id}`).consumers) byId.get(consumer.id).reasons.push({
274
+ code: "dependent",
275
+ path: consumer.path
276
+ });
277
+ }
278
+ if (full) pkg.reasons.push({ code: "full_fallback" });
279
+ }
280
+ const allowed = filters?.length ? new Set(filters.map((filter) => resolveWorkspaceGraphNode(graph, filter).id)) : void 0;
281
+ for (const pkg of packages) {
282
+ pkg.selected = pkg.reasons.length > 0 && (!allowed || allowed.has(pkg.id));
283
+ if (!pkg.selected) pkg.skippedReason = pkg.reasons.length ? "filtered_out" : "not_affected";
284
+ }
285
+ return packages;
286
+ }
287
+ function includeBuildPrerequisites(graph, selected) {
288
+ const included = new Set(selected);
289
+ const outgoing = /* @__PURE__ */ new Map();
290
+ for (const edge of graph.edges) outgoing.set(edge.source, [...outgoing.get(edge.source) ?? [], edge.target]);
291
+ const queue = [...selected];
292
+ for (let index = 0; index < queue.length; index++) for (const target of outgoing.get(queue[index]) ?? []) if (!included.has(target)) {
293
+ included.add(target);
294
+ queue.push(target);
295
+ }
296
+ return [...included].sort();
297
+ }
298
+ //#endregion
299
+ //#region src/commands/check/affected/commands.ts
300
+ const stages = [
301
+ "build",
302
+ "lint",
303
+ "typecheck",
304
+ "tsd",
305
+ "test"
306
+ ];
307
+ const globCharacters = /[*?[\]{}!()+@]/g;
308
+ function readScripts(cwd, directory = ".") {
309
+ const filename = path.join(cwd, directory, "package.json");
310
+ if (directory === "." && !existsSync(filename)) return /* @__PURE__ */ new Set();
311
+ const data = JSON.parse(readFileSync(filename, "utf8"));
312
+ return new Set(Object.entries(data.scripts ?? {}).filter(([, value]) => typeof value === "string" && value.trim()).map(([name]) => name));
313
+ }
314
+ function printCommand(args) {
315
+ return ["pnpm", ...args].map((arg) => /^[\w@./:=+-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`).join(" ");
316
+ }
317
+ /** Snapshot script capabilities once so matrix jobs share the original plan's inputs. */
318
+ function createAffectedCommandPlanner(graph) {
319
+ const scripts = new Map(graph.nodes.map((node) => [node.id, readScripts(graph.workspaceDir, node.id)]));
320
+ const rootScripts = readScripts(graph.workspaceDir);
321
+ return (packages, full, filtered) => {
322
+ const selected = packages.filter((pkg) => pkg.selected).map((pkg) => pkg.id);
323
+ const buildTargets = includeBuildPrerequisites(graph, selected);
324
+ return stages.map((name) => {
325
+ const root = full && !filtered && rootScripts.has(name);
326
+ const candidates = name === "build" ? buildTargets : selected;
327
+ const targets = root ? ["."] : candidates.filter((id) => scripts.get(id)?.has(name));
328
+ const missingTargets = root ? [] : candidates.filter((id) => !scripts.get(id)?.has(name));
329
+ const args = !targets.length ? [] : root ? [name] : [
330
+ "--recursive",
331
+ ...targets.map((id) => `--filter=./${id.replace(globCharacters, (value) => `[${value}]`).replace(/\.$/, "[.]")}`),
332
+ "--fail-if-no-match",
333
+ "--if-present",
334
+ "run",
335
+ name
336
+ ];
337
+ const command = {
338
+ name,
339
+ command: targets.length ? printCommand(args) : "",
340
+ description: root ? localize(`Run the root ${name} script for full verification.`, `运行根 ${name} 脚本进行全量校验。`) : localize(`Run ${name} in ${targets.length} workspace packages.`, `在 ${targets.length} 个 workspace 包中运行 ${name}。`),
341
+ executable: "pnpm",
342
+ args,
343
+ scope: root ? "root" : "packages",
344
+ targets,
345
+ missingTargets,
346
+ prerequisiteTargets: root ? [] : targets.filter((id) => !selected.includes(id))
347
+ };
348
+ if (!targets.length) command.skipReason = candidates.length ? "missing_script" : packages.some((pkg) => pkg.skippedReason === "filtered_out") ? "filter_intersection_empty" : "no_affected_packages";
349
+ return command;
350
+ });
351
+ };
352
+ }
353
+ //#endregion
354
+ //#region src/commands/check/affected/git.ts
355
+ function readAffectedGitRange(cwd, base = "origin/main", head = "HEAD") {
356
+ const git = (args) => execFileSync("git", args, {
357
+ cwd,
358
+ encoding: "utf8",
359
+ stdio: [
360
+ "ignore",
361
+ "pipe",
362
+ "pipe"
363
+ ],
364
+ maxBuffer: 16777216
365
+ });
366
+ const range = {
367
+ base,
368
+ head,
369
+ baseCommit: null,
370
+ headCommit: null,
371
+ mergeBase: null,
372
+ includesWorkingTree: false
373
+ };
374
+ const fallback = [];
375
+ const changes = /* @__PURE__ */ new Map();
376
+ const add = (file, kind) => {
377
+ const kinds = changes.get(file) ?? /* @__PURE__ */ new Set();
378
+ kinds.add(kind);
379
+ changes.set(file, kinds);
380
+ };
381
+ const diff = (args) => {
382
+ const fields = git([
383
+ "diff",
384
+ "--name-status",
385
+ "--no-renames",
386
+ "-z",
387
+ "--relative",
388
+ ...args
389
+ ]).split("\0");
390
+ const kinds = {
391
+ A: "added",
392
+ D: "deleted",
393
+ M: "modified",
394
+ T: "type_changed",
395
+ U: "unmerged"
396
+ };
397
+ for (let index = 0; index < fields.length - 1; index += 2) {
398
+ const kind = kinds[fields[index]];
399
+ const filename = fields[index + 1];
400
+ if (!kind || !filename) throw new Error("Unexpected Git diff record");
401
+ add(filename, kind);
402
+ }
403
+ };
404
+ const fail = (code) => {
405
+ fallback.push({ code });
406
+ return {
407
+ git: range,
408
+ files: [],
409
+ fallback
410
+ };
411
+ };
412
+ try {
413
+ if (realpathSync(git(["rev-parse", "--show-toplevel"]).trim()) !== realpathSync(cwd)) return fail("workspace_not_git_root");
414
+ } catch {
415
+ return fail("git_unavailable");
416
+ }
417
+ try {
418
+ range.baseCommit = git([
419
+ "rev-parse",
420
+ "--verify",
421
+ "--end-of-options",
422
+ `${base}^{commit}`
423
+ ]).trim();
424
+ } catch {
425
+ return fail("base_unavailable");
426
+ }
427
+ try {
428
+ range.headCommit = git([
429
+ "rev-parse",
430
+ "--verify",
431
+ "--end-of-options",
432
+ `${head}^{commit}`
433
+ ]).trim();
434
+ if (range.headCommit !== git([
435
+ "rev-parse",
436
+ "--verify",
437
+ "HEAD"
438
+ ]).trim()) return fail("head_not_checked_out");
439
+ } catch {
440
+ return fail("head_unavailable");
441
+ }
442
+ try {
443
+ range.mergeBase = git([
444
+ "merge-base",
445
+ range.baseCommit,
446
+ range.headCommit
447
+ ]).trim();
448
+ } catch {
449
+ return fail("merge_base_unavailable");
450
+ }
451
+ try {
452
+ diff([range.mergeBase, range.headCommit]);
453
+ diff(["--cached", range.headCommit]);
454
+ diff([]);
455
+ for (const filename of git([
456
+ "ls-files",
457
+ "--others",
458
+ "--exclude-standard",
459
+ "-z"
460
+ ]).split("\0").filter(Boolean)) add(filename, "untracked");
461
+ range.includesWorkingTree = true;
462
+ } catch {
463
+ return fail("git_diff_failed");
464
+ }
465
+ const files = [...changes].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path, kinds]) => ({
466
+ path,
467
+ kinds: [...kinds].sort()
468
+ }));
469
+ if (files.some((file) => file.kinds.includes("unmerged"))) fallback.push({ code: "unmerged_changes" });
470
+ return {
471
+ git: range,
472
+ files,
473
+ fallback
474
+ };
475
+ }
476
+ //#endregion
477
+ //#region src/commands/check/affected/inputs.ts
478
+ const defaultAffectedGlobalInputs = [
479
+ "package.json",
480
+ "pnpm-workspace.yaml",
481
+ "pnpm-lock.yaml",
482
+ "turbo.json",
483
+ "turbo.jsonc",
484
+ "tsconfig*.json",
485
+ "eslint.config.*",
486
+ ".eslintrc*",
487
+ "stylelint.config.*",
488
+ ".stylelintrc*",
489
+ "vitest.config.*",
490
+ "lint-staged.config.*",
491
+ "commitlint.config.*",
492
+ ".npmrc",
493
+ ".pnpmfile.*",
494
+ ".node-version",
495
+ ".nvmrc",
496
+ ".github/**",
497
+ ".husky/**",
498
+ "scripts/**",
499
+ "patches/**"
500
+ ];
501
+ function readAffectedGlobalInputs(cwd, extra = []) {
502
+ const patterns = /* @__PURE__ */ new Set([...defaultAffectedGlobalInputs, ...extra]);
503
+ const fallback = [];
504
+ const config = ["turbo.json", "turbo.jsonc"].map((file) => path.join(cwd, file)).find((file) => existsSync(file));
505
+ if (config) try {
506
+ const data = parse(readFileSync(config, "utf8"));
507
+ if (data.globalDependencies !== void 0) {
508
+ if (!Array.isArray(data.globalDependencies) || !data.globalDependencies.every((value) => typeof value === "string")) throw new Error("Invalid globalDependencies");
509
+ for (const pattern of data.globalDependencies) patterns.add(pattern);
510
+ }
511
+ } catch {
512
+ fallback.push({ code: "global_inputs_unavailable" });
513
+ }
514
+ return {
515
+ patterns: [...patterns].sort(),
516
+ fallback
517
+ };
518
+ }
519
+ function classifyAffectedFiles(files, ids, globalInputs) {
520
+ const owners = [...ids].sort((a, b) => b.length - a.length);
521
+ const fallback = [];
522
+ const triggers = /* @__PURE__ */ new Map();
523
+ const trigger = (code, file) => triggers.set(code, [...triggers.get(code) ?? [], file]);
524
+ for (const file of files) {
525
+ const owner = owners.find((id) => file.path.startsWith(`${id}/`));
526
+ if (owner) file.owner = owner;
527
+ if (globalInputs.some((pattern) => path.matchesGlob(file.path, pattern))) {
528
+ file.reason = "global_input";
529
+ trigger("global_input", file.path);
530
+ } else if (path.basename(file.path) === "package.json") {
531
+ file.reason = "workspace_manifest";
532
+ trigger("workspace_manifest_changed", file.path);
533
+ } else if (!owner) {
534
+ const documentation = file.path.startsWith("docs/") || !file.path.includes("/") && /\.(?:md|mdx)$/i.test(file.path) || /^(?:LICENSE|LICENCE|NOTICE)(?:\.|$)/i.test(file.path);
535
+ file.reason = documentation ? "documentation" : "unowned";
536
+ if (!documentation) trigger("unowned_change", file.path);
537
+ }
538
+ }
539
+ for (const [code, files] of triggers) fallback.push({
540
+ code,
541
+ files
542
+ });
543
+ return fallback;
544
+ }
545
+ //#endregion
546
+ //#region src/commands/check/affected/index.ts
547
+ /** Internal shared snapshot used by local checks and matrix generation. */
548
+ async function resolveAffectedCheckContext(options) {
549
+ const graph = await getWorkspaceGraph(options.cwd);
550
+ if (!existsSync(path.join(graph.workspaceDir, "pnpm-workspace.yaml"))) throw new Error("Affected checks require a discoverable pnpm-workspace.yaml");
551
+ const changes = readAffectedGitRange(graph.workspaceDir, options.base, options.head);
552
+ const inputs = readAffectedGlobalInputs(graph.workspaceDir, options.globalInputs);
553
+ const fallback = [...changes.fallback, ...classifyAffectedFiles(changes.files, graph.nodes.map((node) => node.id), inputs.patterns)];
554
+ if (changes.files.some((file) => file.reason !== "documentation") || fallback.length) {
555
+ fallback.push(...inputs.fallback);
556
+ if (graph.diagnostics.length) fallback.push({
557
+ code: "graph_diagnostics",
558
+ diagnostics: graph.diagnostics
559
+ });
560
+ }
561
+ const full = fallback.length > 0;
562
+ const packages = selectAffectedPackages(graph, changes.files, full, options.filters);
563
+ const createCommands = createAffectedCommandPlanner(graph);
564
+ return {
565
+ plan: {
566
+ schemaVersion: 1,
567
+ mode: "affected",
568
+ cwd: graph.workspaceDir,
569
+ git: changes.git,
570
+ strategy: full ? "full" : "affected",
571
+ fallback,
572
+ globalInputs: inputs.patterns,
573
+ files: changes.files,
574
+ packages,
575
+ commands: createCommands(packages, full, !!options.filters?.length)
576
+ },
577
+ createCommands
578
+ };
579
+ }
580
+ /** Resolve one explainable plan; Git uncertainty expands checks rather than yielding an empty selection. */
581
+ async function resolveAffectedCheckPlan(options) {
582
+ return (await resolveAffectedCheckContext(options)).plan;
583
+ }
584
+ //#endregion
585
+ //#region src/commands/check/execute.ts
586
+ /** Run checks without exiting the caller, retaining every completed and skipped stage. */
587
+ async function runCheckWithReport(options) {
588
+ const start = performance.now();
589
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
590
+ if (options.affected && (options.full || options.staged || options.editFile)) throw new Error("Affected mode cannot be combined with full, staged or editFile");
591
+ if (!options.affected && (options.base || options.head || options.filters || options.globalInputs)) throw new Error("base, head, filters and globalInputs require affected mode");
592
+ const affectedPlan = options.affected ? await resolveAffectedCheckPlan(options) : void 0;
593
+ const plan = affectedPlan ?? (options.full && !options.editFile ? await resolveFullWorkspaceCheckPlan(options.cwd) : resolveRecommendedCheckPlan(options));
594
+ const tasks = plan.commands.map((command, index) => ({
595
+ name: command.name,
596
+ command: command.command,
597
+ executable: affectedPlan?.commands[index]?.executable ?? (plan.mode === "full" ? "pnpm" : process.execPath),
598
+ args: affectedPlan?.commands[index]?.args ?? (plan.mode === "full" ? [command.name] : [
599
+ fileURLToPath(import.meta.resolve("@icebreakers/monorepo/cli")),
600
+ "verify",
601
+ command.name,
602
+ ...options.editFile ? [options.editFile] : []
603
+ ]),
604
+ cwd: plan.cwd,
605
+ status: "skipped",
606
+ startedAt: null,
607
+ endedAt: null,
608
+ durationMs: 0,
609
+ exitCode: null,
610
+ signal: null,
611
+ reason: affectedPlan?.commands[index]?.skipReason ?? "not_run"
612
+ }));
613
+ if (affectedPlan) {
614
+ process.stdout.write(`[affected:${affectedPlan.strategy}] ${affectedPlan.packages.filter((pkg) => pkg.selected).map((pkg) => pkg.id).join(", ") || "(none)"}\n`);
615
+ for (const reason of affectedPlan.fallback) process.stdout.write(`[affected:fallback] ${reason.code}\n`);
616
+ }
617
+ let status = "success";
618
+ let exitCode = 0;
619
+ for (const task of tasks) {
620
+ if (task.reason !== "not_run") {
621
+ process.stdout.write(`[check:${task.name}] skipped: ${task.reason}\n`);
622
+ continue;
623
+ }
624
+ if (options.signal?.aborted) {
625
+ status = "interrupted";
626
+ exitCode = signalExitCode(options.signal.reason === "SIGTERM" ? "SIGTERM" : "SIGINT");
627
+ task.reason = "interrupted_before_start";
628
+ continue;
629
+ }
630
+ if (status !== "success") {
631
+ task.reason = "previous_task_failed";
632
+ continue;
633
+ }
634
+ if (task.name === "staged-typecheck") {
635
+ task.reason = "no_explicit_staged_files";
636
+ continue;
637
+ }
638
+ delete task.reason;
639
+ await executeCheckTask(task, options.signal);
640
+ if (task.status !== "success") {
641
+ status = task.status === "interrupted" ? "interrupted" : "failed";
642
+ exitCode = task.signal ? signalExitCode(task.signal) : task.exitCode ?? 1;
643
+ }
644
+ }
645
+ if (options.signal?.aborted && status === "success") {
646
+ status = "interrupted";
647
+ exitCode = signalExitCode(options.signal.reason === "SIGTERM" ? "SIGTERM" : "SIGINT");
648
+ }
649
+ return {
650
+ schemaVersion: 1,
651
+ cwd: plan.cwd,
652
+ mode: plan.mode,
653
+ status,
654
+ startedAt,
655
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
656
+ durationMs: Math.max(0, performance.now() - start),
657
+ exitCode,
658
+ tasks,
659
+ ...affectedPlan ? { affectedPlan } : {}
660
+ };
661
+ }
662
+ //#endregion
663
+ export { resolveFullWorkspaceCheckPlan as a, verifyCommitMsg as c, runPnpmCommand as d, logger as f, getKnownRepoCheckCommands as i, verifyPreCommit as l, resolveAffectedCheckContext as n, resolveRecommendedCheckPlan as o, resolveAffectedCheckPlan as r, runRecommendedCheck as s, runCheckWithReport as t, verifyStagedTypecheck as u };
@@ -0,0 +1,28 @@
1
+ import { St as localize } from "./workspace-tasks-CnB8kkS0.mjs";
2
+ //#region src/commands/check/cache/format.ts
3
+ function label(value, markdown) {
4
+ return markdown ? value.replace(/[\\`*_{}[\]()#+.!|<>~-]/gu, "\\$&") : value;
5
+ }
6
+ function formatTurboAnalysis(report, markdown = false) {
7
+ const { totals, criticalPath } = report;
8
+ const display = (value) => label(value, markdown);
9
+ const rate = totals.hitRate === null ? "unknown" : `${(totals.hitRate * 100).toFixed(1)}%`;
10
+ return [
11
+ ...markdown ? [localize("# Turbo cache analysis", "# Turbo 缓存分析"), ""] : [],
12
+ localize(`Cache: ${totals.hits} hit, ${totals.misses} miss, ${totals.unknownCache} unknown; hit rate ${rate} among known results.`, `缓存:${totals.hits} 命中,${totals.misses} 未命中,${totals.unknownCache} 未知;已知结果命中率 ${rate}。`),
13
+ "",
14
+ localize("Slowest recorded tasks:", "耗时最长的已记录任务:"),
15
+ ...report.slowest.map((task) => `- ${display(task.taskId)}: ${task.durationMs} ms`),
16
+ "",
17
+ criticalPath.available ? localize(`Longest measured dependency chain: ${criticalPath.taskIds.map(display).join(" → ")}; ${criticalPath.durationMs} ms of task time. Recorded span: ${criticalPath.observedSpanMs} ms.`, `最长实测依赖链:${criticalPath.taskIds.map(display).join(" → ")};任务总耗时 ${criticalPath.durationMs} ms,记录跨度 ${criticalPath.observedSpanMs} ms。`) : localize(`Dependency critical path unavailable: ${criticalPath.reason}.`, `无法计算依赖关键路径:${criticalPath.reason}。`),
18
+ localize("Task time excludes scheduling gaps, setup and contention; it is not a wall-clock optimization estimate.", "任务耗时不包含调度间隔、准备和资源竞争,不代表可节省的实际运行时间。"),
19
+ "",
20
+ ...report.globalEvidence.map((item) => `- ${item.category}: ${display(item.field)} (${item.change})`),
21
+ ...report.tasks.flatMap((task) => [`- ${display(task.taskId)}: cache ${task.cache}; comparison ${task.comparison}${task.durationDeltaMs === null ? "" : `; Δ ${task.durationDeltaMs} ms`}`, ...task.evidence.map((item) => ` ${item.category}: ${display(item.field)} (${item.change})`)]),
22
+ "",
23
+ localize("Differences are recorded evidence; a summary cannot prove a unique cause of a cache miss.", "差异来自摘要记录,不能据此断定缓存未命中的唯一原因。"),
24
+ ...report.limitations.map((item) => `! ${item.code}: ${item.summary}${item.taskId ? ` / ${display(item.taskId)}` : ""}${item.field ? ` / ${display(item.field)}` : ""}`)
25
+ ].join("\n");
26
+ }
27
+ //#endregion
28
+ export { formatTurboAnalysis };