@icebreakers/monorepo 5.6.0 → 5.7.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.
- package/README.md +2 -0
- package/dist/baseline-CRCTiMNM.mjs +146 -0
- package/dist/bundle-B9vRch4R.mjs +49 -0
- package/dist/catalog-D0Sk385O.mjs +299 -0
- package/dist/cli.mjs +1487 -156
- package/dist/commands-Bj0sX3R9.mjs +13849 -0
- package/dist/config-Dg-voj8q.mjs +66 -0
- package/dist/{create-flow-CXRhfGbb.mjs → create-flow-BWFWDWR4.mjs} +90 -24
- package/dist/deps-BbykICqB.mjs +47 -0
- package/dist/execute-D2GlX018.mjs +68 -0
- package/dist/execute-DI1mgVLv.mjs +663 -0
- package/dist/format-Dbs0fupU.mjs +28 -0
- package/dist/index-CoCTFWZJ.d.mts +2150 -0
- package/dist/index.d.mts +1738 -112
- package/dist/index.mjs +60 -7
- package/dist/inputs-BKtLcrQ9.mjs +50 -0
- package/dist/npm-Bh6HBy5V.mjs +82 -0
- package/dist/plan-CxySMaLN.mjs +75 -0
- package/dist/run-D_bceMqf.mjs +165 -0
- package/dist/save-DzIWKs0T.mjs +79 -0
- package/dist/scan-B_-E6BWh.mjs +293 -0
- package/dist/template-drift-D0hKxixr.mjs +2740 -0
- package/dist/tooling-entry.d.mts +1 -1
- package/dist/tooling-entry.mjs +2 -2
- package/dist/transaction-DFam8_dp.mjs +168 -0
- package/dist/tsconfig-BZ6E1fBA.mjs +1483 -0
- package/dist/{vitest-Blzbh8xZ.mjs → vitest-XbNmiloj.mjs} +1 -1
- package/dist/workspace-tasks-C5W-QwWj.mjs +4435 -0
- package/package.json +22 -4
- package/resources/api-report/runner.cjs +76 -0
- package/resources/devcontainer/setup.mjs +36 -0
- package/resources/knip/reporter.mjs +46 -0
- package/resources/maintenance/migration-lanes.mjs +141 -0
- package/resources/maintenance/migration-lock.mjs +119 -0
- package/resources/maintenance/migrations.mjs +215 -0
- package/resources/maintenance/presets.mjs +130 -0
- package/resources/maintenance/validate.mjs +233 -0
- package/resources/maintenance/workflow.yml +151 -0
- package/resources/skills/repoctl/SKILL.md +2 -0
- package/resources/skills/repoctl/references/commands.md +224 -13
- package/resources/skills/repoctl/references/config.md +70 -6
- package/resources/skills/repoctl/references/dependencies.md +37 -0
- package/resources/skills/repoctl/references/knip.md +34 -0
- package/resources/skills/repoctl/references/templates.md +23 -0
- package/dist/commands-D4xZQ5t-.mjs +0 -5685
- package/dist/config-p842Knhq.mjs +0 -114
- package/dist/index-Bl_PB2Ch.d.mts +0 -1039
- package/dist/tsconfig-BrjI_5yI.mjs +0 -75
- package/dist/types-MAUIQpfp.mjs +0 -499
- package/dist/workspace-MCKewElu.mjs +0 -123
|
@@ -0,0 +1,4435 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
|
|
2
|
+
import { f as loadMonorepoConfigDetails, j as ConfigValidationError, k as version, u as getRepoctlConfigCandidates } from "./tsconfig-BZ6E1fBA.mjs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import gitUrlParse from "git-url-parse";
|
|
5
|
+
import { simpleGit } from "simple-git";
|
|
6
|
+
import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
|
|
7
|
+
import { findWorkspacePackages } from "@pnpm/workspace.find-packages";
|
|
8
|
+
import { readWorkspaceManifest } from "@pnpm/workspace.read-manifest";
|
|
9
|
+
import path from "pathe";
|
|
10
|
+
import process from "node:process";
|
|
11
|
+
import fs, { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, unlink, utimes, writeFile } from "node:fs/promises";
|
|
12
|
+
import { spawnSync } from "node:child_process";
|
|
13
|
+
import { constants, realpathSync } from "node:fs";
|
|
14
|
+
import semver from "semver";
|
|
15
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
16
|
+
import * as path$2 from "node:path";
|
|
17
|
+
import path$1 from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import crossSpawn from "cross-spawn";
|
|
20
|
+
import { canVerifyTemplateInstance, captureTemplateSnapshot, compareTemplateSnapshots, generationParameters, getTemplateDefinition, instanceRelativePath, isExactTemplateVersion, listTemplateInstances, loadTemplateBaseline, loadTemplateBaseline as loadTemplateBaseline$1, loadTemplateInstanceRegistry, loadTemplateInstanceRegistry as loadTemplateInstanceRegistry$1, normalizeTemplateExclusions, packageDir, prepareTemplateInstanceSource, readTemplatePackageVersion, readTemplateParameterManifest, rebuildTemplateInstanceBaseline, registerTemplateInstances, relocateTemplateInstance, renderTemplateParameters, replaceTemplateInstance, resolveTemplateParameters, safeInstancePath, scaffoldTemplate, snapshotDigest, templateInstanceId } from "@icebreakers/monorepo-templates";
|
|
21
|
+
import { Buffer } from "node:buffer";
|
|
22
|
+
import { constants as constants$1, tmpdir } from "node:os";
|
|
23
|
+
import { TextDecoder as TextDecoder$1 } from "node:util";
|
|
24
|
+
import { glob } from "tinyglobby";
|
|
25
|
+
import { diff3Merge } from "node-diff3";
|
|
26
|
+
import { parse as parse$1 } from "comment-json";
|
|
27
|
+
import { performance } from "node:perf_hooks";
|
|
28
|
+
import micromatch from "micromatch";
|
|
29
|
+
import { parse as parse$2 } from "@babel/parser";
|
|
30
|
+
//#region src/core/git.ts
|
|
31
|
+
/**
|
|
32
|
+
* 对 simple-git 的轻量封装,集中处理配置缓存与常用查询。
|
|
33
|
+
*/
|
|
34
|
+
var GitClient = class {
|
|
35
|
+
client;
|
|
36
|
+
#config;
|
|
37
|
+
constructor(options = {}) {
|
|
38
|
+
this.client = simpleGit(options);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* 读取 Git 的 config 列表,原样返回 simple-git 的结果。
|
|
42
|
+
*/
|
|
43
|
+
listConfig() {
|
|
44
|
+
return this.client.listConfig();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* 初始化配置缓存,避免多次访问 Git 产生的性能损耗。
|
|
48
|
+
*/
|
|
49
|
+
async init() {
|
|
50
|
+
const listConfig = await this.listConfig();
|
|
51
|
+
this.#config = listConfig.all;
|
|
52
|
+
return this.#config;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 获取缓存的配置,若未初始化则自动触发 init。
|
|
56
|
+
*/
|
|
57
|
+
async getConfig() {
|
|
58
|
+
if (this.#config) return this.#config;
|
|
59
|
+
else return await this.init();
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 解析 remote.origin.url,返回 git-url-parse 的结构,便于获取仓库元信息。
|
|
63
|
+
*/
|
|
64
|
+
async getGitUrl() {
|
|
65
|
+
const x = (await this.getConfig())["remote.origin.url"];
|
|
66
|
+
if (typeof x === "string") return gitUrlParse(x);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* 组合 owner/name,生成常用的仓库名表达。
|
|
70
|
+
*/
|
|
71
|
+
async getRepoName() {
|
|
72
|
+
const url = await this.getGitUrl();
|
|
73
|
+
if (url) return `${url.owner}/${url.name}`;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* 从 Git 配置中提取用户信息,用于填充 package.json author 字段。
|
|
77
|
+
*/
|
|
78
|
+
async getUser() {
|
|
79
|
+
const config = await this.getConfig();
|
|
80
|
+
return {
|
|
81
|
+
name: config["user.name"],
|
|
82
|
+
email: config["user.email"]
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* 获取当前仓库的顶层目录路径。
|
|
87
|
+
*/
|
|
88
|
+
async getRepoRoot() {
|
|
89
|
+
try {
|
|
90
|
+
const root = await this.client.revparse(["--show-toplevel"]);
|
|
91
|
+
return typeof root === "string" ? root.trim() : void 0;
|
|
92
|
+
} catch {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/core/workspace.ts
|
|
99
|
+
var workspace_exports = /* @__PURE__ */ __exportAll({
|
|
100
|
+
clearWorkspaceCache: () => clearWorkspaceCache,
|
|
101
|
+
getWorkspaceData: () => getWorkspaceData,
|
|
102
|
+
getWorkspacePackageSummaries: () => getWorkspacePackageSummaries,
|
|
103
|
+
getWorkspacePackages: () => getWorkspacePackages
|
|
104
|
+
});
|
|
105
|
+
const workspaceDirCache = /* @__PURE__ */ new Map();
|
|
106
|
+
const workspaceManifestCache = /* @__PURE__ */ new Map();
|
|
107
|
+
const workspacePackagesCache = /* @__PURE__ */ new Map();
|
|
108
|
+
function normalizeDir(dir) {
|
|
109
|
+
return path.resolve(dir);
|
|
110
|
+
}
|
|
111
|
+
function getPatternsCacheKey(patterns) {
|
|
112
|
+
return patterns === void 0 ? "<manifest>" : JSON.stringify(patterns);
|
|
113
|
+
}
|
|
114
|
+
function comparePackagePath(left, right) {
|
|
115
|
+
return left.relativeDir.localeCompare(right.relativeDir);
|
|
116
|
+
}
|
|
117
|
+
function getPackageRootDir(project) {
|
|
118
|
+
return normalizeDir(project.rootDirRealPath || project.rootDir);
|
|
119
|
+
}
|
|
120
|
+
async function findWorkspaceDirCached(cwd) {
|
|
121
|
+
const key = normalizeDir(cwd);
|
|
122
|
+
if (!workspaceDirCache.has(key)) workspaceDirCache.set(key, findWorkspaceDir(key));
|
|
123
|
+
return workspaceDirCache.get(key);
|
|
124
|
+
}
|
|
125
|
+
async function readWorkspaceManifestCached(workspaceDir) {
|
|
126
|
+
const key = normalizeDir(workspaceDir);
|
|
127
|
+
if (!workspaceManifestCache.has(key)) workspaceManifestCache.set(key, readWorkspaceManifest(key));
|
|
128
|
+
return workspaceManifestCache.get(key);
|
|
129
|
+
}
|
|
130
|
+
async function findWorkspacePackagesCached(workspaceDir, patterns) {
|
|
131
|
+
const normalizedWorkspaceDir = normalizeDir(workspaceDir);
|
|
132
|
+
const key = `${normalizedWorkspaceDir}:${getPatternsCacheKey(patterns)}`;
|
|
133
|
+
if (!workspacePackagesCache.has(key)) workspacePackagesCache.set(key, findWorkspacePackages(normalizedWorkspaceDir, patterns ? { patterns } : {}));
|
|
134
|
+
return workspacePackagesCache.get(key);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* 清空当前进程内的 workspace 发现缓存。
|
|
138
|
+
*
|
|
139
|
+
* 普通 CLI 命令执行后进程会退出;长期运行的集成测试或程序化调用在修改
|
|
140
|
+
* `pnpm-workspace.yaml` / package 目录后,可以调用它让后续扫描重新读磁盘。
|
|
141
|
+
*/
|
|
142
|
+
function clearWorkspaceCache() {
|
|
143
|
+
workspaceDirCache.clear();
|
|
144
|
+
workspaceManifestCache.clear();
|
|
145
|
+
workspacePackagesCache.clear();
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* 读取 pnpm workspace 下的所有包,并根据选项做过滤。
|
|
149
|
+
*
|
|
150
|
+
* 默认值:
|
|
151
|
+
* - `ignoreRootPackage`: `true`
|
|
152
|
+
* - `ignorePrivatePackage`: `true`
|
|
153
|
+
*
|
|
154
|
+
* @param workspaceDir workspace 根目录
|
|
155
|
+
* @param options 过滤选项
|
|
156
|
+
* @returns 带有 `pkgJsonPath` 字段的 workspace package 列表
|
|
157
|
+
*/
|
|
158
|
+
async function getWorkspacePackages(workspaceDir, options) {
|
|
159
|
+
const normalizedWorkspaceDir = normalizeDir(workspaceDir);
|
|
160
|
+
const ignoreRootPackage = options?.ignoreRootPackage ?? true;
|
|
161
|
+
const ignorePrivatePackage = options?.ignorePrivatePackage ?? true;
|
|
162
|
+
const manifest = options?.patterns === void 0 ? await readWorkspaceManifestCached(normalizedWorkspaceDir) : void 0;
|
|
163
|
+
let pkgs = (await findWorkspacePackagesCached(normalizedWorkspaceDir, options?.patterns ?? manifest?.packages)).filter((x) => {
|
|
164
|
+
if (ignorePrivatePackage && x.manifest.private) return false;
|
|
165
|
+
return true;
|
|
166
|
+
}).map((project) => {
|
|
167
|
+
const rootDir = getPackageRootDir(project);
|
|
168
|
+
const pkgJsonPath = path.resolve(rootDir, "package.json");
|
|
169
|
+
return {
|
|
170
|
+
...project,
|
|
171
|
+
rootDir,
|
|
172
|
+
pkgJsonPath
|
|
173
|
+
};
|
|
174
|
+
});
|
|
175
|
+
if (ignoreRootPackage) pkgs = pkgs.filter((x) => {
|
|
176
|
+
return x.rootDir !== normalizedWorkspaceDir;
|
|
177
|
+
});
|
|
178
|
+
return pkgs;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 一次性返回 `cwd`、真实 `workspaceDir` 与过滤后的包列表。
|
|
182
|
+
*
|
|
183
|
+
* @param cwd 当前工作目录
|
|
184
|
+
* @param options 传给 `getWorkspacePackages()` 的过滤选项
|
|
185
|
+
*/
|
|
186
|
+
async function getWorkspaceData(cwd, options) {
|
|
187
|
+
const normalizedCwd = normalizeDir(cwd);
|
|
188
|
+
const workspaceDir = await findWorkspaceDirCached(normalizedCwd) ?? normalizedCwd;
|
|
189
|
+
return {
|
|
190
|
+
cwd: normalizedCwd,
|
|
191
|
+
workspaceDir,
|
|
192
|
+
packages: await getWorkspacePackages(workspaceDir, options)
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* 返回适合展示和程序化消费的 workspace package 摘要。
|
|
197
|
+
*/
|
|
198
|
+
async function getWorkspacePackageSummaries(cwd, options) {
|
|
199
|
+
const { packages, workspaceDir } = await getWorkspaceData(cwd, options);
|
|
200
|
+
const summaries = packages.map((pkg) => ({
|
|
201
|
+
...pkg.manifest.name ? { name: pkg.manifest.name } : {},
|
|
202
|
+
...pkg.manifest.description ? { description: pkg.manifest.description } : {},
|
|
203
|
+
private: pkg.manifest.private === true,
|
|
204
|
+
rootDir: pkg.rootDir,
|
|
205
|
+
relativeDir: path.relative(workspaceDir, pkg.rootDir) || ".",
|
|
206
|
+
pkgJsonPath: pkg.pkgJsonPath
|
|
207
|
+
})).sort(comparePackagePath);
|
|
208
|
+
return {
|
|
209
|
+
cwd: normalizeDir(cwd),
|
|
210
|
+
workspaceDir,
|
|
211
|
+
packages: summaries
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region src/utils/fs.ts
|
|
216
|
+
function stringifyJson(data, options) {
|
|
217
|
+
const content = JSON.stringify(data, void 0, options?.spaces);
|
|
218
|
+
return options?.spaces ? `${content}\n` : content;
|
|
219
|
+
}
|
|
220
|
+
async function ensureParentDir(targetPath) {
|
|
221
|
+
await mkdir(path.dirname(targetPath), { recursive: true });
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* 判断文件或目录是否存在。
|
|
225
|
+
*
|
|
226
|
+
* @param targetPath 目标路径
|
|
227
|
+
* @returns 存在时返回 `true`
|
|
228
|
+
*/
|
|
229
|
+
async function pathExists(targetPath) {
|
|
230
|
+
try {
|
|
231
|
+
await access(targetPath);
|
|
232
|
+
return true;
|
|
233
|
+
} catch {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* `pathExists()` 的别名。
|
|
239
|
+
*/
|
|
240
|
+
const exists$1 = pathExists;
|
|
241
|
+
/**
|
|
242
|
+
* 递归创建目录。
|
|
243
|
+
*/
|
|
244
|
+
async function ensureDir(targetPath) {
|
|
245
|
+
await mkdir(targetPath, { recursive: true });
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* 确保文件存在;若父目录不存在会自动创建。
|
|
249
|
+
*/
|
|
250
|
+
async function ensureFile(targetPath) {
|
|
251
|
+
await ensureParentDir(targetPath);
|
|
252
|
+
await (await open(targetPath, "a")).close();
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* 递归删除文件或目录。
|
|
256
|
+
*
|
|
257
|
+
* 默认启用 `force: true`、`recursive: true`,并带少量重试。
|
|
258
|
+
*/
|
|
259
|
+
async function remove(targetPath) {
|
|
260
|
+
await rm(targetPath, {
|
|
261
|
+
recursive: true,
|
|
262
|
+
force: true,
|
|
263
|
+
maxRetries: 3,
|
|
264
|
+
retryDelay: 100
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* 递归复制文件或目录。
|
|
269
|
+
*/
|
|
270
|
+
async function copy(sourcePath, targetPath) {
|
|
271
|
+
await cp(sourcePath, targetPath, {
|
|
272
|
+
recursive: true,
|
|
273
|
+
force: true
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* 自动创建父目录后写入文件。
|
|
278
|
+
*/
|
|
279
|
+
async function outputFile(targetPath, data, options) {
|
|
280
|
+
await ensureParentDir(targetPath);
|
|
281
|
+
await writeFile(targetPath, data, options);
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* 读取 JSON 文件并解析。
|
|
285
|
+
*/
|
|
286
|
+
async function readJson(targetPath) {
|
|
287
|
+
return JSON.parse(await readFile(targetPath, "utf8"));
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* `readJson()` 的别名。
|
|
291
|
+
*/
|
|
292
|
+
const readJSON = readJson;
|
|
293
|
+
/**
|
|
294
|
+
* 写入 JSON 文件,不会自动创建父目录。
|
|
295
|
+
*/
|
|
296
|
+
async function writeJson(targetPath, data, options) {
|
|
297
|
+
await writeFile(targetPath, stringifyJson(data, options), "utf8");
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* `writeJson()` 的别名。
|
|
301
|
+
*/
|
|
302
|
+
const writeJSON = writeJson;
|
|
303
|
+
/**
|
|
304
|
+
* 自动创建父目录后写入 JSON 文件。
|
|
305
|
+
*/
|
|
306
|
+
async function outputJson(targetPath, data, options) {
|
|
307
|
+
await ensureParentDir(targetPath);
|
|
308
|
+
await writeJson(targetPath, data, options);
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* `outputJson()` 的别名。
|
|
312
|
+
*/
|
|
313
|
+
const outputJSON = outputJson;
|
|
314
|
+
/**
|
|
315
|
+
* 判断是否为可忽略的文件系统错误。
|
|
316
|
+
* - ENOENT: 文件已被删除
|
|
317
|
+
* - EBUSY: Windows 中资源被系统占用
|
|
318
|
+
*/
|
|
319
|
+
function isIgnorableFsError(error) {
|
|
320
|
+
if (!error) return false;
|
|
321
|
+
const code = error.code;
|
|
322
|
+
return code === "ENOENT" || code === "EBUSY" || code === "EEXIST";
|
|
323
|
+
}
|
|
324
|
+
const fs$2 = {
|
|
325
|
+
copy,
|
|
326
|
+
ensureDir,
|
|
327
|
+
ensureFile,
|
|
328
|
+
exists: exists$1,
|
|
329
|
+
mkdtemp,
|
|
330
|
+
outputFile,
|
|
331
|
+
outputJSON,
|
|
332
|
+
outputJson,
|
|
333
|
+
pathExists,
|
|
334
|
+
readFile,
|
|
335
|
+
readdir,
|
|
336
|
+
readJSON,
|
|
337
|
+
readJson,
|
|
338
|
+
remove,
|
|
339
|
+
stat,
|
|
340
|
+
writeFile,
|
|
341
|
+
writeJSON,
|
|
342
|
+
writeJson
|
|
343
|
+
};
|
|
344
|
+
//#endregion
|
|
345
|
+
//#region src/i18n/locales/en/error.ts
|
|
346
|
+
const errorMessages$1 = {
|
|
347
|
+
commanderAllowedChoices: "Allowed choices are",
|
|
348
|
+
commanderArgumentMissing: "argument missing",
|
|
349
|
+
commanderDidYouMean: "Did you mean",
|
|
350
|
+
commanderDidYouMeanOneOf: "Did you mean one of",
|
|
351
|
+
commanderErrorPrefix: "error:",
|
|
352
|
+
commanderMissingRequiredArgument: "missing required argument",
|
|
353
|
+
commanderNotSpecified: "not specified",
|
|
354
|
+
commanderRequiredOption: "required option",
|
|
355
|
+
commanderTooManyArguments: "too many arguments",
|
|
356
|
+
commanderUnknownCommand: "unknown command",
|
|
357
|
+
commanderUnknownOption: "unknown option",
|
|
358
|
+
tasksFileRequired: "A tasks file path is required when using tasks mode.",
|
|
359
|
+
unknownCreateIntent: "Unknown create intent: {intent}",
|
|
360
|
+
unknownInitTooling: "Unknown init tooling target: {targets}",
|
|
361
|
+
missingPackageJsonForTooling: "Cannot initialize tooling because package.json was not found: {path}",
|
|
362
|
+
missingDependencyVersion: "No version information was found for dependency {name}."
|
|
363
|
+
};
|
|
364
|
+
//#endregion
|
|
365
|
+
//#region src/i18n/locales/en/help.ts
|
|
366
|
+
const helpMessages$1 = {
|
|
367
|
+
argumentsTitle: "Arguments:",
|
|
368
|
+
cliDescription: "Task-first repository initialization and maintenance for pnpm and Turborepo workspaces.",
|
|
369
|
+
commandsTitle: "Commands:",
|
|
370
|
+
choicesLabel: "choices:",
|
|
371
|
+
defaultLabel: "default:",
|
|
372
|
+
envLabel: "env:",
|
|
373
|
+
globalOptionsTitle: "Global Options:",
|
|
374
|
+
helpCommand: "Display help for command",
|
|
375
|
+
helpOption: "Display help for command",
|
|
376
|
+
languageOption: "Output language: en or zh-CN",
|
|
377
|
+
optionsTitle: "Options:",
|
|
378
|
+
presetLabel: "preset:",
|
|
379
|
+
quickStart: `
|
|
380
|
+
Quick start:
|
|
381
|
+
Existing repo:
|
|
382
|
+
$ {cliName} init
|
|
383
|
+
$ {cliName} doctor
|
|
384
|
+
$ {cliName} templates
|
|
385
|
+
$ {cliName} new my-package
|
|
386
|
+
$ {cliName} check
|
|
387
|
+
|
|
388
|
+
Faster in generated repos:
|
|
389
|
+
$ pnpm run repo:init
|
|
390
|
+
$ pnpm run repo:doctor
|
|
391
|
+
$ pnpm run repo:new -- my-package
|
|
392
|
+
$ pnpm run repo:check
|
|
393
|
+
|
|
394
|
+
Keep the repo current:
|
|
395
|
+
$ {cliName} upgrade
|
|
396
|
+
`,
|
|
397
|
+
usageTitle: "Usage:",
|
|
398
|
+
versionOption: "Output the version number"
|
|
399
|
+
};
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/i18n/locales/en/prompt.ts
|
|
402
|
+
const promptMessages$1 = {
|
|
403
|
+
createIntent: "What do you want to create?",
|
|
404
|
+
createName: "Enter a name",
|
|
405
|
+
libraryTemplate: "Select a library template",
|
|
406
|
+
packageName: "Enter the package name",
|
|
407
|
+
templateType: "Select a template type",
|
|
408
|
+
upgradeFiles: "Select the files you need",
|
|
409
|
+
overwriteFiles: "Select changed managed files to overwrite",
|
|
410
|
+
skillTargets: "Select skill synchronization targets"
|
|
411
|
+
};
|
|
412
|
+
//#endregion
|
|
413
|
+
//#region src/i18n/locales/en/report.ts
|
|
414
|
+
const reportMessages$1 = {
|
|
415
|
+
wrote: "Wrote {path}",
|
|
416
|
+
dryRunOnly: "Dry run only; no files were written.",
|
|
417
|
+
nextInstallBuild: "Next: run `pnpm install` and `pnpm build`.",
|
|
418
|
+
nextInstallStart: "Next: run `pnpm install` and start the new workspace package.",
|
|
419
|
+
doctorBlocking: "Doctor found {count} blocking issue(s).",
|
|
420
|
+
doctorStrictWarnings: "Doctor found {count} warning(s) in strict mode.",
|
|
421
|
+
doctorSuggestions: "Doctor found {count} suggestion(s)."
|
|
422
|
+
};
|
|
423
|
+
//#endregion
|
|
424
|
+
//#region src/i18n/locales/en/index.ts
|
|
425
|
+
const enMessages = {
|
|
426
|
+
...helpMessages$1,
|
|
427
|
+
...promptMessages$1,
|
|
428
|
+
...reportMessages$1,
|
|
429
|
+
...errorMessages$1
|
|
430
|
+
};
|
|
431
|
+
//#endregion
|
|
432
|
+
//#region src/i18n/locales/zh-CN/error.ts
|
|
433
|
+
const errorMessages = {
|
|
434
|
+
commanderAllowedChoices: "可选值为",
|
|
435
|
+
commanderArgumentMissing: "缺少参数",
|
|
436
|
+
commanderDidYouMean: "你是否想输入",
|
|
437
|
+
commanderDidYouMeanOneOf: "你是否想输入以下之一",
|
|
438
|
+
commanderErrorPrefix: "错误:",
|
|
439
|
+
commanderMissingRequiredArgument: "缺少必填参数",
|
|
440
|
+
commanderNotSpecified: "未指定",
|
|
441
|
+
commanderRequiredOption: "必填选项",
|
|
442
|
+
commanderTooManyArguments: "参数过多",
|
|
443
|
+
commanderUnknownCommand: "未知命令",
|
|
444
|
+
commanderUnknownOption: "未知选项",
|
|
445
|
+
tasksFileRequired: "使用 tasks 模式时必须提供任务文件路径。",
|
|
446
|
+
unknownCreateIntent: "未找到创建意图:{intent}",
|
|
447
|
+
unknownInitTooling: "未知的 init tooling 目标:{targets}",
|
|
448
|
+
missingPackageJsonForTooling: "未找到 package.json,无法初始化 tooling:{path}",
|
|
449
|
+
missingDependencyVersion: "未找到依赖 {name} 的版本信息。"
|
|
450
|
+
};
|
|
451
|
+
//#endregion
|
|
452
|
+
//#region src/i18n/locales/zh-CN/help.ts
|
|
453
|
+
const helpMessages = {
|
|
454
|
+
argumentsTitle: "参数:",
|
|
455
|
+
cliDescription: "面向 pnpm 与 Turborepo 工作区的任务型仓库初始化与维护工具。",
|
|
456
|
+
commandsTitle: "命令:",
|
|
457
|
+
choicesLabel: "可选值:",
|
|
458
|
+
defaultLabel: "默认值:",
|
|
459
|
+
envLabel: "环境变量:",
|
|
460
|
+
globalOptionsTitle: "全局选项:",
|
|
461
|
+
helpCommand: "显示指定命令的帮助",
|
|
462
|
+
helpOption: "显示命令帮助",
|
|
463
|
+
languageOption: "输出语言:en 或 zh-CN",
|
|
464
|
+
optionsTitle: "选项:",
|
|
465
|
+
presetLabel: "预设值:",
|
|
466
|
+
quickStart: `
|
|
467
|
+
快速开始:
|
|
468
|
+
已有仓库:
|
|
469
|
+
$ {cliName} init
|
|
470
|
+
$ {cliName} doctor
|
|
471
|
+
$ {cliName} templates
|
|
472
|
+
$ {cliName} new my-package
|
|
473
|
+
$ {cliName} check
|
|
474
|
+
|
|
475
|
+
生成仓库中的快捷脚本:
|
|
476
|
+
$ pnpm run repo:init
|
|
477
|
+
$ pnpm run repo:doctor
|
|
478
|
+
$ pnpm run repo:new -- my-package
|
|
479
|
+
$ pnpm run repo:check
|
|
480
|
+
|
|
481
|
+
保持仓库配置最新:
|
|
482
|
+
$ {cliName} upgrade
|
|
483
|
+
`,
|
|
484
|
+
usageTitle: "用法:",
|
|
485
|
+
versionOption: "输出版本号"
|
|
486
|
+
};
|
|
487
|
+
//#endregion
|
|
488
|
+
//#region src/i18n/locales/zh-CN/prompt.ts
|
|
489
|
+
const promptMessages = {
|
|
490
|
+
createIntent: "你要创建什么?",
|
|
491
|
+
createName: "请输入名称",
|
|
492
|
+
libraryTemplate: "请选择库模板",
|
|
493
|
+
packageName: "请输入包名",
|
|
494
|
+
templateType: "请选择模板类型",
|
|
495
|
+
upgradeFiles: "选择你需要的文件",
|
|
496
|
+
overwriteFiles: "检测到受管文件内容变化,请选择要覆盖的文件",
|
|
497
|
+
skillTargets: "请选择需要同步的技能目标"
|
|
498
|
+
};
|
|
499
|
+
//#endregion
|
|
500
|
+
//#region src/i18n/locales/zh-CN/report.ts
|
|
501
|
+
const reportMessages = {
|
|
502
|
+
wrote: "已写入 {path}",
|
|
503
|
+
dryRunOnly: "仅执行预览;未写入任何文件。",
|
|
504
|
+
nextInstallBuild: "下一步:运行 `pnpm install` 和 `pnpm build`。",
|
|
505
|
+
nextInstallStart: "下一步:运行 `pnpm install`,然后启动新 workspace 包。",
|
|
506
|
+
doctorBlocking: "Doctor 发现 {count} 个阻断问题。",
|
|
507
|
+
doctorStrictWarnings: "严格模式下 doctor 发现 {count} 个警告。",
|
|
508
|
+
doctorSuggestions: "Doctor 提供了 {count} 条建议。"
|
|
509
|
+
};
|
|
510
|
+
//#endregion
|
|
511
|
+
//#region src/i18n/locales/zh-CN/index.ts
|
|
512
|
+
const zhCNMessages = {
|
|
513
|
+
...helpMessages,
|
|
514
|
+
...promptMessages,
|
|
515
|
+
...reportMessages,
|
|
516
|
+
...errorMessages
|
|
517
|
+
};
|
|
518
|
+
//#endregion
|
|
519
|
+
//#region src/i18n/index.ts
|
|
520
|
+
const supportedLocales = ["en", "zh-CN"];
|
|
521
|
+
function isRepoctlLocale(value) {
|
|
522
|
+
return supportedLocales.includes(value);
|
|
523
|
+
}
|
|
524
|
+
function readArgvLocale(argv) {
|
|
525
|
+
const equalsArg = argv.find((arg) => arg.startsWith("--lang="));
|
|
526
|
+
if (equalsArg) return equalsArg.slice(7);
|
|
527
|
+
const index = argv.indexOf("--lang");
|
|
528
|
+
return index >= 0 ? argv[index + 1] : void 0;
|
|
529
|
+
}
|
|
530
|
+
function resolveRepoctlLocale(options = {}) {
|
|
531
|
+
const argvLocale = readArgvLocale(options.argv ?? process.argv);
|
|
532
|
+
if (isRepoctlLocale(argvLocale)) return argvLocale;
|
|
533
|
+
const envLocale = options.env?.["REPOCTL_LANG"] ?? process.env["REPOCTL_LANG"];
|
|
534
|
+
return isRepoctlLocale(envLocale) ? envLocale : "en";
|
|
535
|
+
}
|
|
536
|
+
const repoctlLocale = resolveRepoctlLocale();
|
|
537
|
+
function localize(english, simplifiedChinese) {
|
|
538
|
+
return repoctlLocale === "zh-CN" ? simplifiedChinese : english;
|
|
539
|
+
}
|
|
540
|
+
function message(key, values = {}) {
|
|
541
|
+
const catalog = repoctlLocale === "zh-CN" ? zhCNMessages : enMessages;
|
|
542
|
+
return Object.entries(values).reduce((result, [name, value]) => result.replaceAll(`{${name}}`, value), catalog[key]);
|
|
543
|
+
}
|
|
544
|
+
//#endregion
|
|
545
|
+
//#region src/constants.ts
|
|
546
|
+
const require = createRequire(import.meta.url);
|
|
547
|
+
/**
|
|
548
|
+
* 用户默认看到的 CLI 名称,帮助文案和生成脚本都统一引导到 repo。
|
|
549
|
+
*/
|
|
550
|
+
const cliName = "repo";
|
|
551
|
+
/**
|
|
552
|
+
* 还原出 package.json 所在的绝对路径,方便后续按目录组织资源文件。
|
|
553
|
+
*/
|
|
554
|
+
const packageJsonPath = fileURLToPath(new URL("../package.json", import.meta.url));
|
|
555
|
+
/**
|
|
556
|
+
* @icebreakers/monorepo 包的根目录。
|
|
557
|
+
*/
|
|
558
|
+
const packageDir$1 = path$2.dirname(packageJsonPath);
|
|
559
|
+
/**
|
|
560
|
+
* CLI 提供的模板/资产目录来源于 @icebreakers/monorepo-templates。
|
|
561
|
+
* 这里只解析 package.json 路径,避免 CLI 启动时加载模板包入口。
|
|
562
|
+
*/
|
|
563
|
+
const templatesPackageDir = path$2.dirname(require.resolve("@icebreakers/monorepo-templates/package.json"));
|
|
564
|
+
const assetsDir$1 = path$2.join(templatesPackageDir, "assets");
|
|
565
|
+
const templatesDir = path$2.join(templatesPackageDir, "templates");
|
|
566
|
+
/**
|
|
567
|
+
* monorepo 根目录,方便需要跳出当前包的逻辑(例如定位工作区文件)。
|
|
568
|
+
*/
|
|
569
|
+
const rootDir = path$2.resolve(packageDir$1, "..", "..");
|
|
570
|
+
//#endregion
|
|
571
|
+
//#region src/commands/clean/safety.ts
|
|
572
|
+
function unsafe(target) {
|
|
573
|
+
return new Error(localize(`Unsafe cleanup target: ${target}`, `清理目标不安全:${target}`));
|
|
574
|
+
}
|
|
575
|
+
function isWithin(root, target) {
|
|
576
|
+
const relative = path.relative(root, target);
|
|
577
|
+
return relative !== "" && relative !== ".." && !relative.startsWith("../") && !path.isAbsolute(relative);
|
|
578
|
+
}
|
|
579
|
+
async function assertSafePath(workspaceDir, target, kind) {
|
|
580
|
+
if (!isWithin(workspaceDir, target)) throw unsafe(target);
|
|
581
|
+
const components = path.relative(workspaceDir, target).split("/");
|
|
582
|
+
let current = workspaceDir;
|
|
583
|
+
for (const component of components) {
|
|
584
|
+
current = path.join(current, component);
|
|
585
|
+
const entry = await lstat(current);
|
|
586
|
+
if (entry.isSymbolicLink()) throw unsafe(current);
|
|
587
|
+
if (current === target ? kind === "file" ? !entry.isFile() || entry.nlink > 1 : !entry.isDirectory() : !entry.isDirectory()) throw unsafe(current);
|
|
588
|
+
}
|
|
589
|
+
if (!isWithin(workspaceDir, await realpath(target))) throw unsafe(target);
|
|
590
|
+
}
|
|
591
|
+
async function validateCleanTargets(workspace, selected) {
|
|
592
|
+
const { workspaceDir, packages } = workspace;
|
|
593
|
+
const known = new Set(packages.map((pkg) => path.resolve(pkg.rootDir)));
|
|
594
|
+
const targets = new Set(selected.map((target) => path.resolve(target)));
|
|
595
|
+
for (const target of targets) {
|
|
596
|
+
if (!known.has(target)) throw unsafe(target);
|
|
597
|
+
await assertSafePath(workspaceDir, target, "directory");
|
|
598
|
+
for (const pkg of packages) {
|
|
599
|
+
const packageDir = path.resolve(pkg.rootDir);
|
|
600
|
+
if (isWithin(target, packageDir) && !targets.has(packageDir)) throw new Error(localize(`Cleanup would remove an unselected workspace: ${packageDir}`, `清理会删除未选择的工作区:${packageDir}`));
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
//#endregion
|
|
605
|
+
//#region src/core/file-transaction/index.ts
|
|
606
|
+
/** Keep preparation, replacement and cleanup separate for transactions that also move directories. */
|
|
607
|
+
async function stageFileTransaction(updates, validate, namespace) {
|
|
608
|
+
const id = randomUUID();
|
|
609
|
+
const staged = [];
|
|
610
|
+
const check = async (item) => {
|
|
611
|
+
if (await validate(item.update.path) !== item.target) throw new Error(`Transaction target changed: ${item.update.path}`);
|
|
612
|
+
};
|
|
613
|
+
const checkRecoveryFile = async (item, file, content) => {
|
|
614
|
+
const relative = item.update.path + item[file].slice(item.target.length);
|
|
615
|
+
if (await validate(relative) !== item[file] || await readFile(item[file], "utf8") !== content) throw new Error(`Transaction recovery file changed: ${relative}`);
|
|
616
|
+
};
|
|
617
|
+
const rollback = async () => {
|
|
618
|
+
const recovery = [];
|
|
619
|
+
for (const item of [...staged].reverse()) {
|
|
620
|
+
try {
|
|
621
|
+
if (item.applied) {
|
|
622
|
+
await check(item);
|
|
623
|
+
const current = await readFile(item.target, "utf8");
|
|
624
|
+
if (current !== item.update.original && current !== item.update.content) throw new Error("Concurrent edit must be preserved");
|
|
625
|
+
await checkRecoveryFile(item, "backup", item.update.original);
|
|
626
|
+
await rename(item.backup, item.target);
|
|
627
|
+
item.backupOwned = false;
|
|
628
|
+
item.applied = false;
|
|
629
|
+
} else if (item.backupOwned) {
|
|
630
|
+
await checkRecoveryFile(item, "backup", item.update.original);
|
|
631
|
+
await rm(item.backup, { force: true });
|
|
632
|
+
item.backupOwned = false;
|
|
633
|
+
}
|
|
634
|
+
} catch {
|
|
635
|
+
recovery.push(item.backup);
|
|
636
|
+
}
|
|
637
|
+
try {
|
|
638
|
+
if (item.temporaryOwned) {
|
|
639
|
+
await check(item);
|
|
640
|
+
await checkRecoveryFile(item, "temporary", item.update.content);
|
|
641
|
+
await rm(item.temporary, { force: true });
|
|
642
|
+
item.temporaryOwned = false;
|
|
643
|
+
}
|
|
644
|
+
} catch {
|
|
645
|
+
recovery.push(item.temporary);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return recovery;
|
|
649
|
+
};
|
|
650
|
+
try {
|
|
651
|
+
for (const update of updates) {
|
|
652
|
+
const target = await validate(update.path);
|
|
653
|
+
if (await readFile(target, "utf8") !== update.original) throw new Error(localize(`Manifest changed before applying: ${update.path}`, `应用前清单发生变化:${update.path}`));
|
|
654
|
+
const item = {
|
|
655
|
+
target,
|
|
656
|
+
temporary: `${target}.repoctl-${namespace}-${id}.tmp`,
|
|
657
|
+
backup: `${target}.repoctl-${namespace}-${id}.bak`,
|
|
658
|
+
update,
|
|
659
|
+
applied: false,
|
|
660
|
+
backupOwned: false,
|
|
661
|
+
temporaryOwned: false
|
|
662
|
+
};
|
|
663
|
+
staged.push(item);
|
|
664
|
+
const metadata = await stat(target);
|
|
665
|
+
await copyFile(target, item.backup, constants.COPYFILE_EXCL);
|
|
666
|
+
item.backupOwned = true;
|
|
667
|
+
await checkRecoveryFile(item, "backup", update.original);
|
|
668
|
+
await utimes(item.backup, metadata.atimeMs / 1e3, metadata.mtimeMs / 1e3);
|
|
669
|
+
const temporary = await open(item.temporary, "wx", metadata.mode);
|
|
670
|
+
item.temporaryOwned = true;
|
|
671
|
+
try {
|
|
672
|
+
await temporary.writeFile(update.content, "utf8");
|
|
673
|
+
} finally {
|
|
674
|
+
await temporary.close();
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
} catch (error) {
|
|
678
|
+
const recovery = await rollback();
|
|
679
|
+
if (recovery.length) throw new AggregateError([error], localize(`File preparation failed; recovery files retained: ${recovery.join(", ")}`, `文件准备失败;已保留恢复文件:${recovery.join(",")}`));
|
|
680
|
+
throw error;
|
|
681
|
+
}
|
|
682
|
+
return {
|
|
683
|
+
/** Exact operation-owned files, for directory-level verification before cleanup. */
|
|
684
|
+
recoveryPaths: () => staged.flatMap((item) => [...item.backupOwned ? [item.backup] : [], ...item.temporaryOwned ? [item.temporary] : []]),
|
|
685
|
+
async apply() {
|
|
686
|
+
for (const item of staged) {
|
|
687
|
+
await check(item);
|
|
688
|
+
if (await readFile(item.target, "utf8") !== item.update.original) throw new Error(localize(`Concurrent manifest change: ${item.update.path}`, `清单被并发修改:${item.update.path}`));
|
|
689
|
+
await checkRecoveryFile(item, "temporary", item.update.content);
|
|
690
|
+
await rename(item.temporary, item.target);
|
|
691
|
+
item.applied = true;
|
|
692
|
+
item.temporaryOwned = false;
|
|
693
|
+
}
|
|
694
|
+
},
|
|
695
|
+
rollback,
|
|
696
|
+
async cleanup() {
|
|
697
|
+
const leftovers = [];
|
|
698
|
+
for (const item of staged) try {
|
|
699
|
+
await check(item);
|
|
700
|
+
await checkRecoveryFile(item, "backup", item.update.original);
|
|
701
|
+
await rm(item.backup, { force: true });
|
|
702
|
+
} catch {
|
|
703
|
+
leftovers.push(item.backup);
|
|
704
|
+
}
|
|
705
|
+
return leftovers;
|
|
706
|
+
}
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
//#endregion
|
|
710
|
+
//#region src/utils/object.ts
|
|
711
|
+
const arrayIndexPattern = /^\d+$/;
|
|
712
|
+
function isArrayIndex(value) {
|
|
713
|
+
return arrayIndexPattern.test(value);
|
|
714
|
+
}
|
|
715
|
+
function parsePath(input) {
|
|
716
|
+
const segments = [];
|
|
717
|
+
let current = "";
|
|
718
|
+
let escaped = false;
|
|
719
|
+
for (const char of input) {
|
|
720
|
+
if (escaped) {
|
|
721
|
+
current += char;
|
|
722
|
+
escaped = false;
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
if (char === "\\") {
|
|
726
|
+
escaped = true;
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
if (char === ".") {
|
|
730
|
+
segments.push(current);
|
|
731
|
+
current = "";
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
current += char;
|
|
735
|
+
}
|
|
736
|
+
segments.push(current);
|
|
737
|
+
return segments;
|
|
738
|
+
}
|
|
739
|
+
function setByPath(target, path, value) {
|
|
740
|
+
const segments = typeof path === "string" ? parsePath(path) : [...path];
|
|
741
|
+
if (!segments.length) return target;
|
|
742
|
+
let current = target;
|
|
743
|
+
for (let index = 0; index < segments.length - 1; index++) {
|
|
744
|
+
const segment = segments[index];
|
|
745
|
+
const nextSegment = segments[index + 1];
|
|
746
|
+
const key = Array.isArray(current) && isArrayIndex(segment) ? Number(segment) : segment;
|
|
747
|
+
const existing = current[key];
|
|
748
|
+
if (typeof existing !== "object" || existing === null) current[key] = isArrayIndex(nextSegment) ? [] : {};
|
|
749
|
+
current = current[key];
|
|
750
|
+
}
|
|
751
|
+
const lastSegment = segments.at(-1);
|
|
752
|
+
const lastKey = Array.isArray(current) && isArrayIndex(lastSegment) ? Number(lastSegment) : lastSegment;
|
|
753
|
+
current[lastKey] = value;
|
|
754
|
+
return target;
|
|
755
|
+
}
|
|
756
|
+
//#endregion
|
|
757
|
+
//#region src/commands/tooling-migration.ts
|
|
758
|
+
const legacyToolingLoaderImportPattern = /import\s+\{\s*load(?:Repoctl|Monorepo)ToolingModule\s*\}\s+from\s+['"][^'"]*tooling\/load-tooling-module\.mjs['"]\s*;?\n?/g;
|
|
759
|
+
const legacyToolingLoaderCallPattern = /const\s+\{\s*([\w$]+(?:\s*,\s*[\w$]+)*)\s*\}\s*=\s*await\s+load(?:Repoctl|Monorepo)ToolingModule\(\)\s*;?\n?/g;
|
|
760
|
+
const legacyToolingEntryPattern = /packages\/(?:monorepo|repoctl)\/dist\/tooling-entry\.mjs/;
|
|
761
|
+
const directToolingPackages = [
|
|
762
|
+
{
|
|
763
|
+
source: "@icebreakers/commitlint-config",
|
|
764
|
+
importName: "defineCommitlintConfig",
|
|
765
|
+
wrapSingleArgument: true
|
|
766
|
+
},
|
|
767
|
+
{
|
|
768
|
+
source: "@icebreakers/eslint-config",
|
|
769
|
+
importName: "defineEslintConfig",
|
|
770
|
+
wrapSingleArgument: false
|
|
771
|
+
},
|
|
772
|
+
{
|
|
773
|
+
source: "@icebreakers/stylelint-config",
|
|
774
|
+
importName: "defineStylelintConfig",
|
|
775
|
+
wrapSingleArgument: true
|
|
776
|
+
}
|
|
777
|
+
];
|
|
778
|
+
function normalizeNamedImports(input) {
|
|
779
|
+
return [...new Set(input.split(",").map((item) => item.trim()).filter(Boolean))].sort((left, right) => left.localeCompare(right));
|
|
780
|
+
}
|
|
781
|
+
function hasLegacyToolingReference(content) {
|
|
782
|
+
return content.includes("tooling/load-tooling-module.mjs") || content.includes("loadRepoctlToolingModule") || content.includes("loadMonorepoToolingModule") || legacyToolingEntryPattern.test(content) || directToolingPackages.some((pkg) => content.includes(pkg.source));
|
|
783
|
+
}
|
|
784
|
+
function escapeRegExp(input) {
|
|
785
|
+
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
786
|
+
}
|
|
787
|
+
function findMatchingCloseParen(content, openParenIndex) {
|
|
788
|
+
let depth = 0;
|
|
789
|
+
let quote = null;
|
|
790
|
+
let escaped = false;
|
|
791
|
+
let lineComment = false;
|
|
792
|
+
let blockComment = false;
|
|
793
|
+
for (let index = openParenIndex; index < content.length; index++) {
|
|
794
|
+
const char = content[index];
|
|
795
|
+
const next = content[index + 1];
|
|
796
|
+
if (lineComment) {
|
|
797
|
+
if (char === "\n") lineComment = false;
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
if (blockComment) {
|
|
801
|
+
if (char === "*" && next === "/") {
|
|
802
|
+
blockComment = false;
|
|
803
|
+
index++;
|
|
804
|
+
}
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
if (quote) {
|
|
808
|
+
if (escaped) {
|
|
809
|
+
escaped = false;
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
if (char === "\\") {
|
|
813
|
+
escaped = true;
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
if (char === quote) quote = null;
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
if (char === "/" && next === "/") {
|
|
820
|
+
lineComment = true;
|
|
821
|
+
index++;
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
if (char === "/" && next === "*") {
|
|
825
|
+
blockComment = true;
|
|
826
|
+
index++;
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
if (char === "'" || char === "\"" || char === "`") {
|
|
830
|
+
quote = char;
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
if (char === "(") {
|
|
834
|
+
depth++;
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
if (char === ")") {
|
|
838
|
+
depth--;
|
|
839
|
+
if (depth === 0) return index;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
return -1;
|
|
843
|
+
}
|
|
844
|
+
function hasTopLevelComma(content) {
|
|
845
|
+
if (findMatchingCloseParen(`(${content})`, 0) === -1) return true;
|
|
846
|
+
let depth = 0;
|
|
847
|
+
let quote = null;
|
|
848
|
+
let escaped = false;
|
|
849
|
+
for (let index = 0; index < content.length; index++) {
|
|
850
|
+
const char = content[index];
|
|
851
|
+
if (quote) {
|
|
852
|
+
if (escaped) {
|
|
853
|
+
escaped = false;
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
if (char === "\\") {
|
|
857
|
+
escaped = true;
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
if (char === quote) quote = null;
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
if (char === "'" || char === "\"" || char === "`") {
|
|
864
|
+
quote = char;
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
if ("([{".includes(char)) {
|
|
868
|
+
depth++;
|
|
869
|
+
continue;
|
|
870
|
+
}
|
|
871
|
+
if (")]}".includes(char)) {
|
|
872
|
+
depth--;
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
if (char === "," && depth === 0) return true;
|
|
876
|
+
}
|
|
877
|
+
return false;
|
|
878
|
+
}
|
|
879
|
+
function removeSimpleNamedImport(content, source) {
|
|
880
|
+
const pattern = new RegExp(`import\\s+\\{\\s*icebreaker(?:\\s+as\\s+([\\w$]+))?\\s*\\}\\s+from\\s+['"]${escapeRegExp(source)}['"]\\s*;?\\n?`);
|
|
881
|
+
const match = pattern.exec(content);
|
|
882
|
+
if (!match) return null;
|
|
883
|
+
return {
|
|
884
|
+
localName: match[1] ?? "icebreaker",
|
|
885
|
+
content: content.replace(pattern, "")
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
function replaceExportDefaultCall(content, localName, importName, wrapSingleArgument) {
|
|
889
|
+
const match = new RegExp(`export\\s+default\\s+(?:await\\s+)?${escapeRegExp(localName)}\\s*\\(`).exec(content);
|
|
890
|
+
if (!match) return null;
|
|
891
|
+
const openParenIndex = match.index + match[0].length - 1;
|
|
892
|
+
const closeParenIndex = findMatchingCloseParen(content, openParenIndex);
|
|
893
|
+
if (closeParenIndex === -1) return null;
|
|
894
|
+
const args = content.slice(openParenIndex + 1, closeParenIndex).trim();
|
|
895
|
+
if (wrapSingleArgument && args && hasTopLevelComma(args)) return null;
|
|
896
|
+
const defineArgs = wrapSingleArgument && args ? `{ options: ${args} }` : args;
|
|
897
|
+
return [
|
|
898
|
+
content.slice(0, match.index),
|
|
899
|
+
`export default await ${importName}(${defineArgs})`,
|
|
900
|
+
content.slice(closeParenIndex + 1)
|
|
901
|
+
].join("");
|
|
902
|
+
}
|
|
903
|
+
function migrateDirectToolingReferences(content, importSource = "repoctl/tooling") {
|
|
904
|
+
let nextContent = content;
|
|
905
|
+
const importNames = [];
|
|
906
|
+
for (const pkg of directToolingPackages) {
|
|
907
|
+
if (!nextContent.includes(pkg.source)) continue;
|
|
908
|
+
const removed = removeSimpleNamedImport(nextContent, pkg.source);
|
|
909
|
+
if (!removed) continue;
|
|
910
|
+
const replaced = replaceExportDefaultCall(removed.content, removed.localName, pkg.importName, pkg.wrapSingleArgument);
|
|
911
|
+
if (!replaced) continue;
|
|
912
|
+
nextContent = replaced;
|
|
913
|
+
importNames.push(pkg.importName);
|
|
914
|
+
}
|
|
915
|
+
if (importNames.length === 0) return content;
|
|
916
|
+
return `${`import { ${normalizeNamedImports(importNames.join(",")).join(", ")} } from '${importSource}'\n\n`}${nextContent}`.replace(/\n{3,}/g, "\n\n").trimStart();
|
|
917
|
+
}
|
|
918
|
+
function migrateLegacyToolingReferences(content, importSource = "repoctl/tooling") {
|
|
919
|
+
if (!hasLegacyToolingReference(content)) return content;
|
|
920
|
+
const importNames = [];
|
|
921
|
+
let nextContent = content.replace(legacyToolingLoaderCallPattern, (_match, imports) => {
|
|
922
|
+
importNames.push(...normalizeNamedImports(imports));
|
|
923
|
+
return "";
|
|
924
|
+
});
|
|
925
|
+
if (importNames.length === 0) return migrateDirectToolingReferences(nextContent, importSource).replace(legacyToolingLoaderImportPattern, "").replace(/\n{3,}/g, "\n\n");
|
|
926
|
+
nextContent = nextContent.replace(legacyToolingLoaderImportPattern, "");
|
|
927
|
+
return migrateDirectToolingReferences(`${`import { ${normalizeNamedImports(importNames.join(",")).join(", ")} } from '${importSource}'\n`}${nextContent}`, importSource).replace(/\n{3,}/g, "\n\n").trimStart();
|
|
928
|
+
}
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/commands/create/render.ts
|
|
931
|
+
const rootReferenceExtensions = /* @__PURE__ */ new Set([
|
|
932
|
+
".cjs",
|
|
933
|
+
".cts",
|
|
934
|
+
".js",
|
|
935
|
+
".json",
|
|
936
|
+
".mjs",
|
|
937
|
+
".mts",
|
|
938
|
+
".ts"
|
|
939
|
+
]);
|
|
940
|
+
const rootReferenceReplacements = [{
|
|
941
|
+
from: "../../tsconfig.json",
|
|
942
|
+
to: "tsconfig.json"
|
|
943
|
+
}];
|
|
944
|
+
async function applyGitMetadata(pkgJson, repoDir, targetDir) {
|
|
945
|
+
try {
|
|
946
|
+
const git = new GitClient({ baseDir: repoDir });
|
|
947
|
+
const repoName = await git.getRepoName();
|
|
948
|
+
if (!repoName) return;
|
|
949
|
+
setByPath(pkgJson, ["bugs", "url"], `https://github.com/${repoName}/issues`);
|
|
950
|
+
const repository = {
|
|
951
|
+
type: "git",
|
|
952
|
+
url: `git+https://github.com/${repoName}.git`
|
|
953
|
+
};
|
|
954
|
+
const directoryBase = await git.getRepoRoot() ?? repoDir;
|
|
955
|
+
const relative = path.relative(directoryBase, targetDir);
|
|
956
|
+
if (relative && relative !== ".") repository.directory = relative.split(path.sep).join("/");
|
|
957
|
+
setByPath(pkgJson, "repository", repository);
|
|
958
|
+
const gitUser = await git.getUser();
|
|
959
|
+
if (gitUser?.name && gitUser?.email) setByPath(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
|
|
960
|
+
} catch {}
|
|
961
|
+
}
|
|
962
|
+
function sanitizeTemplatePackageJson(pkgJson) {
|
|
963
|
+
delete pkgJson.author;
|
|
964
|
+
delete pkgJson.bugs;
|
|
965
|
+
delete pkgJson.homepage;
|
|
966
|
+
delete pkgJson.repository;
|
|
967
|
+
}
|
|
968
|
+
function normalizeRelativeSpecifier(fromDir, targetPath) {
|
|
969
|
+
const relativePath = path.relative(fromDir, targetPath).split(path.sep).join("/");
|
|
970
|
+
if (relativePath.startsWith(".")) return relativePath;
|
|
971
|
+
return `./${relativePath}`;
|
|
972
|
+
}
|
|
973
|
+
async function rewriteTemplateRootReferences(targetDir, workspaceDir) {
|
|
974
|
+
let entries;
|
|
975
|
+
try {
|
|
976
|
+
entries = await readdir(targetDir, { withFileTypes: true });
|
|
977
|
+
} catch (error) {
|
|
978
|
+
if (error.code === "ENOENT") return;
|
|
979
|
+
throw error;
|
|
980
|
+
}
|
|
981
|
+
await Promise.all(entries.map(async (entry) => {
|
|
982
|
+
const entryPath = path.join(targetDir, entry.name);
|
|
983
|
+
if (entry.isDirectory()) {
|
|
984
|
+
await rewriteTemplateRootReferences(entryPath, workspaceDir);
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (!entry.isFile() || !rootReferenceExtensions.has(path.extname(entry.name))) return;
|
|
988
|
+
const originalContent = await fs$2.readFile(entryPath, "utf8");
|
|
989
|
+
let nextContent = migrateLegacyToolingReferences(originalContent, "repoctl/tooling");
|
|
990
|
+
for (const replacement of rootReferenceReplacements) {
|
|
991
|
+
if (!nextContent.includes(replacement.from)) continue;
|
|
992
|
+
const targetPath = path.join(workspaceDir, replacement.to);
|
|
993
|
+
const rewrittenSpecifier = normalizeRelativeSpecifier(path.dirname(entryPath), targetPath);
|
|
994
|
+
nextContent = nextContent.replaceAll(replacement.from, rewrittenSpecifier);
|
|
995
|
+
}
|
|
996
|
+
if (nextContent !== originalContent) await fs$2.writeFile(entryPath, nextContent, "utf8");
|
|
997
|
+
}));
|
|
998
|
+
}
|
|
999
|
+
/** Rewrite engineering references before inserting user data, which must retain its exact bytes. */
|
|
1000
|
+
function rewriteTemplateSnapshotReferences(snapshot, targetDir, workspaceDir) {
|
|
1001
|
+
return {
|
|
1002
|
+
...snapshot,
|
|
1003
|
+
files: snapshot.files.map((file) => {
|
|
1004
|
+
if (["repoctl.template.json", "package.json"].includes(file.path) || !rootReferenceExtensions.has(path.extname(file.path))) return file;
|
|
1005
|
+
const content = Buffer.from(file.content, "base64");
|
|
1006
|
+
if (content.includes(0)) return file;
|
|
1007
|
+
let text;
|
|
1008
|
+
try {
|
|
1009
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(content);
|
|
1010
|
+
} catch {
|
|
1011
|
+
return file;
|
|
1012
|
+
}
|
|
1013
|
+
text = migrateLegacyToolingReferences(text, "repoctl/tooling");
|
|
1014
|
+
for (const replacement of rootReferenceReplacements) text = text.replaceAll(replacement.from, normalizeRelativeSpecifier(path.dirname(path.join(targetDir, file.path)), path.join(workspaceDir, replacement.to)));
|
|
1015
|
+
return {
|
|
1016
|
+
...file,
|
|
1017
|
+
content: Buffer.from(text).toString("base64")
|
|
1018
|
+
};
|
|
1019
|
+
})
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
async function renderCreateNewProject(plan, gitMetadata = true) {
|
|
1023
|
+
if (plan.snapshot) {
|
|
1024
|
+
for (const directory of plan.snapshot.directories) await fs$2.ensureDir(path.join(plan.targetDir, directory));
|
|
1025
|
+
for (const file of plan.snapshot.files.filter((file) => file.path !== "package.json")) {
|
|
1026
|
+
const target = path.join(plan.targetDir, file.path.replace(/(^|\/)gitignore$/u, "$1.gitignore"));
|
|
1027
|
+
await fs$2.outputFile(target, Buffer.from(file.content, "base64"));
|
|
1028
|
+
await chmod(target, file.executable ? 493 : 420);
|
|
1029
|
+
}
|
|
1030
|
+
} else await scaffoldTemplate({
|
|
1031
|
+
sourceDir: plan.sourceDir,
|
|
1032
|
+
targetDir: plan.targetDir,
|
|
1033
|
+
skipRootBasenames: ["package.json"]
|
|
1034
|
+
});
|
|
1035
|
+
if (!plan.snapshot) await rewriteTemplateRootReferences(plan.targetDir, plan.cwd);
|
|
1036
|
+
if (plan.hasPackageJson) {
|
|
1037
|
+
const parameterPackage = plan.snapshot?.files.find((file) => file.path === "package.json");
|
|
1038
|
+
const sourceJson = parameterPackage ? JSON.parse(Buffer.from(parameterPackage.content, "base64").toString("utf8")) : await fs$2.readJson(path.resolve(plan.sourceDir, "package.json"));
|
|
1039
|
+
sanitizeTemplatePackageJson(sourceJson);
|
|
1040
|
+
setByPath(sourceJson, "version", "0.0.0");
|
|
1041
|
+
setByPath(sourceJson, "name", plan.packageName);
|
|
1042
|
+
if (gitMetadata) await applyGitMetadata(sourceJson, plan.metadataCwd ?? plan.cwd, plan.metadataTarget ?? plan.targetDir);
|
|
1043
|
+
await fs$2.outputJson(path.resolve(plan.targetDir, plan.packageJsonFileName), sourceJson, { spaces: 2 });
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
//#endregion
|
|
1047
|
+
//#region src/commands/deps/files.ts
|
|
1048
|
+
function hash(content) {
|
|
1049
|
+
return createHash("sha256").update(content).digest("hex");
|
|
1050
|
+
}
|
|
1051
|
+
function record$2(value) {
|
|
1052
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1053
|
+
}
|
|
1054
|
+
/** Retain lexical paths so a symlink cannot hide an out-of-workspace manifest. */
|
|
1055
|
+
async function safeFile(root, relative) {
|
|
1056
|
+
const target = path.resolve(root, relative);
|
|
1057
|
+
const resolved = path.relative(root, target);
|
|
1058
|
+
if (!resolved || resolved === ".." || resolved.startsWith("../") || path.isAbsolute(resolved)) throw new Error(localize(`Unsafe dependency input: ${relative}`, `依赖输入路径不安全:${relative}`));
|
|
1059
|
+
let current = root;
|
|
1060
|
+
for (const component of resolved.split("/")) {
|
|
1061
|
+
current = path.join(current, component);
|
|
1062
|
+
const entry = await lstat(current);
|
|
1063
|
+
if (entry.isSymbolicLink() || (current === target ? !entry.isFile() || entry.nlink > 1 : !entry.isDirectory())) throw new Error(localize(`Linked or unsupported dependency input: ${relative}`, `依赖输入是链接或不支持的文件:${relative}`));
|
|
1064
|
+
}
|
|
1065
|
+
if (path.resolve(await realpath(target)) !== target) throw new Error(localize(`Dependency input changed: ${relative}`, `依赖输入发生变化:${relative}`));
|
|
1066
|
+
return target;
|
|
1067
|
+
}
|
|
1068
|
+
async function readInput(root, relative) {
|
|
1069
|
+
return readFile(await safeFile(root, relative), "utf8");
|
|
1070
|
+
}
|
|
1071
|
+
function updateManifest(original, section, dependency, target) {
|
|
1072
|
+
const manifest = JSON.parse(original);
|
|
1073
|
+
manifest[section][dependency] = target;
|
|
1074
|
+
const indentation = original.match(/\n([\t ]+)"/)?.[1] ?? " ";
|
|
1075
|
+
const newline = original.includes("\r\n") ? "\r\n" : "\n";
|
|
1076
|
+
return `${JSON.stringify(manifest, null, indentation).replaceAll("\n", newline)}${original.endsWith("\n") ? newline : ""}`;
|
|
1077
|
+
}
|
|
1078
|
+
//#endregion
|
|
1079
|
+
//#region src/core/workspace-graph/shared.ts
|
|
1080
|
+
const workspaceDependencyTypes = [
|
|
1081
|
+
"dependencies",
|
|
1082
|
+
"devDependencies",
|
|
1083
|
+
"optionalDependencies",
|
|
1084
|
+
"peerDependencies"
|
|
1085
|
+
];
|
|
1086
|
+
function compareGraphValues(left, right) {
|
|
1087
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
1088
|
+
}
|
|
1089
|
+
function normalizeDependencyTypes(types = workspaceDependencyTypes) {
|
|
1090
|
+
for (const type of types) if (!workspaceDependencyTypes.includes(type)) throw new Error(`Unknown dependency type: ${type}. Expected ${workspaceDependencyTypes.join(", ")}.`);
|
|
1091
|
+
return workspaceDependencyTypes.filter((type) => types.includes(type));
|
|
1092
|
+
}
|
|
1093
|
+
var WorkspaceGraphQueryError = class extends Error {
|
|
1094
|
+
code;
|
|
1095
|
+
selector;
|
|
1096
|
+
candidates;
|
|
1097
|
+
constructor(code, selector, candidates) {
|
|
1098
|
+
super(code === "ambiguous_package" ? `Ambiguous workspace package ${selector}; use an explicit directory: ${candidates.map((id) => `./${id}`).join(", ")}` : `Workspace package not found: ${selector}`);
|
|
1099
|
+
this.code = code;
|
|
1100
|
+
this.selector = selector;
|
|
1101
|
+
this.candidates = candidates;
|
|
1102
|
+
this.name = "WorkspaceGraphQueryError";
|
|
1103
|
+
}
|
|
1104
|
+
};
|
|
1105
|
+
function resolveWorkspaceGraphNode(graph, selector) {
|
|
1106
|
+
const directory = selector.replaceAll("\\", "/");
|
|
1107
|
+
const byName = directory.startsWith("./") ? [] : graph.nodes.filter((node) => node.name === selector);
|
|
1108
|
+
if (byName.length > 1) throw new WorkspaceGraphQueryError("ambiguous_package", selector, byName.map((node) => node.id).sort(compareGraphValues));
|
|
1109
|
+
const id = directory === "./" ? "." : directory.replace(/^\.\//, "").replace(/\/$/, "");
|
|
1110
|
+
const node = byName[0] ?? graph.nodes.find((node) => node.id === id);
|
|
1111
|
+
if (!node) throw new WorkspaceGraphQueryError("package_not_found", selector, []);
|
|
1112
|
+
return node;
|
|
1113
|
+
}
|
|
1114
|
+
//#endregion
|
|
1115
|
+
//#region src/core/workspace-graph/query.ts
|
|
1116
|
+
function edgeKey(edge) {
|
|
1117
|
+
return JSON.stringify([
|
|
1118
|
+
edge.source,
|
|
1119
|
+
edge.target,
|
|
1120
|
+
edge.type,
|
|
1121
|
+
edge.dependency,
|
|
1122
|
+
edge.specifier
|
|
1123
|
+
]);
|
|
1124
|
+
}
|
|
1125
|
+
/** Keep selected packages and their immediate consumers/dependencies, without mutating the graph. */
|
|
1126
|
+
function filterWorkspaceGraph(graph, options = {}) {
|
|
1127
|
+
const dependencyTypes = normalizeDependencyTypes(options.dependencyTypes ?? graph.dependencyTypes);
|
|
1128
|
+
const selected = options.packages?.length ? new Set(options.packages.map((selector) => resolveWorkspaceGraphNode(graph, selector).id)) : void 0;
|
|
1129
|
+
const edges = graph.edges.filter((edge) => dependencyTypes.includes(edge.type) && (!selected || selected.has(edge.source) || selected.has(edge.target))).sort((a, b) => compareGraphValues(edgeKey(a), edgeKey(b)));
|
|
1130
|
+
const included = selected ? /* @__PURE__ */ new Set([...selected, ...edges.flatMap((edge) => [edge.source, edge.target])]) : void 0;
|
|
1131
|
+
return {
|
|
1132
|
+
...graph,
|
|
1133
|
+
dependencyTypes,
|
|
1134
|
+
nodes: graph.nodes.filter((node) => !included || included.has(node.id)).sort((a, b) => compareGraphValues(a.id, b.id)),
|
|
1135
|
+
edges,
|
|
1136
|
+
diagnostics: graph.diagnostics.filter((item) => (!item.type || dependencyTypes.includes(item.type)) && (!included || (item.source ? included.has(item.source) : item.candidates.some((id) => included.has(id)))))
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
function adjacency(graph, reverse) {
|
|
1140
|
+
const result = /* @__PURE__ */ new Map();
|
|
1141
|
+
for (const edge of graph.edges) {
|
|
1142
|
+
const id = reverse ? edge.target : edge.source;
|
|
1143
|
+
const edges = result.get(id) ?? [];
|
|
1144
|
+
edges.push(edge);
|
|
1145
|
+
result.set(id, edges);
|
|
1146
|
+
}
|
|
1147
|
+
return result;
|
|
1148
|
+
}
|
|
1149
|
+
/** One shortest path, found with breadth-first search; cyclic graphs never enumerate all paths. */
|
|
1150
|
+
function whyWorkspaceDependency(graph, from, to, options = {}) {
|
|
1151
|
+
const filtered = filterWorkspaceGraph(graph, options);
|
|
1152
|
+
const source = resolveWorkspaceGraphNode(filtered, from).id;
|
|
1153
|
+
const target = resolveWorkspaceGraphNode(filtered, to).id;
|
|
1154
|
+
const outgoing = adjacency(filtered, false);
|
|
1155
|
+
const visited = /* @__PURE__ */ new Set([source]);
|
|
1156
|
+
const previous = /* @__PURE__ */ new Map();
|
|
1157
|
+
const queue = [source];
|
|
1158
|
+
for (let cursor = 0; cursor < queue.length && !visited.has(target); cursor++) for (const edge of outgoing.get(queue[cursor]) ?? []) if (!visited.has(edge.target)) {
|
|
1159
|
+
visited.add(edge.target);
|
|
1160
|
+
previous.set(edge.target, edge);
|
|
1161
|
+
queue.push(edge.target);
|
|
1162
|
+
}
|
|
1163
|
+
const edges = [];
|
|
1164
|
+
let current = target;
|
|
1165
|
+
while (previous.has(current)) {
|
|
1166
|
+
const edge = previous.get(current);
|
|
1167
|
+
edges.push(edge);
|
|
1168
|
+
current = edge.source;
|
|
1169
|
+
}
|
|
1170
|
+
edges.reverse();
|
|
1171
|
+
const found = visited.has(target);
|
|
1172
|
+
return {
|
|
1173
|
+
schemaVersion: 1,
|
|
1174
|
+
from: source,
|
|
1175
|
+
to: target,
|
|
1176
|
+
found,
|
|
1177
|
+
path: found ? [source, ...edges.map((edge) => edge.target)] : [],
|
|
1178
|
+
edges,
|
|
1179
|
+
dependencyTypes: filtered.dependencyTypes,
|
|
1180
|
+
diagnostics: filtered.diagnostics
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
/** Reverse reachability; the queried package itself is excluded even in a cycle. */
|
|
1184
|
+
function getWorkspaceImpact(graph, selector, options = {}) {
|
|
1185
|
+
const filtered = filterWorkspaceGraph(graph, options);
|
|
1186
|
+
const target = resolveWorkspaceGraphNode(filtered, selector).id;
|
|
1187
|
+
const incoming = adjacency(filtered, true);
|
|
1188
|
+
const distance = /* @__PURE__ */ new Map([[target, 0]]);
|
|
1189
|
+
const next = /* @__PURE__ */ new Map();
|
|
1190
|
+
const queue = [target];
|
|
1191
|
+
for (let cursor = 0; cursor < queue.length; cursor++) {
|
|
1192
|
+
const current = queue[cursor];
|
|
1193
|
+
if (options.direct && current !== target) continue;
|
|
1194
|
+
for (const edge of incoming.get(current) ?? []) if (!distance.has(edge.source)) {
|
|
1195
|
+
distance.set(edge.source, distance.get(current) + 1);
|
|
1196
|
+
next.set(edge.source, current);
|
|
1197
|
+
queue.push(edge.source);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
const consumers = queue.slice(1).sort(compareGraphValues).map((id) => {
|
|
1201
|
+
const path = [id];
|
|
1202
|
+
let current = id;
|
|
1203
|
+
while (next.has(current)) {
|
|
1204
|
+
current = next.get(current);
|
|
1205
|
+
path.push(current);
|
|
1206
|
+
}
|
|
1207
|
+
return {
|
|
1208
|
+
id,
|
|
1209
|
+
distance: distance.get(id),
|
|
1210
|
+
direct: distance.get(id) === 1,
|
|
1211
|
+
path
|
|
1212
|
+
};
|
|
1213
|
+
});
|
|
1214
|
+
return {
|
|
1215
|
+
schemaVersion: 1,
|
|
1216
|
+
target,
|
|
1217
|
+
directOnly: options.direct === true,
|
|
1218
|
+
dependencyTypes: filtered.dependencyTypes,
|
|
1219
|
+
consumers,
|
|
1220
|
+
diagnostics: filtered.diagnostics
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
//#endregion
|
|
1224
|
+
//#region src/core/workspace-graph/resolve.ts
|
|
1225
|
+
function parseDependencyReference(dependency, specifier, rootDir) {
|
|
1226
|
+
const workspace = specifier.startsWith("workspace:");
|
|
1227
|
+
if (specifier.startsWith("link:") || specifier.startsWith("file:") || workspace && specifier.slice(10).startsWith(".")) return {
|
|
1228
|
+
directory: path.resolve(rootDir, specifier.slice(specifier.indexOf(":") + 1)),
|
|
1229
|
+
range: "*",
|
|
1230
|
+
required: true,
|
|
1231
|
+
resolution: workspace ? "workspace" : "local"
|
|
1232
|
+
};
|
|
1233
|
+
let name = dependency;
|
|
1234
|
+
let range = workspace ? specifier.slice(10) : specifier;
|
|
1235
|
+
if (workspace || specifier.startsWith("npm:")) {
|
|
1236
|
+
if (!workspace) range = specifier.slice(4);
|
|
1237
|
+
const separator = range.lastIndexOf("@");
|
|
1238
|
+
if (separator > 0) {
|
|
1239
|
+
name = range.slice(0, separator);
|
|
1240
|
+
range = range.slice(separator + 1);
|
|
1241
|
+
} else if (!workspace) return;
|
|
1242
|
+
if (workspace && (range === "^" || range === "~")) range = "*";
|
|
1243
|
+
}
|
|
1244
|
+
if (!semver.validRange(range)) return workspace ? {
|
|
1245
|
+
name,
|
|
1246
|
+
range: "",
|
|
1247
|
+
required: true,
|
|
1248
|
+
resolution: "workspace"
|
|
1249
|
+
} : void 0;
|
|
1250
|
+
return {
|
|
1251
|
+
name,
|
|
1252
|
+
range,
|
|
1253
|
+
required: workspace,
|
|
1254
|
+
resolution: workspace ? "workspace" : "semver"
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
function resolveGraphDependency(source, sourceId, dependency, specifier, type, packages, nodes) {
|
|
1258
|
+
const reference = parseDependencyReference(dependency, specifier, source.rootDir);
|
|
1259
|
+
if (!reference) {
|
|
1260
|
+
const alias = specifier.startsWith("npm:") ? specifier.slice(4) : void 0;
|
|
1261
|
+
const separator = alias?.lastIndexOf("@") ?? -1;
|
|
1262
|
+
const name = alias ? separator > 0 ? alias.slice(0, separator) : alias : dependency;
|
|
1263
|
+
const candidates = nodes.filter((node) => node.name === name).map((node) => node.id);
|
|
1264
|
+
if (candidates.length || specifier.startsWith("catalog:")) return { diagnostic: {
|
|
1265
|
+
code: "unresolved_specifier",
|
|
1266
|
+
source: sourceId,
|
|
1267
|
+
dependency,
|
|
1268
|
+
type,
|
|
1269
|
+
specifier,
|
|
1270
|
+
candidates
|
|
1271
|
+
} };
|
|
1272
|
+
return {};
|
|
1273
|
+
}
|
|
1274
|
+
let directory = reference.directory;
|
|
1275
|
+
if (directory) try {
|
|
1276
|
+
directory = path.normalize(realpathSync(directory));
|
|
1277
|
+
} catch {}
|
|
1278
|
+
const candidates = nodes.filter((node, index) => directory ? packages[index].rootDir === directory : node.name === reference.name);
|
|
1279
|
+
const diagnostic = (code) => ({ diagnostic: {
|
|
1280
|
+
code,
|
|
1281
|
+
source: sourceId,
|
|
1282
|
+
dependency,
|
|
1283
|
+
type,
|
|
1284
|
+
specifier,
|
|
1285
|
+
candidates: candidates.map((node) => node.id)
|
|
1286
|
+
} });
|
|
1287
|
+
if (!reference.range) return diagnostic("invalid_specifier");
|
|
1288
|
+
if (!candidates.length) return reference.required ? diagnostic("unresolved_dependency") : {};
|
|
1289
|
+
if (candidates.length > 1) return diagnostic("ambiguous_dependency");
|
|
1290
|
+
const target = candidates[0];
|
|
1291
|
+
if (reference.required && reference.range === "*") return {
|
|
1292
|
+
target: target.id,
|
|
1293
|
+
resolution: reference.resolution
|
|
1294
|
+
};
|
|
1295
|
+
if (target.version && semver.satisfies(target.version, reference.range)) return {
|
|
1296
|
+
target: target.id,
|
|
1297
|
+
resolution: reference.resolution
|
|
1298
|
+
};
|
|
1299
|
+
return reference.required ? diagnostic("incompatible_version") : {};
|
|
1300
|
+
}
|
|
1301
|
+
//#endregion
|
|
1302
|
+
//#region src/core/workspace-graph/index.ts
|
|
1303
|
+
/** Read manifest relationships, including private packages by default; never writes files. */
|
|
1304
|
+
async function getWorkspaceGraph(cwd, options = {}) {
|
|
1305
|
+
clearWorkspaceCache();
|
|
1306
|
+
const data = await getWorkspaceData(cwd, {
|
|
1307
|
+
...options,
|
|
1308
|
+
ignorePrivatePackage: options.ignorePrivatePackage ?? false
|
|
1309
|
+
});
|
|
1310
|
+
const packages = [...data.packages].sort((a, b) => compareGraphValues(a.rootDir, b.rootDir));
|
|
1311
|
+
const nodes = packages.map((pkg) => ({
|
|
1312
|
+
id: path.relative(data.workspaceDir, pkg.rootDir) || ".",
|
|
1313
|
+
...pkg.manifest.name ? { name: pkg.manifest.name } : {},
|
|
1314
|
+
...pkg.manifest.version ? { version: pkg.manifest.version } : {},
|
|
1315
|
+
private: pkg.manifest.private === true
|
|
1316
|
+
}));
|
|
1317
|
+
const graph = {
|
|
1318
|
+
schemaVersion: 1,
|
|
1319
|
+
cwd: data.cwd,
|
|
1320
|
+
workspaceDir: data.workspaceDir,
|
|
1321
|
+
dependencyTypes: normalizeDependencyTypes(options.dependencyTypes),
|
|
1322
|
+
nodes,
|
|
1323
|
+
edges: [],
|
|
1324
|
+
diagnostics: []
|
|
1325
|
+
};
|
|
1326
|
+
const names = /* @__PURE__ */ new Map();
|
|
1327
|
+
for (const node of nodes) if (node.name) {
|
|
1328
|
+
const ids = names.get(node.name) ?? [];
|
|
1329
|
+
ids.push(node.id);
|
|
1330
|
+
names.set(node.name, ids);
|
|
1331
|
+
}
|
|
1332
|
+
for (const [dependency, candidates] of [...names].sort(([a], [b]) => compareGraphValues(a, b))) if (candidates.length > 1) graph.diagnostics.push({
|
|
1333
|
+
code: "duplicate_name",
|
|
1334
|
+
dependency,
|
|
1335
|
+
candidates
|
|
1336
|
+
});
|
|
1337
|
+
for (const [index, pkg] of packages.entries()) {
|
|
1338
|
+
const source = nodes[index].id;
|
|
1339
|
+
for (const type of graph.dependencyTypes) for (const [dependency, specifier] of Object.entries(pkg.manifest[type] ?? {}).sort(([a], [b]) => compareGraphValues(a, b))) {
|
|
1340
|
+
const result = resolveGraphDependency(pkg, source, dependency, specifier, type, packages, nodes);
|
|
1341
|
+
if (result.target && result.resolution) graph.edges.push({
|
|
1342
|
+
source,
|
|
1343
|
+
target: result.target,
|
|
1344
|
+
type,
|
|
1345
|
+
dependency,
|
|
1346
|
+
specifier,
|
|
1347
|
+
resolution: result.resolution
|
|
1348
|
+
});
|
|
1349
|
+
if (result.diagnostic) graph.diagnostics.push(result.diagnostic);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return filterWorkspaceGraph(graph, options);
|
|
1353
|
+
}
|
|
1354
|
+
//#endregion
|
|
1355
|
+
//#region src/core/operation-lock/index.ts
|
|
1356
|
+
/** Serialize validation, mutation, rollback and cleanup, including identical concurrent plans. */
|
|
1357
|
+
async function withOperationLock(root, name, run) {
|
|
1358
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new Error("Invalid operation lock name");
|
|
1359
|
+
const lockFile = `.repoctl/${name}.lock`;
|
|
1360
|
+
const filename = path.join(root, lockFile);
|
|
1361
|
+
const directory = path.join(root, ".repoctl");
|
|
1362
|
+
const validateDirectory = async () => {
|
|
1363
|
+
const stat = await lstat(directory);
|
|
1364
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || path.normalize(await realpath(directory)) !== directory) throw new Error(`Unsafe operation lock directory: ${directory}`);
|
|
1365
|
+
};
|
|
1366
|
+
let createdDirectory;
|
|
1367
|
+
try {
|
|
1368
|
+
await mkdir(directory);
|
|
1369
|
+
createdDirectory = await lstat(directory, { bigint: true });
|
|
1370
|
+
} catch (error) {
|
|
1371
|
+
if (error.code !== "EEXIST") throw error;
|
|
1372
|
+
}
|
|
1373
|
+
let handle;
|
|
1374
|
+
let identity;
|
|
1375
|
+
let written = false;
|
|
1376
|
+
const token = `${randomUUID()}\n`;
|
|
1377
|
+
const failures = [];
|
|
1378
|
+
let result;
|
|
1379
|
+
try {
|
|
1380
|
+
await validateDirectory();
|
|
1381
|
+
try {
|
|
1382
|
+
handle = await open(filename, "wx");
|
|
1383
|
+
} catch (error) {
|
|
1384
|
+
if (error.code === "EEXIST") throw new Error(`Operation ${name} is locked: ${lockFile}. After a crash, verify no writer is active and recover pending backups before removing this lock.`);
|
|
1385
|
+
throw error;
|
|
1386
|
+
}
|
|
1387
|
+
identity = await handle.stat({ bigint: true });
|
|
1388
|
+
await handle.writeFile(token);
|
|
1389
|
+
written = true;
|
|
1390
|
+
result = await run();
|
|
1391
|
+
} catch (error) {
|
|
1392
|
+
failures.push(error);
|
|
1393
|
+
}
|
|
1394
|
+
try {
|
|
1395
|
+
await handle?.close();
|
|
1396
|
+
if (identity) {
|
|
1397
|
+
await validateDirectory();
|
|
1398
|
+
const current = await lstat(filename, { bigint: true });
|
|
1399
|
+
if (!current.isFile() || current.isSymbolicLink() || current.nlink !== 1n || current.ino !== identity.ino || current.dev !== identity.dev || written && await readFile(filename, "utf8") !== token) throw new Error("Operation lock ownership changed");
|
|
1400
|
+
await unlink(filename);
|
|
1401
|
+
}
|
|
1402
|
+
} catch (error) {
|
|
1403
|
+
failures.push(new Error(`Operation lock cleanup needs attention; preserve ${lockFile}.`, { cause: error }));
|
|
1404
|
+
}
|
|
1405
|
+
if (createdDirectory) try {
|
|
1406
|
+
await validateDirectory();
|
|
1407
|
+
const current = await lstat(directory, { bigint: true });
|
|
1408
|
+
if (current.ino === createdDirectory.ino && current.dev === createdDirectory.dev) await rmdir(directory);
|
|
1409
|
+
} catch {}
|
|
1410
|
+
if (failures.length > 1) throw new AggregateError(failures, `Operation failed and lock cleanup needs attention; preserve ${lockFile}.`);
|
|
1411
|
+
if (failures.length) throw failures[0];
|
|
1412
|
+
return result;
|
|
1413
|
+
}
|
|
1414
|
+
//#endregion
|
|
1415
|
+
//#region src/core/merge-text/index.ts
|
|
1416
|
+
function decode(content) {
|
|
1417
|
+
if (content.includes(0)) return null;
|
|
1418
|
+
try {
|
|
1419
|
+
return new TextDecoder$1("utf-8", {
|
|
1420
|
+
fatal: true,
|
|
1421
|
+
ignoreBOM: true
|
|
1422
|
+
}).decode(content);
|
|
1423
|
+
} catch {
|
|
1424
|
+
return null;
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
/** Merge complete lines without normalizing the BOM, line endings or final newline. */
|
|
1428
|
+
function mergeText(base, local, upstream) {
|
|
1429
|
+
if (local.equals(upstream) || local.equals(base)) return {
|
|
1430
|
+
content: upstream,
|
|
1431
|
+
reason: "upstream-update",
|
|
1432
|
+
conflicts: []
|
|
1433
|
+
};
|
|
1434
|
+
if (upstream.equals(base)) return {
|
|
1435
|
+
content: local,
|
|
1436
|
+
reason: "local-changes-preserved",
|
|
1437
|
+
conflicts: []
|
|
1438
|
+
};
|
|
1439
|
+
if (base.length + local.length + upstream.length > 1048576) return {
|
|
1440
|
+
content: null,
|
|
1441
|
+
reason: "merge-size-limit",
|
|
1442
|
+
conflicts: []
|
|
1443
|
+
};
|
|
1444
|
+
const texts = [
|
|
1445
|
+
local,
|
|
1446
|
+
base,
|
|
1447
|
+
upstream
|
|
1448
|
+
].map(decode);
|
|
1449
|
+
if (texts.includes(null)) return {
|
|
1450
|
+
content: null,
|
|
1451
|
+
reason: "binary-merge-conflict",
|
|
1452
|
+
conflicts: []
|
|
1453
|
+
};
|
|
1454
|
+
const lines = texts.map((text) => [...text.match(/[^\n]*\n|[^\n]+$/g) ?? []]);
|
|
1455
|
+
const merged = [];
|
|
1456
|
+
const conflicts = [];
|
|
1457
|
+
for (const region of diff3Merge(lines[0], lines[1], lines[2])) if (region.ok) merged.push(...region.ok);
|
|
1458
|
+
else if (region.conflict) {
|
|
1459
|
+
const { o, oIndex, a, b } = region.conflict;
|
|
1460
|
+
conflicts.push({
|
|
1461
|
+
baseStart: oIndex + 1,
|
|
1462
|
+
baseEnd: oIndex + o.length,
|
|
1463
|
+
base: o.join(""),
|
|
1464
|
+
local: a.join(""),
|
|
1465
|
+
upstream: b.join("")
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
return {
|
|
1469
|
+
content: conflicts.length ? null : Buffer.from(merged.join("")),
|
|
1470
|
+
reason: conflicts.length ? "overlapping-merge-conflict" : "three-way-merge",
|
|
1471
|
+
conflicts
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
//#endregion
|
|
1475
|
+
//#region src/commands/check/cache/compare.ts
|
|
1476
|
+
function group(field) {
|
|
1477
|
+
if (field.startsWith("global.files.")) return "global.files";
|
|
1478
|
+
if (field.startsWith("global.environment.")) return "global.environment";
|
|
1479
|
+
if (field.startsWith("global.")) return "global.configuration";
|
|
1480
|
+
if (field.startsWith("inputs.")) return "inputs";
|
|
1481
|
+
if (field.startsWith("environment.")) return "environment";
|
|
1482
|
+
if (field.startsWith("dependencies.")) return "dependencies";
|
|
1483
|
+
return "configuration";
|
|
1484
|
+
}
|
|
1485
|
+
function compareEvidence(currentEvidence, previousEvidence, currentComplete, previousComplete) {
|
|
1486
|
+
const output = [];
|
|
1487
|
+
for (const field of [.../* @__PURE__ */ new Set([...currentEvidence.keys(), ...previousEvidence.keys()])].sort()) {
|
|
1488
|
+
const after = currentEvidence.get(field);
|
|
1489
|
+
const prior = previousEvidence.get(field);
|
|
1490
|
+
if (after?.digest === prior?.digest) continue;
|
|
1491
|
+
output.push({
|
|
1492
|
+
category: (after ?? prior).category,
|
|
1493
|
+
field,
|
|
1494
|
+
change: after && prior ? "changed" : !after && !currentComplete.has(group(field)) || !prior && !previousComplete.has(group(field)) ? "unknown" : after ? "added" : "removed",
|
|
1495
|
+
beforeDigest: prior?.digest ?? null,
|
|
1496
|
+
afterDigest: after?.digest ?? null
|
|
1497
|
+
});
|
|
1498
|
+
}
|
|
1499
|
+
return output;
|
|
1500
|
+
}
|
|
1501
|
+
function differences(current, previous) {
|
|
1502
|
+
const output = compareEvidence(current.evidence, previous.evidence, current.completeGroups, previous.completeGroups);
|
|
1503
|
+
if (current.hash !== previous.hash) output.push({
|
|
1504
|
+
category: "task-hash",
|
|
1505
|
+
field: "task.hash",
|
|
1506
|
+
change: current.hash && previous.hash ? "changed" : "unknown",
|
|
1507
|
+
beforeDigest: previous.hash,
|
|
1508
|
+
afterDigest: current.hash
|
|
1509
|
+
});
|
|
1510
|
+
return output;
|
|
1511
|
+
}
|
|
1512
|
+
function analyzeTask(id, now, before) {
|
|
1513
|
+
const current = now.tasks.get(id);
|
|
1514
|
+
const previous = before?.tasks.get(id);
|
|
1515
|
+
const supported = now.supported && (!before || before.supported);
|
|
1516
|
+
let comparison = before ? "unknown" : "not-requested";
|
|
1517
|
+
if (before && supported) comparison = !current ? now.ambiguous ? "unknown" : "removed" : !previous ? before.ambiguous ? "unknown" : "added" : current.hash && previous.hash ? current.hash === previous.hash ? "unchanged" : "changed" : "unknown";
|
|
1518
|
+
return {
|
|
1519
|
+
taskId: id,
|
|
1520
|
+
cache: current?.cache ?? "unknown",
|
|
1521
|
+
durationMs: current?.duration ?? null,
|
|
1522
|
+
exitCode: current?.exitCode ?? null,
|
|
1523
|
+
hashDigest: current?.hash ?? null,
|
|
1524
|
+
comparison,
|
|
1525
|
+
previousDurationMs: previous?.duration ?? null,
|
|
1526
|
+
durationDeltaMs: current?.duration != null && previous?.duration != null ? current.duration - previous.duration : null,
|
|
1527
|
+
evidence: before && current && previous && supported ? differences(current, previous) : []
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
//#endregion
|
|
1531
|
+
//#region src/commands/check/cache/critical-path.ts
|
|
1532
|
+
const unavailable = (reason) => ({
|
|
1533
|
+
available: false,
|
|
1534
|
+
reason,
|
|
1535
|
+
taskIds: [],
|
|
1536
|
+
durationMs: null,
|
|
1537
|
+
observedSpanMs: null
|
|
1538
|
+
});
|
|
1539
|
+
/** Longest measured dependency chain, not a claim about total wall-clock performance. */
|
|
1540
|
+
function criticalPath(summary) {
|
|
1541
|
+
if (!summary.supported) return unavailable("unsupported-schema");
|
|
1542
|
+
if (summary.ambiguous) return unavailable("ambiguous-tasks");
|
|
1543
|
+
const tasks = [...summary.tasks.values()].sort((a, b) => a.id.localeCompare(b.id));
|
|
1544
|
+
if (!tasks.length) return unavailable("no-tasks");
|
|
1545
|
+
if (tasks.some((task) => task.duration === null || task.start === null || task.end === null)) return unavailable("missing-timing");
|
|
1546
|
+
if (tasks.some((task) => !task.dependencies || task.dependencies.some((id) => !summary.tasks.has(id)))) return unavailable("missing-dependencies");
|
|
1547
|
+
const indegree = new Map(tasks.map((task) => [task.id, task.dependencies.length]));
|
|
1548
|
+
const children = new Map(tasks.map((task) => [task.id, []]));
|
|
1549
|
+
for (const task of tasks) for (const dependency of task.dependencies) children.get(dependency).push(task.id);
|
|
1550
|
+
const ready = tasks.filter((task) => !task.dependencies.length).map((task) => task.id);
|
|
1551
|
+
const distance = /* @__PURE__ */ new Map();
|
|
1552
|
+
const parent = /* @__PURE__ */ new Map();
|
|
1553
|
+
let visited = 0;
|
|
1554
|
+
let overlapping = false;
|
|
1555
|
+
for (let cursor = 0; cursor < ready.length; cursor++) {
|
|
1556
|
+
const id = ready[cursor];
|
|
1557
|
+
const task = summary.tasks.get(id);
|
|
1558
|
+
const total = (distance.get(id) ?? 0) + task.duration;
|
|
1559
|
+
if (!Number.isSafeInteger(total)) return unavailable("timing-overflow");
|
|
1560
|
+
distance.set(id, total);
|
|
1561
|
+
visited++;
|
|
1562
|
+
for (const child of children.get(id)) {
|
|
1563
|
+
if (task.end > summary.tasks.get(child).start) overlapping = true;
|
|
1564
|
+
if (total > (distance.get(child) ?? -1)) {
|
|
1565
|
+
distance.set(child, total);
|
|
1566
|
+
parent.set(child, id);
|
|
1567
|
+
}
|
|
1568
|
+
const count = indegree.get(child) - 1;
|
|
1569
|
+
indegree.set(child, count);
|
|
1570
|
+
if (!count) ready.push(child);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
if (visited !== tasks.length) return unavailable("dependency-cycle");
|
|
1574
|
+
if (overlapping) return unavailable("overlapping-dependency");
|
|
1575
|
+
const longest = tasks.reduce((best, task) => distance.get(task.id) > distance.get(best.id) ? task : best);
|
|
1576
|
+
const chain = [];
|
|
1577
|
+
for (let id = longest.id; id !== void 0; id = parent.get(id)) chain.push(id);
|
|
1578
|
+
return {
|
|
1579
|
+
available: true,
|
|
1580
|
+
reason: "complete",
|
|
1581
|
+
taskIds: chain.reverse(),
|
|
1582
|
+
durationMs: distance.get(longest.id),
|
|
1583
|
+
observedSpanMs: tasks.reduce((latest, task) => Math.max(latest, task.end), 0) - tasks.reduce((earliest, task) => Math.min(earliest, task.start), Infinity)
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
//#endregion
|
|
1587
|
+
//#region src/commands/check/cache/evidence.ts
|
|
1588
|
+
function record$1(value) {
|
|
1589
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1590
|
+
}
|
|
1591
|
+
function canonical(value, depth = 0) {
|
|
1592
|
+
if (depth > 64) throw new Error("Turbo summary evidence exceeds the supported nesting depth; input contents are omitted.");
|
|
1593
|
+
if (typeof value === "number" && !Number.isFinite(value)) throw new TypeError("Turbo summary evidence contains a non-finite number; input contents are omitted.");
|
|
1594
|
+
if (Array.isArray(value)) return value.map((item) => canonical(item, depth + 1));
|
|
1595
|
+
const object = record$1(value);
|
|
1596
|
+
return object ? Object.fromEntries(Object.keys(object).sort().map((key) => [key, canonical(object[key], depth + 1)])) : value;
|
|
1597
|
+
}
|
|
1598
|
+
function digest$1(value) {
|
|
1599
|
+
return createHash("sha256").update(JSON.stringify(canonical(value)) ?? "undefined").digest("hex");
|
|
1600
|
+
}
|
|
1601
|
+
function safeLabel(value) {
|
|
1602
|
+
return typeof value === "string" && value.length > 0 && value.length <= 1024 && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
1603
|
+
}
|
|
1604
|
+
function addEvidence(output, category, field, value) {
|
|
1605
|
+
output.set(field, {
|
|
1606
|
+
category,
|
|
1607
|
+
digest: digest$1(value)
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
function inputEvidence(output, prefix, value, category) {
|
|
1611
|
+
const inputs = record$1(value);
|
|
1612
|
+
if (!inputs) return false;
|
|
1613
|
+
let complete = true;
|
|
1614
|
+
for (const [filename, hash] of Object.entries(inputs)) {
|
|
1615
|
+
if (typeof hash !== "string" || !safeLabel(filename)) {
|
|
1616
|
+
complete = false;
|
|
1617
|
+
continue;
|
|
1618
|
+
}
|
|
1619
|
+
addEvidence(output, category, `${prefix}.${filename}`, hash);
|
|
1620
|
+
}
|
|
1621
|
+
return complete;
|
|
1622
|
+
}
|
|
1623
|
+
/** Native summaries may contain NAME=hash or NAME=value. Neither suffix is emitted. */
|
|
1624
|
+
function environmentEvidence(output, prefix, value) {
|
|
1625
|
+
const environment = record$1(value);
|
|
1626
|
+
const specified = record$1(environment?.["specified"]);
|
|
1627
|
+
if (!environment || !specified) return false;
|
|
1628
|
+
let complete = true;
|
|
1629
|
+
for (const key of ["env", "passThroughEnv"]) {
|
|
1630
|
+
const values = specified[key];
|
|
1631
|
+
if (key === "passThroughEnv" && values === null || Array.isArray(values) && values.every((item) => typeof item === "string" && /^!?[A-Z_][\w*]*$/iu.test(item))) addEvidence(output, "environment", `${prefix}.specified.${key}`, values === null ? [] : [...new Set(values)].sort());
|
|
1632
|
+
else complete = false;
|
|
1633
|
+
}
|
|
1634
|
+
for (const key of [
|
|
1635
|
+
"configured",
|
|
1636
|
+
"inferred",
|
|
1637
|
+
"passthrough"
|
|
1638
|
+
]) {
|
|
1639
|
+
const values = environment[key];
|
|
1640
|
+
if (key === "passthrough" && values === null) continue;
|
|
1641
|
+
if (!Array.isArray(values)) {
|
|
1642
|
+
complete = false;
|
|
1643
|
+
continue;
|
|
1644
|
+
}
|
|
1645
|
+
const names = /* @__PURE__ */ new Set();
|
|
1646
|
+
for (const entry of values) {
|
|
1647
|
+
const separator = typeof entry === "string" ? entry.indexOf("=") : -1;
|
|
1648
|
+
const name = separator > 0 ? entry.slice(0, separator) : "";
|
|
1649
|
+
if (!/^[A-Z_]\w*$/iu.test(name) || names.has(name)) {
|
|
1650
|
+
complete = false;
|
|
1651
|
+
continue;
|
|
1652
|
+
}
|
|
1653
|
+
names.add(name);
|
|
1654
|
+
addEvidence(output, "environment", `${prefix}.${key}.${name}`, entry.slice(separator + 1));
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
return complete;
|
|
1658
|
+
}
|
|
1659
|
+
function configurationEvidence(output, task) {
|
|
1660
|
+
const definition = record$1(task["resolvedTaskDefinition"]) ?? {};
|
|
1661
|
+
let complete = true;
|
|
1662
|
+
for (const key of [
|
|
1663
|
+
"outputs",
|
|
1664
|
+
"cache",
|
|
1665
|
+
"dependsOn",
|
|
1666
|
+
"inputs",
|
|
1667
|
+
"outputLogs",
|
|
1668
|
+
"persistent",
|
|
1669
|
+
"interruptible",
|
|
1670
|
+
"env",
|
|
1671
|
+
"passThroughEnv",
|
|
1672
|
+
"interactive"
|
|
1673
|
+
]) if (Object.hasOwn(definition, key)) addEvidence(output, "configuration", `definition.${key}`, definition[key]);
|
|
1674
|
+
else complete = false;
|
|
1675
|
+
for (const key of [
|
|
1676
|
+
"command",
|
|
1677
|
+
"cliArguments",
|
|
1678
|
+
"envMode",
|
|
1679
|
+
"framework",
|
|
1680
|
+
"outputs",
|
|
1681
|
+
"excludedOutputs",
|
|
1682
|
+
"hashOfExternalDependencies"
|
|
1683
|
+
]) if (Object.hasOwn(task, key)) addEvidence(output, "configuration", `task.${key}`, task[key]);
|
|
1684
|
+
else complete = false;
|
|
1685
|
+
return complete;
|
|
1686
|
+
}
|
|
1687
|
+
//#endregion
|
|
1688
|
+
//#region src/commands/check/cache/parse.ts
|
|
1689
|
+
const finite = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
1690
|
+
function parseTask(task, id) {
|
|
1691
|
+
const execution = record$1(task["execution"]);
|
|
1692
|
+
const start = finite(execution?.["startTime"]);
|
|
1693
|
+
const end = finite(execution?.["endTime"]);
|
|
1694
|
+
const cache = record$1(task["cache"]);
|
|
1695
|
+
const dependencies = task["dependencies"];
|
|
1696
|
+
const evidence = /* @__PURE__ */ new Map();
|
|
1697
|
+
const completeGroups = /* @__PURE__ */ new Set();
|
|
1698
|
+
if (inputEvidence(evidence, "inputs", task["inputs"], "input")) completeGroups.add("inputs");
|
|
1699
|
+
if (environmentEvidence(evidence, "environment", task["environmentVariables"])) completeGroups.add("environment");
|
|
1700
|
+
if (configurationEvidence(evidence, task)) completeGroups.add("configuration");
|
|
1701
|
+
return {
|
|
1702
|
+
id,
|
|
1703
|
+
cache: cache?.["status"] === "HIT" ? "hit" : cache?.["status"] === "MISS" ? "miss" : "unknown",
|
|
1704
|
+
start,
|
|
1705
|
+
end,
|
|
1706
|
+
duration: start !== null && end !== null && end >= start ? end - start : null,
|
|
1707
|
+
exitCode: typeof execution?.["exitCode"] === "number" && Number.isInteger(execution["exitCode"]) ? execution["exitCode"] : null,
|
|
1708
|
+
hash: typeof task["hash"] === "string" && task["hash"] ? digest$1(task["hash"]) : null,
|
|
1709
|
+
dependencies: Array.isArray(dependencies) && dependencies.every(safeLabel) ? [...new Set(dependencies)].sort() : null,
|
|
1710
|
+
evidence,
|
|
1711
|
+
completeGroups
|
|
1712
|
+
};
|
|
1713
|
+
}
|
|
1714
|
+
function globalEvidence(value, result) {
|
|
1715
|
+
const global = record$1(value);
|
|
1716
|
+
if (!global) return;
|
|
1717
|
+
if (inputEvidence(result.globalEvidence, "global.files", global["files"], "global-input")) result.completeGroups.add("global.files");
|
|
1718
|
+
if (environmentEvidence(result.globalEvidence, "global.environment", global["environmentVariables"])) result.completeGroups.add("global.environment");
|
|
1719
|
+
let complete = true;
|
|
1720
|
+
for (const key of [
|
|
1721
|
+
"rootKey",
|
|
1722
|
+
"hashOfExternalDependencies",
|
|
1723
|
+
"hashOfInternalDependencies",
|
|
1724
|
+
"engines"
|
|
1725
|
+
]) if (Object.hasOwn(global, key)) addEvidence(result.globalEvidence, "global-input", `global.${key}`, global[key]);
|
|
1726
|
+
else complete = false;
|
|
1727
|
+
if (complete) result.completeGroups.add("global.configuration");
|
|
1728
|
+
}
|
|
1729
|
+
async function readTurboSummary(filename, summary) {
|
|
1730
|
+
let root;
|
|
1731
|
+
try {
|
|
1732
|
+
const metadata = await stat(filename);
|
|
1733
|
+
if (!metadata.isFile() || metadata.size > 20971520) throw new Error("Unsupported file size or type");
|
|
1734
|
+
const contents = await readFile(filename, "utf8");
|
|
1735
|
+
if (Buffer.byteLength(contents) > 20971520) throw new Error("Summary changed size");
|
|
1736
|
+
root = record$1(JSON.parse(contents));
|
|
1737
|
+
} catch {
|
|
1738
|
+
throw new Error(`Cannot read ${summary} Turbo summary as a JSON object of at most 20 MiB; input contents are omitted.`);
|
|
1739
|
+
}
|
|
1740
|
+
if (!root) throw new Error(`The ${summary} Turbo summary must be a JSON object.`);
|
|
1741
|
+
const limitations = [];
|
|
1742
|
+
const result = {
|
|
1743
|
+
supported: root["version"] === "1" || root["version"] === 1,
|
|
1744
|
+
turboVersion: typeof root["turboVersion"] === "string" && /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/u.test(root["turboVersion"]) ? root["turboVersion"] : null,
|
|
1745
|
+
tasks: /* @__PURE__ */ new Map(),
|
|
1746
|
+
ambiguous: false,
|
|
1747
|
+
globalEvidence: /* @__PURE__ */ new Map(),
|
|
1748
|
+
completeGroups: /* @__PURE__ */ new Set(),
|
|
1749
|
+
limitations
|
|
1750
|
+
};
|
|
1751
|
+
if (!result.supported) limitations.push({
|
|
1752
|
+
code: "unsupported_schema",
|
|
1753
|
+
summary
|
|
1754
|
+
});
|
|
1755
|
+
if (!Array.isArray(root["tasks"])) {
|
|
1756
|
+
limitations.push({
|
|
1757
|
+
code: "missing_tasks",
|
|
1758
|
+
summary
|
|
1759
|
+
});
|
|
1760
|
+
result.ambiguous = true;
|
|
1761
|
+
return result;
|
|
1762
|
+
}
|
|
1763
|
+
const duplicates = /* @__PURE__ */ new Set();
|
|
1764
|
+
for (const value of root["tasks"]) {
|
|
1765
|
+
const task = record$1(value);
|
|
1766
|
+
const id = task?.["taskId"];
|
|
1767
|
+
if (!task || !safeLabel(id)) {
|
|
1768
|
+
limitations.push({
|
|
1769
|
+
code: "missing_task_identity",
|
|
1770
|
+
summary
|
|
1771
|
+
});
|
|
1772
|
+
result.ambiguous = true;
|
|
1773
|
+
continue;
|
|
1774
|
+
}
|
|
1775
|
+
if (result.tasks.has(id) || duplicates.has(id)) {
|
|
1776
|
+
result.tasks.delete(id);
|
|
1777
|
+
duplicates.add(id);
|
|
1778
|
+
result.ambiguous = true;
|
|
1779
|
+
continue;
|
|
1780
|
+
}
|
|
1781
|
+
const parsed = parseTask(task, id);
|
|
1782
|
+
if (parsed.duration === null) limitations.push({
|
|
1783
|
+
code: "missing_task_timing",
|
|
1784
|
+
summary,
|
|
1785
|
+
taskId: id
|
|
1786
|
+
});
|
|
1787
|
+
result.tasks.set(id, parsed);
|
|
1788
|
+
}
|
|
1789
|
+
for (const id of [...duplicates].sort()) limitations.push({
|
|
1790
|
+
code: "duplicate_task_identity",
|
|
1791
|
+
summary,
|
|
1792
|
+
taskId: id
|
|
1793
|
+
});
|
|
1794
|
+
globalEvidence(root["globalCacheInputs"], result);
|
|
1795
|
+
for (const task of result.tasks.values()) {
|
|
1796
|
+
if (task.dependencies === null) {
|
|
1797
|
+
limitations.push({
|
|
1798
|
+
code: "missing_task_dependencies",
|
|
1799
|
+
summary,
|
|
1800
|
+
taskId: task.id
|
|
1801
|
+
});
|
|
1802
|
+
continue;
|
|
1803
|
+
}
|
|
1804
|
+
addEvidence(task.evidence, "dependency", "dependencies.members", task.dependencies);
|
|
1805
|
+
let complete = true;
|
|
1806
|
+
for (const dependency of task.dependencies) {
|
|
1807
|
+
const hash = result.tasks.get(dependency)?.hash;
|
|
1808
|
+
if (hash === null || hash === void 0) complete = false;
|
|
1809
|
+
else addEvidence(task.evidence, "dependency", `dependencies.hash.${dependency}`, hash);
|
|
1810
|
+
}
|
|
1811
|
+
if (complete) task.completeGroups.add("dependencies");
|
|
1812
|
+
else limitations.push({
|
|
1813
|
+
code: "missing_dependency_hash",
|
|
1814
|
+
summary,
|
|
1815
|
+
taskId: task.id
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
for (const field of [
|
|
1819
|
+
"global.files",
|
|
1820
|
+
"global.environment",
|
|
1821
|
+
"global.configuration"
|
|
1822
|
+
]) if (!result.completeGroups.has(field)) limitations.push({
|
|
1823
|
+
code: "incomplete_hash_evidence",
|
|
1824
|
+
summary,
|
|
1825
|
+
field
|
|
1826
|
+
});
|
|
1827
|
+
for (const task of result.tasks.values()) for (const field of [
|
|
1828
|
+
"inputs",
|
|
1829
|
+
"environment",
|
|
1830
|
+
"configuration",
|
|
1831
|
+
"dependencies"
|
|
1832
|
+
]) if (!task.completeGroups.has(field)) limitations.push({
|
|
1833
|
+
code: "incomplete_hash_evidence",
|
|
1834
|
+
summary,
|
|
1835
|
+
taskId: task.id,
|
|
1836
|
+
field
|
|
1837
|
+
});
|
|
1838
|
+
return result;
|
|
1839
|
+
}
|
|
1840
|
+
//#endregion
|
|
1841
|
+
//#region src/commands/check/cache/index.ts
|
|
1842
|
+
var cache_exports = /* @__PURE__ */ __exportAll({ analyzeTurboRuns: () => analyzeTurboRuns });
|
|
1843
|
+
/** Analyze existing evidence only. Never invoke Turbo, package scripts, or cache mutation. */
|
|
1844
|
+
async function analyzeTurboRuns(current, options = {}) {
|
|
1845
|
+
const slowest = options.slowest ?? 10;
|
|
1846
|
+
if (!Number.isInteger(slowest) || slowest < 1 || slowest > 100) throw new Error("Slow task count must be an integer from 1 to 100.");
|
|
1847
|
+
const now = await readTurboSummary(current, "current");
|
|
1848
|
+
const before = options.previous === void 0 ? void 0 : await readTurboSummary(options.previous, "previous");
|
|
1849
|
+
const ids = [.../* @__PURE__ */ new Set([...now.tasks.keys(), ...before?.tasks.keys() ?? []])].sort();
|
|
1850
|
+
const globalEvidence = before && now.supported && before.supported ? compareEvidence(now.globalEvidence, before.globalEvidence, now.completeGroups, before.completeGroups) : [];
|
|
1851
|
+
const globalChanged = globalEvidence.some((item) => item.change !== "unknown");
|
|
1852
|
+
const tasks = ids.map((id) => analyzeTask(id, now, before));
|
|
1853
|
+
const currentTasks = [...now.tasks.values()];
|
|
1854
|
+
const hits = currentTasks.filter((task) => task.cache === "hit").length;
|
|
1855
|
+
const misses = currentTasks.filter((task) => task.cache === "miss").length;
|
|
1856
|
+
const limitations = [...now.limitations, ...before?.limitations ?? []];
|
|
1857
|
+
for (const task of tasks) {
|
|
1858
|
+
if (task.cache === "miss" && task.comparison === "unchanged") limitations.push({
|
|
1859
|
+
code: "cache_miss_with_unchanged_hash",
|
|
1860
|
+
summary: "current",
|
|
1861
|
+
taskId: task.taskId
|
|
1862
|
+
});
|
|
1863
|
+
if (task.comparison === "changed" && !globalChanged && !task.evidence.some((item) => item.category !== "task-hash" && item.change !== "unknown")) limitations.push({
|
|
1864
|
+
code: "hash_changed_without_explanation",
|
|
1865
|
+
summary: "current",
|
|
1866
|
+
taskId: task.taskId
|
|
1867
|
+
});
|
|
1868
|
+
}
|
|
1869
|
+
return {
|
|
1870
|
+
schemaVersion: 1,
|
|
1871
|
+
kind: "turbo-cache-analysis",
|
|
1872
|
+
current: {
|
|
1873
|
+
supportedSchema: now.supported,
|
|
1874
|
+
turboVersion: now.turboVersion
|
|
1875
|
+
},
|
|
1876
|
+
previous: before ? {
|
|
1877
|
+
supportedSchema: before.supported,
|
|
1878
|
+
turboVersion: before.turboVersion
|
|
1879
|
+
} : null,
|
|
1880
|
+
totals: {
|
|
1881
|
+
tasks: currentTasks.length,
|
|
1882
|
+
hits,
|
|
1883
|
+
misses,
|
|
1884
|
+
unknownCache: currentTasks.length - hits - misses,
|
|
1885
|
+
hitRate: hits + misses ? hits / (hits + misses) : null
|
|
1886
|
+
},
|
|
1887
|
+
tasks,
|
|
1888
|
+
globalEvidence,
|
|
1889
|
+
slowest: currentTasks.filter((task) => task.duration !== null).map((task) => ({
|
|
1890
|
+
taskId: task.id,
|
|
1891
|
+
durationMs: task.duration
|
|
1892
|
+
})).sort((a, b) => b.durationMs - a.durationMs || a.taskId.localeCompare(b.taskId)).slice(0, slowest),
|
|
1893
|
+
criticalPath: criticalPath(now),
|
|
1894
|
+
limitations
|
|
1895
|
+
};
|
|
1896
|
+
}
|
|
1897
|
+
//#endregion
|
|
1898
|
+
//#region src/commands/check/process.ts
|
|
1899
|
+
function signalExitCode(signal) {
|
|
1900
|
+
return 128 + (constants$1.signals[signal] ?? 1);
|
|
1901
|
+
}
|
|
1902
|
+
function abortSignal(signal) {
|
|
1903
|
+
return signal.reason === "SIGTERM" ? "SIGTERM" : "SIGINT";
|
|
1904
|
+
}
|
|
1905
|
+
function stopCheckProcessTree(child, signal) {
|
|
1906
|
+
if (!child.pid) return;
|
|
1907
|
+
if (process.platform === "win32") {
|
|
1908
|
+
spawnSync("taskkill", [
|
|
1909
|
+
"/pid",
|
|
1910
|
+
String(child.pid),
|
|
1911
|
+
"/T",
|
|
1912
|
+
"/F"
|
|
1913
|
+
], { stdio: "ignore" });
|
|
1914
|
+
return;
|
|
1915
|
+
}
|
|
1916
|
+
try {
|
|
1917
|
+
process.kill(-child.pid, signal);
|
|
1918
|
+
} catch (error) {
|
|
1919
|
+
if (error.code !== "ESRCH") child.kill(signal);
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
async function executeCheckTask(task, signal) {
|
|
1923
|
+
const start = performance.now();
|
|
1924
|
+
task.startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1925
|
+
process.stdout.write(`[check:${task.name}] .\n`);
|
|
1926
|
+
await new Promise((resolve) => {
|
|
1927
|
+
let child;
|
|
1928
|
+
let timer;
|
|
1929
|
+
let interrupted;
|
|
1930
|
+
let settled = false;
|
|
1931
|
+
const abort = () => {
|
|
1932
|
+
interrupted = abortSignal(signal);
|
|
1933
|
+
if (child) {
|
|
1934
|
+
stopCheckProcessTree(child, interrupted);
|
|
1935
|
+
timer = setTimeout(() => child && stopCheckProcessTree(child, "SIGKILL"), 3e3);
|
|
1936
|
+
timer.unref();
|
|
1937
|
+
}
|
|
1938
|
+
};
|
|
1939
|
+
const finish = (code, childSignal, error) => {
|
|
1940
|
+
if (settled) return;
|
|
1941
|
+
settled = true;
|
|
1942
|
+
signal?.removeEventListener("abort", abort);
|
|
1943
|
+
if (timer) clearTimeout(timer);
|
|
1944
|
+
if (interrupted && child) stopCheckProcessTree(child, "SIGKILL");
|
|
1945
|
+
task.endedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1946
|
+
task.durationMs = Math.max(0, performance.now() - start);
|
|
1947
|
+
task.signal = interrupted ?? childSignal;
|
|
1948
|
+
task.exitCode = code;
|
|
1949
|
+
task.status = task.signal ? "interrupted" : error || code !== 0 ? "failed" : "success";
|
|
1950
|
+
if (error) {
|
|
1951
|
+
task.errorCode = error.code ?? "SPAWN_ERROR";
|
|
1952
|
+
task.reason = "command_start_failed";
|
|
1953
|
+
}
|
|
1954
|
+
resolve();
|
|
1955
|
+
};
|
|
1956
|
+
try {
|
|
1957
|
+
child = crossSpawn(task.executable, task.args, {
|
|
1958
|
+
cwd: task.cwd,
|
|
1959
|
+
stdio: "inherit",
|
|
1960
|
+
detached: process.platform !== "win32"
|
|
1961
|
+
});
|
|
1962
|
+
child.once("error", (error) => finish(null, null, error));
|
|
1963
|
+
child.once("close", (code, childSignal) => finish(code, childSignal));
|
|
1964
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1965
|
+
if (signal?.aborted) abort();
|
|
1966
|
+
} catch (error) {
|
|
1967
|
+
finish(null, null, error);
|
|
1968
|
+
}
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1971
|
+
//#endregion
|
|
1972
|
+
//#region src/commands/check/knip/index.ts
|
|
1973
|
+
var knip_exports = /* @__PURE__ */ __exportAll({
|
|
1974
|
+
getKnipConfigurationSuggestions: () => getKnipConfigurationSuggestions,
|
|
1975
|
+
planKnipCheck: () => planKnipCheck,
|
|
1976
|
+
runKnipCheck: () => runKnipCheck,
|
|
1977
|
+
saveKnipBaseline: () => saveKnipBaseline
|
|
1978
|
+
});
|
|
1979
|
+
async function planKnipCheck(cwd, options = {}) {
|
|
1980
|
+
return (await import("./plan-CxySMaLN.mjs")).planKnipCheck(cwd, options);
|
|
1981
|
+
}
|
|
1982
|
+
async function runKnipCheck(cwd, options = {}) {
|
|
1983
|
+
return (await import("./run-D_bceMqf.mjs")).runKnipCheck(cwd, options);
|
|
1984
|
+
}
|
|
1985
|
+
async function getKnipConfigurationSuggestions(cwd) {
|
|
1986
|
+
return (await import("./config-Dg-voj8q.mjs")).getKnipConfigurationSuggestions(cwd);
|
|
1987
|
+
}
|
|
1988
|
+
async function saveKnipBaseline(cwd, report, file) {
|
|
1989
|
+
return (await import("./save-DzIWKs0T.mjs")).saveKnipBaseline(cwd, report, file);
|
|
1990
|
+
}
|
|
1991
|
+
//#endregion
|
|
1992
|
+
//#region src/commands/env-cache/config.ts
|
|
1993
|
+
const arrays = [
|
|
1994
|
+
"env",
|
|
1995
|
+
"passThroughEnv",
|
|
1996
|
+
"inputs"
|
|
1997
|
+
];
|
|
1998
|
+
const object$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1999
|
+
function strings(value) {
|
|
2000
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0 && item.length <= 1024 && !/[\p{Cc}\p{Cf}]/u.test(item));
|
|
2001
|
+
}
|
|
2002
|
+
async function readConfiguration(root, directory) {
|
|
2003
|
+
const candidates = [];
|
|
2004
|
+
for (const name of ["turbo.json", "turbo.jsonc"]) try {
|
|
2005
|
+
const metadata = await lstat(path.join(directory, name));
|
|
2006
|
+
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 1048576) throw new Error("Unsafe or oversized Turbo configuration");
|
|
2007
|
+
candidates.push(name);
|
|
2008
|
+
} catch (error) {
|
|
2009
|
+
if (error.code !== "ENOENT") throw error;
|
|
2010
|
+
}
|
|
2011
|
+
if (!candidates.length) return null;
|
|
2012
|
+
if (candidates.length > 1) throw new Error("Both turbo.json and turbo.jsonc exist");
|
|
2013
|
+
const filename = path.relative(root, path.join(directory, candidates[0]));
|
|
2014
|
+
let value;
|
|
2015
|
+
try {
|
|
2016
|
+
value = parse$1(await readFile(path.join(root, filename), "utf8"));
|
|
2017
|
+
} catch {
|
|
2018
|
+
throw new Error("Cannot parse Turbo configuration; contents omitted");
|
|
2019
|
+
}
|
|
2020
|
+
if (!object$1(value) || value["global"] !== void 0 || object$1(value["futureFlags"]) && value["futureFlags"]["globalConfiguration"] === true || value["pipeline"] !== void 0 || value["tasks"] !== void 0 && !object$1(value["tasks"])) throw new Error("Invalid Turbo configuration shape");
|
|
2021
|
+
if (directory !== root && [
|
|
2022
|
+
"globalEnv",
|
|
2023
|
+
"globalPassThroughEnv",
|
|
2024
|
+
"globalDependencies"
|
|
2025
|
+
].some((field) => Object.hasOwn(value, field))) throw new Error("Global Turbo declarations belong in the root configuration");
|
|
2026
|
+
const readArray = (data, field, context) => {
|
|
2027
|
+
const items = data[field] ?? [];
|
|
2028
|
+
if (!strings(items) || field.toLowerCase().includes("env") && items.some((item) => item !== "$TURBO_EXTENDS$" && !/^[\w!*\\]+$/.test(item))) throw new Error("Invalid Turbo array declaration; contents omitted");
|
|
2029
|
+
if (items.includes("$TURBO_EXTENDS$") && (items[0] !== "$TURBO_EXTENDS$" || directory === root)) throw new Error("Invalid Turbo inheritance marker");
|
|
2030
|
+
return items.map((pattern) => ({
|
|
2031
|
+
pattern,
|
|
2032
|
+
path: filename,
|
|
2033
|
+
field: `${context}${field}`
|
|
2034
|
+
}));
|
|
2035
|
+
};
|
|
2036
|
+
const tasks = /* @__PURE__ */ new Map();
|
|
2037
|
+
for (const [name, task] of Object.entries(value["tasks"] ?? {})) {
|
|
2038
|
+
if (!object$1(task) || task["cache"] !== void 0 && typeof task["cache"] !== "boolean" || task["extends"] !== void 0 && (directory === root || typeof task["extends"] !== "boolean")) throw new Error("Invalid Turbo task declaration");
|
|
2039
|
+
const definition = {};
|
|
2040
|
+
for (const field of arrays) if (Object.hasOwn(task, field)) definition[field] = readArray(task, field, `tasks.${name}.`);
|
|
2041
|
+
if (task["cache"] !== void 0) definition.cache = task["cache"];
|
|
2042
|
+
if (task["extends"] !== void 0) definition.extends = task["extends"];
|
|
2043
|
+
tasks.set(name, definition);
|
|
2044
|
+
}
|
|
2045
|
+
const inherited = value["extends"] ?? [];
|
|
2046
|
+
if (!strings(inherited) || directory !== root && inherited[0] !== "//") throw new Error("Package Turbo configuration must extend // first");
|
|
2047
|
+
return {
|
|
2048
|
+
filename,
|
|
2049
|
+
extends: inherited,
|
|
2050
|
+
tasks,
|
|
2051
|
+
globalEnv: readArray(value, "globalEnv", ""),
|
|
2052
|
+
globalPassThroughEnv: readArray(value, "globalPassThroughEnv", ""),
|
|
2053
|
+
globalDependencies: readArray(value, "globalDependencies", "")
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
function merge(base, next) {
|
|
2057
|
+
const result = next.extends === false ? { enabled: Object.keys(next).some((key) => key !== "extends") } : { ...base };
|
|
2058
|
+
for (const key of arrays) {
|
|
2059
|
+
const items = next[key];
|
|
2060
|
+
if (items !== void 0) result[key] = items[0]?.pattern === "$TURBO_EXTENDS$" ? [...result[key] ?? [], ...items.slice(1)] : items;
|
|
2061
|
+
}
|
|
2062
|
+
if (next.cache !== void 0) result.cache = next.cache;
|
|
2063
|
+
return result;
|
|
2064
|
+
}
|
|
2065
|
+
async function loadTurboConfigurations(root, packages) {
|
|
2066
|
+
const rootConfig = await readConfiguration(root, root);
|
|
2067
|
+
if (!rootConfig) throw new Error("Root Turbo configuration is missing");
|
|
2068
|
+
const configurations = /* @__PURE__ */ new Map();
|
|
2069
|
+
for (const pkg of packages) if (pkg.directory !== root) {
|
|
2070
|
+
if (configurations.has(pkg.name)) throw new Error("Duplicate workspace package names prevent configuration resolution");
|
|
2071
|
+
configurations.set(pkg.name, await readConfiguration(root, pkg.directory));
|
|
2072
|
+
}
|
|
2073
|
+
function layers(name, task, visiting = []) {
|
|
2074
|
+
if (visiting.includes(name)) throw new Error("Turbo package configuration inheritance cycle");
|
|
2075
|
+
const config = configurations.get(name);
|
|
2076
|
+
const result = [];
|
|
2077
|
+
if (config) {
|
|
2078
|
+
for (const parent of config.extends.filter((item) => item !== "//")) {
|
|
2079
|
+
if (!configurations.has(parent) || !configurations.get(parent)) throw new Error("Unknown inherited Turbo package configuration");
|
|
2080
|
+
result.push(...layers(parent, task, [...visiting, name]));
|
|
2081
|
+
}
|
|
2082
|
+
if (config.tasks.has(task)) result.push(config.tasks.get(task));
|
|
2083
|
+
}
|
|
2084
|
+
return result;
|
|
2085
|
+
}
|
|
2086
|
+
return (name, task) => {
|
|
2087
|
+
const base = rootConfig.tasks.get(`${name}#${task}`) ?? (name === "//" ? void 0 : rootConfig.tasks.get(task));
|
|
2088
|
+
const inherited = layers(name, task);
|
|
2089
|
+
const current = inherited.reduce(merge, base ?? {});
|
|
2090
|
+
return {
|
|
2091
|
+
enabled: current.enabled ?? (base !== void 0 || inherited.length > 0),
|
|
2092
|
+
env: current.env ?? [],
|
|
2093
|
+
passThroughEnv: current.passThroughEnv ?? [],
|
|
2094
|
+
inputs: current.inputs,
|
|
2095
|
+
cache: current.cache ?? true,
|
|
2096
|
+
globalEnv: rootConfig.globalEnv,
|
|
2097
|
+
globalPassThroughEnv: rootConfig.globalPassThroughEnv,
|
|
2098
|
+
globalDependencies: rootConfig.globalDependencies
|
|
2099
|
+
};
|
|
2100
|
+
};
|
|
2101
|
+
}
|
|
2102
|
+
//#endregion
|
|
2103
|
+
//#region src/commands/env-cache/patterns.ts
|
|
2104
|
+
function envRegex(pattern) {
|
|
2105
|
+
let expression = "";
|
|
2106
|
+
let wildcard = false;
|
|
2107
|
+
const value = pattern.startsWith("\\!") ? pattern.slice(1) : pattern;
|
|
2108
|
+
for (let index = 0; index < value.length; index++) {
|
|
2109
|
+
const char = value[index];
|
|
2110
|
+
if (char === "*" && value[index - 1] !== "\\") {
|
|
2111
|
+
if (!wildcard) expression += ".*";
|
|
2112
|
+
wildcard = true;
|
|
2113
|
+
} else {
|
|
2114
|
+
if (char === "*" && value[index - 1] === "\\") expression = expression.slice(0, -2);
|
|
2115
|
+
expression += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2116
|
+
wildcard = false;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
return new RegExp(`^${expression}$`, process.platform === "win32" ? "iu" : "u");
|
|
2120
|
+
}
|
|
2121
|
+
function envExcluded(name, declarations) {
|
|
2122
|
+
return declarations.some((item) => item.pattern.startsWith("!") && envRegex(item.pattern.slice(1)).test(name));
|
|
2123
|
+
}
|
|
2124
|
+
function envMatches(name, declarations) {
|
|
2125
|
+
return envExcluded(name, declarations) ? [] : declarations.filter((item) => !item.pattern.startsWith("!") && envRegex(item.pattern).test(name));
|
|
2126
|
+
}
|
|
2127
|
+
function matchesFile(filename, patterns) {
|
|
2128
|
+
return micromatch([filename], patterns, { dot: true }).length > 0;
|
|
2129
|
+
}
|
|
2130
|
+
function negativeFileMatch(filename, patterns) {
|
|
2131
|
+
return patterns.some((pattern) => pattern.startsWith("!") && matchesFile(filename, [pattern.slice(1)]));
|
|
2132
|
+
}
|
|
2133
|
+
//#endregion
|
|
2134
|
+
//#region src/commands/env-cache/scan.ts
|
|
2135
|
+
const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
2136
|
+
const variableName = (name) => typeof name === "string" && /^[A-Z_]\w*$/iu.test(name);
|
|
2137
|
+
function property(node) {
|
|
2138
|
+
const value = record(node["property"]);
|
|
2139
|
+
if (node["computed"] !== true && value?.["type"] === "Identifier") return String(value["name"]);
|
|
2140
|
+
return value?.["type"] === "StringLiteral" ? String(value["value"]) : void 0;
|
|
2141
|
+
}
|
|
2142
|
+
function envObject(value) {
|
|
2143
|
+
const node = record(value);
|
|
2144
|
+
if (!node || !["MemberExpression", "OptionalMemberExpression"].includes(String(node["type"])) || property(node) !== "env") return;
|
|
2145
|
+
const object = record(node["object"]);
|
|
2146
|
+
if (object?.["type"] === "Identifier" && object["name"] === "process") return "process-env";
|
|
2147
|
+
if (object?.["type"] === "MetaProperty" && record(object["meta"])?.["name"] === "import" && record(object["property"])?.["name"] === "meta") return "import-meta-env";
|
|
2148
|
+
}
|
|
2149
|
+
function add(result, name, evidence) {
|
|
2150
|
+
if (variableName(name)) {
|
|
2151
|
+
const items = result.variables.get(name) ?? [];
|
|
2152
|
+
if (!items.some((item) => item.path === evidence.path && item.line === evidence.line && item.column === evidence.column)) items.push(evidence);
|
|
2153
|
+
result.variables.set(name, items);
|
|
2154
|
+
} else result.dynamic.push({
|
|
2155
|
+
...evidence,
|
|
2156
|
+
kind: "dynamic"
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
2159
|
+
/** AST diagnostics never include expressions, string contents or parser error messages. */
|
|
2160
|
+
function scanSource(filename, source) {
|
|
2161
|
+
const result = {
|
|
2162
|
+
variables: /* @__PURE__ */ new Map(),
|
|
2163
|
+
dynamic: [],
|
|
2164
|
+
parseErrors: []
|
|
2165
|
+
};
|
|
2166
|
+
const parts = filename.endsWith(".vue") || filename.endsWith(".svelte") ? [...source.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script\s*>/gi)].map((match) => ({
|
|
2167
|
+
text: match[1],
|
|
2168
|
+
offset: source.slice(0, match.index + match[0].indexOf(">") + 1).split("\n").length - 1
|
|
2169
|
+
})) : [{
|
|
2170
|
+
text: source,
|
|
2171
|
+
offset: 0
|
|
2172
|
+
}];
|
|
2173
|
+
for (const part of parts) {
|
|
2174
|
+
let ast;
|
|
2175
|
+
try {
|
|
2176
|
+
ast = parse$2(part.text, {
|
|
2177
|
+
sourceType: "unambiguous",
|
|
2178
|
+
plugins: /\.[cm]?ts$/.test(filename) ? ["typescript"] : ["typescript", "jsx"],
|
|
2179
|
+
allowAwaitOutsideFunction: true,
|
|
2180
|
+
allowReturnOutsideFunction: true
|
|
2181
|
+
});
|
|
2182
|
+
} catch {
|
|
2183
|
+
result.parseErrors.push(part.offset + 1);
|
|
2184
|
+
continue;
|
|
2185
|
+
}
|
|
2186
|
+
function visit(value, parent) {
|
|
2187
|
+
if (Array.isArray(value)) {
|
|
2188
|
+
value.forEach((item) => visit(item, parent));
|
|
2189
|
+
return;
|
|
2190
|
+
}
|
|
2191
|
+
const node = record(value);
|
|
2192
|
+
if (!node || typeof node["type"] !== "string") return;
|
|
2193
|
+
const start = record(record(node["loc"])?.["start"]);
|
|
2194
|
+
const evidence = (kind) => ({
|
|
2195
|
+
path: filename,
|
|
2196
|
+
line: Number(start?.["line"] ?? 1) + part.offset,
|
|
2197
|
+
column: Number(start?.["column"] ?? 0) + 1,
|
|
2198
|
+
kind
|
|
2199
|
+
});
|
|
2200
|
+
const kind = envObject(node["object"]);
|
|
2201
|
+
if (kind && ["MemberExpression", "OptionalMemberExpression"].includes(node["type"])) add(result, property(node), evidence(kind));
|
|
2202
|
+
else if (node["type"] === "VariableDeclarator" && envObject(node["init"]) && record(node["id"])?.["type"] === "ObjectPattern") {
|
|
2203
|
+
const properties = record(node["id"])["properties"];
|
|
2204
|
+
for (const value of properties) {
|
|
2205
|
+
const item = record(value);
|
|
2206
|
+
const key = record(item?.["key"]);
|
|
2207
|
+
const name = item?.["computed"] === true ? key?.["type"] === "StringLiteral" ? key["value"] : void 0 : key?.["name"] ?? key?.["value"];
|
|
2208
|
+
add(result, name, evidence(envObject(node["init"])));
|
|
2209
|
+
}
|
|
2210
|
+
} else if (envObject(node) && !(parent && (parent["object"] === node || parent["type"] === "VariableDeclarator" && record(parent["id"])?.["type"] === "ObjectPattern"))) result.dynamic.push(evidence("dynamic"));
|
|
2211
|
+
for (const [key, child] of Object.entries(node)) if (![
|
|
2212
|
+
"loc",
|
|
2213
|
+
"comments",
|
|
2214
|
+
"leadingComments",
|
|
2215
|
+
"trailingComments",
|
|
2216
|
+
"innerComments",
|
|
2217
|
+
"tokens",
|
|
2218
|
+
"errors"
|
|
2219
|
+
].includes(key)) visit(child, node);
|
|
2220
|
+
}
|
|
2221
|
+
visit(ast);
|
|
2222
|
+
}
|
|
2223
|
+
return result;
|
|
2224
|
+
}
|
|
2225
|
+
/** Only names from example files are retained; actual env files are never passed here. */
|
|
2226
|
+
function scanExample(filename, source) {
|
|
2227
|
+
const result = {
|
|
2228
|
+
variables: /* @__PURE__ */ new Map(),
|
|
2229
|
+
dynamic: [],
|
|
2230
|
+
parseErrors: []
|
|
2231
|
+
};
|
|
2232
|
+
let quote;
|
|
2233
|
+
for (const [index, line] of source.split(/\r?\n/).entries()) {
|
|
2234
|
+
if (quote) {
|
|
2235
|
+
if (new RegExp(`(?<!\\\\)${quote}`).test(line)) quote = void 0;
|
|
2236
|
+
continue;
|
|
2237
|
+
}
|
|
2238
|
+
const match = /^\s*(?:export\s+)?([A-Z_]\w*)\s*=(.*)$/iu.exec(line);
|
|
2239
|
+
if (match) {
|
|
2240
|
+
add(result, match[1], {
|
|
2241
|
+
path: filename,
|
|
2242
|
+
line: index + 1,
|
|
2243
|
+
column: 1,
|
|
2244
|
+
kind: "example"
|
|
2245
|
+
});
|
|
2246
|
+
const value = match[2].trimStart();
|
|
2247
|
+
if (/^["'`]/.test(value) && !new RegExp(`(?<!\\\\)${value[0]}`).test(value.slice(1))) quote = value[0];
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
return result;
|
|
2251
|
+
}
|
|
2252
|
+
//#endregion
|
|
2253
|
+
//#region src/commands/env-cache/files.ts
|
|
2254
|
+
const ignored = [
|
|
2255
|
+
"**/node_modules/**",
|
|
2256
|
+
"**/.git/**",
|
|
2257
|
+
"**/dist/**",
|
|
2258
|
+
"**/build/**",
|
|
2259
|
+
"**/coverage/**",
|
|
2260
|
+
"**/.turbo/**",
|
|
2261
|
+
"**/.repoctl/**",
|
|
2262
|
+
"**/.next/**",
|
|
2263
|
+
"**/.nuxt/**",
|
|
2264
|
+
"**/out/**"
|
|
2265
|
+
];
|
|
2266
|
+
const sourcePattern = /\.(?:[cm]?[jt]sx?|vue|svelte)$/i;
|
|
2267
|
+
const envPattern = /^(?:\.env|\.dev\.vars)(?:\.|$)/;
|
|
2268
|
+
const examplePattern = /^(?:\.env|\.dev\.vars)(?:\.[\w-]+)*\.example$/;
|
|
2269
|
+
function finding(rule, pkg, task, message, fields = {}) {
|
|
2270
|
+
return {
|
|
2271
|
+
rule,
|
|
2272
|
+
package: pkg,
|
|
2273
|
+
task,
|
|
2274
|
+
severity: "warn",
|
|
2275
|
+
variable: null,
|
|
2276
|
+
path: null,
|
|
2277
|
+
line: null,
|
|
2278
|
+
message,
|
|
2279
|
+
...fields
|
|
2280
|
+
};
|
|
2281
|
+
}
|
|
2282
|
+
/** Source and example reads reject links; actual dotenv files are only enumerated. */
|
|
2283
|
+
async function readSafe(root, filename) {
|
|
2284
|
+
const target = path.join(root, filename);
|
|
2285
|
+
if (path.resolve(await realpath(target)) !== target) throw new Error("Linked scan input");
|
|
2286
|
+
const info = await lstat(target);
|
|
2287
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > 2097152) throw new Error("Unsupported scan input");
|
|
2288
|
+
return readFile(target, "utf8");
|
|
2289
|
+
}
|
|
2290
|
+
async function scanPackage(root, pkg, packageDirectories, include, exclude = []) {
|
|
2291
|
+
const directory = path.relative(root, pkg.directory);
|
|
2292
|
+
const nested = packageDirectories.filter((other) => other !== pkg.directory && other.startsWith(`${pkg.directory}/`)).map((other) => `${path.relative(pkg.directory, other)}/**`);
|
|
2293
|
+
const files = await glob(["**/*"], {
|
|
2294
|
+
cwd: pkg.directory,
|
|
2295
|
+
dot: true,
|
|
2296
|
+
onlyFiles: true,
|
|
2297
|
+
followSymbolicLinks: false,
|
|
2298
|
+
ignore: [
|
|
2299
|
+
...ignored,
|
|
2300
|
+
...nested,
|
|
2301
|
+
...exclude
|
|
2302
|
+
]
|
|
2303
|
+
});
|
|
2304
|
+
const references = /* @__PURE__ */ new Map();
|
|
2305
|
+
const dynamic = [];
|
|
2306
|
+
const environmentFiles = [];
|
|
2307
|
+
const findings = [];
|
|
2308
|
+
for (const local of files.sort()) {
|
|
2309
|
+
const relative = path.join(directory, local);
|
|
2310
|
+
if (/[\p{Cc}\p{Cf}]/u.test(relative)) {
|
|
2311
|
+
findings.push(finding("env-scan-input", pkg.name, null, "A filename contains unsupported control characters; its contents were not read."));
|
|
2312
|
+
continue;
|
|
2313
|
+
}
|
|
2314
|
+
const basename = path.basename(local);
|
|
2315
|
+
const environment = envPattern.test(basename);
|
|
2316
|
+
if (environment) environmentFiles.push(relative);
|
|
2317
|
+
const example = examplePattern.test(basename);
|
|
2318
|
+
if (!example && (environment || !sourcePattern.test(local)) || include && !matchesFile(local, include)) continue;
|
|
2319
|
+
try {
|
|
2320
|
+
const source = await readSafe(root, relative);
|
|
2321
|
+
const result = example ? scanExample(relative, source) : scanSource(relative, source);
|
|
2322
|
+
for (const [name, evidence] of result.variables) references.set(name, [...references.get(name) ?? [], ...evidence]);
|
|
2323
|
+
dynamic.push(...result.dynamic);
|
|
2324
|
+
for (const line of result.parseErrors) findings.push(finding("env-source-unparsed", pkg.name, null, "Source syntax could not be parsed; source text and parser details are omitted.", {
|
|
2325
|
+
path: relative,
|
|
2326
|
+
line
|
|
2327
|
+
}));
|
|
2328
|
+
} catch {
|
|
2329
|
+
findings.push(finding("env-scan-input", pkg.name, null, "A linked, oversized or unreadable source/example file was not scanned.", { path: relative }));
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
return {
|
|
2333
|
+
references,
|
|
2334
|
+
dynamic,
|
|
2335
|
+
environmentFiles,
|
|
2336
|
+
findings
|
|
2337
|
+
};
|
|
2338
|
+
}
|
|
2339
|
+
/** Git path enumeration establishes default-input coverage without loading env values. */
|
|
2340
|
+
function defaultInputs(root, files) {
|
|
2341
|
+
if (!files.length) return /* @__PURE__ */ new Set();
|
|
2342
|
+
const result = spawnSync("git", [
|
|
2343
|
+
"-C",
|
|
2344
|
+
root,
|
|
2345
|
+
"ls-files",
|
|
2346
|
+
"-z",
|
|
2347
|
+
"--cached",
|
|
2348
|
+
"--others",
|
|
2349
|
+
"--exclude-standard",
|
|
2350
|
+
"--",
|
|
2351
|
+
...files
|
|
2352
|
+
], {
|
|
2353
|
+
encoding: "utf8",
|
|
2354
|
+
timeout: 1e4,
|
|
2355
|
+
maxBuffer: 4194304
|
|
2356
|
+
});
|
|
2357
|
+
return result.status === 0 ? new Set(result.stdout.split("\0").filter(Boolean)) : null;
|
|
2358
|
+
}
|
|
2359
|
+
//#endregion
|
|
2360
|
+
//#region src/commands/env-cache/turbo-environment.ts
|
|
2361
|
+
const globalHash = ["VERCEL_ANALYTICS_ID", "VERCEL_TARGET_ENV"];
|
|
2362
|
+
const passthrough = [
|
|
2363
|
+
"HOME",
|
|
2364
|
+
"USER",
|
|
2365
|
+
"TZ",
|
|
2366
|
+
"LANG",
|
|
2367
|
+
"SHELL",
|
|
2368
|
+
"PWD",
|
|
2369
|
+
"XDG_DATA_*",
|
|
2370
|
+
"XDG_RUNTIME_DIR",
|
|
2371
|
+
"XAUTHORITY",
|
|
2372
|
+
"DBUS_SESSION_BUS_ADDRESS",
|
|
2373
|
+
"CI",
|
|
2374
|
+
"NODE_OPTIONS",
|
|
2375
|
+
"COREPACK_*",
|
|
2376
|
+
"LD_LIBRARY_PATH",
|
|
2377
|
+
"DYLD_FALLBACK_LIBRARY_PATH",
|
|
2378
|
+
"LIBPATH",
|
|
2379
|
+
"LD_PRELOAD",
|
|
2380
|
+
"DYLD_INSERT_LIBRARIES",
|
|
2381
|
+
"COLORTERM",
|
|
2382
|
+
"FORCE_COLOR",
|
|
2383
|
+
"NO_COLOR",
|
|
2384
|
+
"TERM",
|
|
2385
|
+
"TERM_PROGRAM",
|
|
2386
|
+
"DISPLAY",
|
|
2387
|
+
"TMP",
|
|
2388
|
+
"TEMP",
|
|
2389
|
+
"WINDIR",
|
|
2390
|
+
"ProgramFiles",
|
|
2391
|
+
"ProgramFiles(x86)",
|
|
2392
|
+
"VSCODE_*",
|
|
2393
|
+
"ELECTRON_RUN_AS_NODE",
|
|
2394
|
+
"DOCKER_*",
|
|
2395
|
+
"BUILDKIT_*",
|
|
2396
|
+
"COMPOSE_*",
|
|
2397
|
+
"JB_IDE_*",
|
|
2398
|
+
"JB_INTERPRETER",
|
|
2399
|
+
"_JETBRAINS_TEST_RUNNER_RUN_SCOPE_TYPE",
|
|
2400
|
+
"TURBO_*",
|
|
2401
|
+
"VERCEL",
|
|
2402
|
+
"VERCEL_*",
|
|
2403
|
+
"NEXT_*",
|
|
2404
|
+
"USE_OUTPUT_FOR_EDGE_FUNCTIONS",
|
|
2405
|
+
"NOW_BUILDER",
|
|
2406
|
+
"VC_MICROFRONTENDS_CONFIG_FILE_NAME",
|
|
2407
|
+
"GITHUB_*",
|
|
2408
|
+
"RUNNER_*",
|
|
2409
|
+
"__NIXOS_*",
|
|
2410
|
+
"NIX_*",
|
|
2411
|
+
"APPDATA",
|
|
2412
|
+
"LOCALAPPDATA",
|
|
2413
|
+
"PATH",
|
|
2414
|
+
"PROGRAMDATA",
|
|
2415
|
+
"SYSTEMROOT",
|
|
2416
|
+
"SYSTEMDRIVE",
|
|
2417
|
+
"USERPROFILE",
|
|
2418
|
+
"HOMEDRIVE",
|
|
2419
|
+
"HOMEPATH",
|
|
2420
|
+
"PNPM_HOME",
|
|
2421
|
+
"pnpm_config_verify_deps_before_run",
|
|
2422
|
+
"NPM_CONFIG_STORE_DIR",
|
|
2423
|
+
"COMSPEC",
|
|
2424
|
+
"PATHEXT"
|
|
2425
|
+
];
|
|
2426
|
+
const builtinGlobalEnv = globalHash.map((pattern) => ({
|
|
2427
|
+
pattern,
|
|
2428
|
+
field: "globalEnv",
|
|
2429
|
+
path: "turbo:built-in"
|
|
2430
|
+
}));
|
|
2431
|
+
const builtinPassThroughEnv = passthrough.map((pattern) => ({
|
|
2432
|
+
pattern,
|
|
2433
|
+
field: "passThroughEnv",
|
|
2434
|
+
path: "turbo:built-in"
|
|
2435
|
+
}));
|
|
2436
|
+
//#endregion
|
|
2437
|
+
//#region src/commands/env-cache/evaluate.ts
|
|
2438
|
+
const frameworks = [
|
|
2439
|
+
[["next"], ["NEXT_PUBLIC_*"]],
|
|
2440
|
+
[["@sveltejs/kit"], ["PUBLIC_*"]],
|
|
2441
|
+
[["astro"], ["PUBLIC_*"]],
|
|
2442
|
+
[["nuxt"], ["NUXT_*", "NUXT_ENV_*"]],
|
|
2443
|
+
[["expo"], ["EXPO_PUBLIC_*"]],
|
|
2444
|
+
[["react-scripts"], ["REACT_APP_*"]],
|
|
2445
|
+
[["gatsby"], ["GATSBY_*"]],
|
|
2446
|
+
[["@remix-run/dev"], ["REMIX_*"]],
|
|
2447
|
+
[["@solidjs/start", "solid-start"], ["VITE_*"]],
|
|
2448
|
+
[["@redwoodjs/core"], ["REDWOOD_ENV_*"]],
|
|
2449
|
+
[["sanity"], ["SANITY_STUDIO_*"]],
|
|
2450
|
+
[["vite"], ["VITE_*"]]
|
|
2451
|
+
];
|
|
2452
|
+
const viteBuiltins = /* @__PURE__ */ new Set([
|
|
2453
|
+
"MODE",
|
|
2454
|
+
"BASE_URL",
|
|
2455
|
+
"DEV",
|
|
2456
|
+
"PROD",
|
|
2457
|
+
"SSR"
|
|
2458
|
+
]);
|
|
2459
|
+
function frameworkDeclarations(dependencies, enabled) {
|
|
2460
|
+
return ((enabled ? frameworks.find(([names]) => names.some((name) => dependencies.includes(name))) : void 0)?.[1] ?? []).map((pattern) => ({
|
|
2461
|
+
path: "turbo:framework-inference",
|
|
2462
|
+
field: "env",
|
|
2463
|
+
pattern
|
|
2464
|
+
}));
|
|
2465
|
+
}
|
|
2466
|
+
function variable(name, evidence, config, inferred) {
|
|
2467
|
+
const hash = [...envMatches(name, [...builtinGlobalEnv, ...config.globalEnv]), ...envMatches(name, config.env)];
|
|
2468
|
+
if (hash.length) return {
|
|
2469
|
+
name,
|
|
2470
|
+
evidence,
|
|
2471
|
+
coverage: "hash",
|
|
2472
|
+
declarations: hash
|
|
2473
|
+
};
|
|
2474
|
+
const framework = envExcluded(name, config.env) ? [] : envMatches(name, inferred);
|
|
2475
|
+
if (framework.length) return {
|
|
2476
|
+
name,
|
|
2477
|
+
evidence,
|
|
2478
|
+
coverage: "inferred",
|
|
2479
|
+
declarations: framework
|
|
2480
|
+
};
|
|
2481
|
+
const passthrough = envExcluded(name, config.passThroughEnv) ? [] : [
|
|
2482
|
+
...envMatches(name, builtinPassThroughEnv),
|
|
2483
|
+
...envMatches(name, config.globalPassThroughEnv),
|
|
2484
|
+
...envMatches(name, config.passThroughEnv)
|
|
2485
|
+
];
|
|
2486
|
+
if (passthrough.length) return {
|
|
2487
|
+
name,
|
|
2488
|
+
evidence,
|
|
2489
|
+
coverage: "passthrough",
|
|
2490
|
+
declarations: passthrough
|
|
2491
|
+
};
|
|
2492
|
+
if (viteBuiltins.has(name) && evidence.every((item) => item.kind === "import-meta-env") && inferred.some((item) => ["VITE_*", "PUBLIC_*"].includes(item.pattern))) return {
|
|
2493
|
+
name,
|
|
2494
|
+
evidence,
|
|
2495
|
+
coverage: "builtin",
|
|
2496
|
+
declarations: [{
|
|
2497
|
+
path: "framework:import-meta-env",
|
|
2498
|
+
field: "builtin",
|
|
2499
|
+
pattern: name
|
|
2500
|
+
}]
|
|
2501
|
+
};
|
|
2502
|
+
return {
|
|
2503
|
+
name,
|
|
2504
|
+
evidence,
|
|
2505
|
+
coverage: "missing",
|
|
2506
|
+
declarations: []
|
|
2507
|
+
};
|
|
2508
|
+
}
|
|
2509
|
+
function fileCoverage(filename, directory, config, defaults) {
|
|
2510
|
+
const global = config.globalDependencies.map((item) => item.pattern);
|
|
2511
|
+
if (!negativeFileMatch(filename, global) && matchesFile(filename, global.filter((pattern) => !pattern.startsWith("!")))) return "global";
|
|
2512
|
+
const local = path.relative(directory, filename);
|
|
2513
|
+
const inputs = config.inputs?.map((item) => {
|
|
2514
|
+
const negative = item.pattern.startsWith("!");
|
|
2515
|
+
const pattern = negative ? item.pattern.slice(1) : item.pattern;
|
|
2516
|
+
return `${negative ? "!" : ""}${pattern.startsWith("$TURBO_ROOT$/") ? path.relative(directory, pattern.slice(13)) : pattern}`;
|
|
2517
|
+
});
|
|
2518
|
+
if (inputs && negativeFileMatch(local, inputs)) return "missing";
|
|
2519
|
+
if (inputs && matchesFile(local, inputs.filter((pattern) => pattern !== "$TURBO_DEFAULT$" && !pattern.startsWith("!")))) return "task";
|
|
2520
|
+
if (!inputs?.length || inputs.includes("$TURBO_DEFAULT$")) return local.startsWith("../") ? "missing" : defaults === null ? "unknown" : defaults.has(filename) ? "default" : "missing";
|
|
2521
|
+
return "missing";
|
|
2522
|
+
}
|
|
2523
|
+
function evaluate(pkg, directory, task, config, references, dynamic, files, defaults, inferred) {
|
|
2524
|
+
const result = {
|
|
2525
|
+
package: pkg,
|
|
2526
|
+
path: directory || ".",
|
|
2527
|
+
task,
|
|
2528
|
+
cache: config.cache,
|
|
2529
|
+
variables: [...references].sort(([a], [b]) => a.localeCompare(b)).map(([name, evidence]) => variable(name, evidence, config, inferred)),
|
|
2530
|
+
dynamic,
|
|
2531
|
+
files: files.map((filename) => ({
|
|
2532
|
+
path: filename,
|
|
2533
|
+
coverage: fileCoverage(filename, directory, config, defaults)
|
|
2534
|
+
}))
|
|
2535
|
+
};
|
|
2536
|
+
const findings = [];
|
|
2537
|
+
for (const item of result.variables) if (["missing", "passthrough"].includes(item.coverage)) {
|
|
2538
|
+
const evidence = item.evidence[0];
|
|
2539
|
+
findings.push(finding(item.coverage === "missing" ? "env-unhashed" : "env-passthrough", pkg, task, item.coverage === "missing" ? "This variable is not declared in the task hash. Review whether its value changes build output." : "This variable is available through passthrough but does not affect the task hash. Review whether that is intentional.", {
|
|
2540
|
+
severity: config.cache ? "warn" : "info",
|
|
2541
|
+
variable: item.name,
|
|
2542
|
+
path: evidence.path,
|
|
2543
|
+
line: evidence.line
|
|
2544
|
+
}));
|
|
2545
|
+
}
|
|
2546
|
+
for (const evidence of dynamic) findings.push(finding("env-dynamic-access", pkg, task, "The variable name or environment-object use cannot be resolved statically.", {
|
|
2547
|
+
path: evidence.path,
|
|
2548
|
+
line: evidence.line,
|
|
2549
|
+
severity: config.cache ? "warn" : "info"
|
|
2550
|
+
}));
|
|
2551
|
+
for (const file of result.files) if (file.coverage === "missing" || file.coverage === "unknown") findings.push(finding("env-file-input", pkg, task, file.coverage === "unknown" ? "Default input coverage could not be verified without Git metadata." : "This environment file is not covered by task inputs or globalDependencies.", {
|
|
2552
|
+
path: file.path,
|
|
2553
|
+
severity: config.cache ? "warn" : "info"
|
|
2554
|
+
}));
|
|
2555
|
+
for (const declaration of config.globalEnv.filter((item) => item.pattern === "*")) findings.push(finding("env-global-scope", pkg, task, "globalEnv matches every variable and invalidates all tasks when any value changes. Review whether task-local declarations would be sufficient.", { path: declaration.path }));
|
|
2556
|
+
return {
|
|
2557
|
+
result,
|
|
2558
|
+
findings
|
|
2559
|
+
};
|
|
2560
|
+
}
|
|
2561
|
+
//#endregion
|
|
2562
|
+
//#region src/commands/env-cache/settings.ts
|
|
2563
|
+
const list = (value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0 && item.length <= 1024 && !/[\p{Cc}\p{Cf}]/u.test(item));
|
|
2564
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2565
|
+
function settings(value, options) {
|
|
2566
|
+
if (value !== void 0 && !object(value)) throw new Error("commands.env must be an object");
|
|
2567
|
+
const config = value ?? {};
|
|
2568
|
+
for (const key of [
|
|
2569
|
+
"tasks",
|
|
2570
|
+
"include",
|
|
2571
|
+
"exclude"
|
|
2572
|
+
]) if (config[key] !== void 0 && !list(config[key])) throw new Error("Invalid environment scan list; contents omitted");
|
|
2573
|
+
if (config["frameworkInference"] !== void 0 && typeof config["frameworkInference"] !== "boolean") throw new Error("frameworkInference must be boolean");
|
|
2574
|
+
if (options.frameworkInference !== void 0 && typeof options.frameworkInference !== "boolean") throw new Error("frameworkInference must be boolean");
|
|
2575
|
+
const tasks = options.tasks ?? config["tasks"] ?? ["build"];
|
|
2576
|
+
if (!list(tasks) || !tasks.length || tasks.some((task) => !/^[\w:.-]+$/.test(task))) throw new Error("Environment tasks must be nonempty task names");
|
|
2577
|
+
if (config["suppressions"] !== void 0 && (!Array.isArray(config["suppressions"]) || config["suppressions"].some((item) => {
|
|
2578
|
+
return !object(item) || typeof item["rule"] !== "string" || !/^[a-z-]+$/.test(item["rule"]) || typeof item["reason"] !== "string" || !item["reason"].trim() || [
|
|
2579
|
+
"package",
|
|
2580
|
+
"task",
|
|
2581
|
+
"variable",
|
|
2582
|
+
"path"
|
|
2583
|
+
].some((key) => item[key] !== void 0 && !list([item[key]]));
|
|
2584
|
+
}))) throw new Error("Every environment suppression needs a rule, a reason and valid optional selectors");
|
|
2585
|
+
return {
|
|
2586
|
+
...config,
|
|
2587
|
+
tasks: [...new Set(tasks)],
|
|
2588
|
+
frameworkInference: options.frameworkInference ?? config["frameworkInference"] ?? true
|
|
2589
|
+
};
|
|
2590
|
+
}
|
|
2591
|
+
function suppress(findings, suppressions = []) {
|
|
2592
|
+
const used = /* @__PURE__ */ new Set();
|
|
2593
|
+
for (const finding of findings) {
|
|
2594
|
+
const index = suppressions.findIndex((item) => item.rule === finding.rule && [
|
|
2595
|
+
"package",
|
|
2596
|
+
"task",
|
|
2597
|
+
"variable",
|
|
2598
|
+
"path"
|
|
2599
|
+
].every((field) => {
|
|
2600
|
+
const key = field;
|
|
2601
|
+
return item[key] === void 0 || finding[key] !== null && matchesFile(finding[key], [item[key]]);
|
|
2602
|
+
}));
|
|
2603
|
+
if (index >= 0) {
|
|
2604
|
+
used.add(index);
|
|
2605
|
+
finding.suppression = {
|
|
2606
|
+
index,
|
|
2607
|
+
reason: suppressions[index].reason
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
for (const [index] of suppressions.entries()) if (!used.has(index)) findings.push({
|
|
2612
|
+
rule: "env-suppression-unused",
|
|
2613
|
+
severity: "warn",
|
|
2614
|
+
package: "//",
|
|
2615
|
+
task: null,
|
|
2616
|
+
variable: null,
|
|
2617
|
+
path: null,
|
|
2618
|
+
line: null,
|
|
2619
|
+
message: `Environment suppression ${index} did not match any finding.`
|
|
2620
|
+
});
|
|
2621
|
+
}
|
|
2622
|
+
//#endregion
|
|
2623
|
+
//#region src/commands/env-cache/index.ts
|
|
2624
|
+
var env_cache_exports = /* @__PURE__ */ __exportAll({ checkEnvironmentCache: () => checkEnvironmentCache });
|
|
2625
|
+
async function checkEnvironmentCache(cwd, options = {}) {
|
|
2626
|
+
const report = {
|
|
2627
|
+
schemaVersion: 1,
|
|
2628
|
+
kind: "environment-cache-check",
|
|
2629
|
+
status: "pass",
|
|
2630
|
+
tasks: [],
|
|
2631
|
+
findings: [],
|
|
2632
|
+
summary: {
|
|
2633
|
+
info: 0,
|
|
2634
|
+
warn: 0,
|
|
2635
|
+
fail: 0,
|
|
2636
|
+
suppressed: 0
|
|
2637
|
+
},
|
|
2638
|
+
limitations: [
|
|
2639
|
+
"Source references are candidates for selected tasks, not proof of runtime reachability. By default only build is checked.",
|
|
2640
|
+
"Only JavaScript/TypeScript and Vue/Svelte script blocks are scanned. Aliases, shadowed globals, template expressions, generated code and cross-package source imports are not resolved.",
|
|
2641
|
+
"Actual environment files and process environment values are never read. Example files contribute names only.",
|
|
2642
|
+
"Advanced Turbo global configuration and object-form input declarations are not supported; unsupported shapes fail validation.",
|
|
2643
|
+
"Framework inference is estimated from package dependencies. Runtime CLI flags, custom framework prefixes and shell-defined variables may change behavior.",
|
|
2644
|
+
"Executable repoctl configuration is loaded normally and must itself avoid side effects for a read-only check."
|
|
2645
|
+
]
|
|
2646
|
+
};
|
|
2647
|
+
try {
|
|
2648
|
+
clearWorkspaceCache();
|
|
2649
|
+
const workspace = await getWorkspaceData(cwd, {
|
|
2650
|
+
ignoreRootPackage: false,
|
|
2651
|
+
ignorePrivatePackage: false
|
|
2652
|
+
});
|
|
2653
|
+
const root = path.resolve(await realpath(workspace.workspaceDir));
|
|
2654
|
+
const config = settings((await loadMonorepoConfigDetails(root, { refresh: true })).config.commands?.env, options);
|
|
2655
|
+
const packages = workspace.packages.map((pkg) => ({
|
|
2656
|
+
name: pkg.rootDir === root ? "//" : pkg.manifest.name ?? path.relative(root, pkg.rootDir),
|
|
2657
|
+
directory: pkg.rootDir,
|
|
2658
|
+
manifest: pkg.manifest
|
|
2659
|
+
}));
|
|
2660
|
+
if (packages.some((pkg) => pkg.directory !== root && !pkg.directory.startsWith(`${root}/`))) throw new Error("Workspace package lies outside the canonical root");
|
|
2661
|
+
const resolve = await loadTurboConfigurations(root, packages);
|
|
2662
|
+
const rootFiles = [];
|
|
2663
|
+
for (const pkg of packages.sort((a, b) => a.directory.localeCompare(b.directory))) {
|
|
2664
|
+
const scanned = await scanPackage(root, pkg, packages.map((item) => item.directory), config.include, config.exclude);
|
|
2665
|
+
report.findings.push(...scanned.findings);
|
|
2666
|
+
if (pkg.directory === root) rootFiles.push(...scanned.environmentFiles);
|
|
2667
|
+
const files = [.../* @__PURE__ */ new Set([...rootFiles, ...scanned.environmentFiles])].sort();
|
|
2668
|
+
const defaults = defaultInputs(root, files);
|
|
2669
|
+
const inferred = frameworkDeclarations([...Object.keys(pkg.manifest.dependencies ?? {}), ...Object.keys(pkg.manifest.devDependencies ?? {})], config.frameworkInference);
|
|
2670
|
+
for (const task of config.tasks) {
|
|
2671
|
+
if (!pkg.manifest.scripts?.[task]) continue;
|
|
2672
|
+
try {
|
|
2673
|
+
const configuration = resolve(pkg.name, task);
|
|
2674
|
+
if (!configuration.enabled) {
|
|
2675
|
+
report.findings.push(finding("env-task-disabled", pkg.name, task, "This script is not registered as a Turbo task or is excluded from inheritance.", { severity: "info" }));
|
|
2676
|
+
continue;
|
|
2677
|
+
}
|
|
2678
|
+
const evaluated = evaluate(pkg.name, path.relative(root, pkg.directory), task, configuration, scanned.references, scanned.dynamic, files, defaults, inferred);
|
|
2679
|
+
report.tasks.push(evaluated.result);
|
|
2680
|
+
report.findings.push(...evaluated.findings);
|
|
2681
|
+
} catch {
|
|
2682
|
+
report.findings.push(finding("env-turbo-config", pkg.name, task, "Task configuration could not be resolved; declaration contents are omitted.", { severity: "fail" }));
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
if (!report.tasks.length) report.findings.push(finding("env-no-tasks", "//", null, "No workspace scripts matched the selected tasks."));
|
|
2687
|
+
suppress(report.findings, config.suppressions);
|
|
2688
|
+
} catch {
|
|
2689
|
+
report.findings.push(finding("env-config", "//", null, "Workspace, repoctl or Turbo configuration is invalid or unreadable; contents are omitted.", { severity: "fail" }));
|
|
2690
|
+
}
|
|
2691
|
+
for (const item of report.findings) if (item.suppression) report.summary.suppressed++;
|
|
2692
|
+
else report.summary[item.severity]++;
|
|
2693
|
+
report.status = report.summary.fail ? "fail" : report.summary.warn ? "warn" : "pass";
|
|
2694
|
+
return report;
|
|
2695
|
+
}
|
|
2696
|
+
//#endregion
|
|
2697
|
+
//#region src/commands/env-cache/format.ts
|
|
2698
|
+
var format_exports = /* @__PURE__ */ __exportAll({ formatEnvironmentCache: () => formatEnvironmentCache });
|
|
2699
|
+
const cell = (value) => (value ?? "—").replace(/[\r\n|]/g, " ").replace(/</g, "<").replace(/>/g, ">").replace(/`/g, "`");
|
|
2700
|
+
function formatEnvironmentCache(report, markdown = false) {
|
|
2701
|
+
const lines = [
|
|
2702
|
+
`${markdown ? "# " : ""}Environment cache check: ${report.status}`,
|
|
2703
|
+
"",
|
|
2704
|
+
`${report.summary.fail} failures, ${report.summary.warn} warnings, ${report.summary.info} notes, ${report.summary.suppressed} suppressed.`
|
|
2705
|
+
];
|
|
2706
|
+
for (const task of report.tasks) {
|
|
2707
|
+
lines.push("", `${markdown ? "## " : ""}${cell(task.package)}#${cell(task.task)} (cache: ${task.cache === null ? "unknown" : task.cache})`);
|
|
2708
|
+
for (const variable of task.variables) {
|
|
2709
|
+
const source = variable.evidence.map((item) => `${cell(item.path)}:${item.line}:${item.column}`).join(", ");
|
|
2710
|
+
lines.push(`- ${cell(variable.name)}: ${variable.coverage} — ${source}`);
|
|
2711
|
+
}
|
|
2712
|
+
for (const file of task.files) lines.push(`- File ${cell(file.path)}: ${file.coverage}`);
|
|
2713
|
+
}
|
|
2714
|
+
lines.push("", markdown ? "## Findings" : "Findings");
|
|
2715
|
+
for (const finding of report.findings) lines.push(`- [${finding.suppression ? "suppressed" : finding.severity}] ${finding.rule}: ${cell(finding.package)}${finding.task ? `#${cell(finding.task)}` : ""}${finding.variable ? ` ${cell(finding.variable)}` : ""}${finding.path ? ` ${cell(finding.path)}${finding.line ? `:${finding.line}` : ""}` : ""} — ${cell(finding.message)}${finding.suppression ? ` Reason: ${cell(finding.suppression.reason)}` : ""}`);
|
|
2716
|
+
lines.push("", markdown ? "## Scan limits" : "Scan limits", ...report.limitations.map((item) => `- ${item}`));
|
|
2717
|
+
return lines.join("\n");
|
|
2718
|
+
}
|
|
2719
|
+
//#endregion
|
|
2720
|
+
//#region src/commands/generate/files.ts
|
|
2721
|
+
function generatorPath(value) {
|
|
2722
|
+
if (typeof value !== "string" || !value || value.includes("\\") || path.isAbsolute(value) || value.split("/").some((part) => !part || part === "." || part === ".." || /[<>:"|?*]/.test(part) || [...part].some((character) => character.charCodeAt(0) < 32) || /[. ]$/.test(part) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)) || value.split("/").some((part) => [
|
|
2723
|
+
"node_modules",
|
|
2724
|
+
".git",
|
|
2725
|
+
".repoctl",
|
|
2726
|
+
"dist"
|
|
2727
|
+
].includes(part))) throw new Error(`Expected a portable package-relative generator path: ${String(value)}`);
|
|
2728
|
+
return value;
|
|
2729
|
+
}
|
|
2730
|
+
/** Validate every existing ancestor even when the destination does not exist yet. */
|
|
2731
|
+
async function generatorFile(root, relative) {
|
|
2732
|
+
const parts = generatorPath(relative).split("/");
|
|
2733
|
+
let cursor = root;
|
|
2734
|
+
for (const [index, part] of parts.entries()) {
|
|
2735
|
+
cursor = path.join(cursor, part);
|
|
2736
|
+
try {
|
|
2737
|
+
const metadata = await lstat(cursor);
|
|
2738
|
+
if (metadata.isSymbolicLink() || (index === parts.length - 1 ? !metadata.isFile() || metadata.nlink !== 1 : !metadata.isDirectory())) throw new Error(`Linked or unsupported generator path: ${relative}`);
|
|
2739
|
+
} catch (error) {
|
|
2740
|
+
if (error.code === "ENOENT") return null;
|
|
2741
|
+
throw error;
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
return readFile(await safeFile(root, relative), "utf8");
|
|
2745
|
+
}
|
|
2746
|
+
//#endregion
|
|
2747
|
+
//#region src/commands/project-references/files.ts
|
|
2748
|
+
const ownershipFile = ".repoctl/typescript-references.json";
|
|
2749
|
+
const compare$1 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
2750
|
+
function relativeFile(value, glob = false) {
|
|
2751
|
+
if (typeof value !== "string" || !value || value.includes("\\") || value.includes("\0") || path.isAbsolute(value) || /^[a-z]:/i.test(value) || value.split("/").some((part) => !part || part === "." || part === "..") || !glob && /[*?[\]{}!]/.test(value)) throw new Error(`Expected a canonical workspace-relative ${glob ? "pattern" : "file"}: ${String(value)}`);
|
|
2752
|
+
return value;
|
|
2753
|
+
}
|
|
2754
|
+
async function exists(root, relative) {
|
|
2755
|
+
let cursor = root;
|
|
2756
|
+
for (const component of relativeFile(relative).split("/")) {
|
|
2757
|
+
cursor = path.join(cursor, component);
|
|
2758
|
+
try {
|
|
2759
|
+
const stat = await lstat(cursor);
|
|
2760
|
+
if (stat.isSymbolicLink() || cursor !== path.join(root, relative) && !stat.isDirectory()) throw new Error(`Linked or unsupported project reference path: ${relative}`);
|
|
2761
|
+
} catch (error) {
|
|
2762
|
+
if (error.code === "ENOENT") return false;
|
|
2763
|
+
throw error;
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
return true;
|
|
2767
|
+
}
|
|
2768
|
+
async function readText(root, relative, inputs) {
|
|
2769
|
+
const text = new TextDecoder$1("utf-8", {
|
|
2770
|
+
fatal: true,
|
|
2771
|
+
ignoreBOM: true
|
|
2772
|
+
}).decode(await readFile(await safeFile(root, relative)));
|
|
2773
|
+
if (inputs) inputs[relative] = hash(text);
|
|
2774
|
+
return text;
|
|
2775
|
+
}
|
|
2776
|
+
function referenceTarget(source, reference) {
|
|
2777
|
+
if (!reference || reference.includes("\\") || path.isAbsolute(reference) || /^[a-z]:/i.test(reference)) throw new Error(`Unsupported project reference: ${reference}`);
|
|
2778
|
+
const resolved = path.normalize(path.join(path.dirname(source), reference));
|
|
2779
|
+
return relativeFile(resolved.endsWith(".json") ? resolved : path.join(resolved, "tsconfig.json"));
|
|
2780
|
+
}
|
|
2781
|
+
function referencePath(source, target) {
|
|
2782
|
+
const relative = path.relative(path.dirname(source), target);
|
|
2783
|
+
return relative.startsWith(".") ? relative : `./${relative}`;
|
|
2784
|
+
}
|
|
2785
|
+
//#endregion
|
|
2786
|
+
//#region src/commands/project-references/compiler.ts
|
|
2787
|
+
function loadCompiler(root) {
|
|
2788
|
+
try {
|
|
2789
|
+
return createRequire(path.join(root, "package.json"))("typescript");
|
|
2790
|
+
} catch {
|
|
2791
|
+
throw new Error("Install TypeScript in the workspace before checking or synchronizing project references.");
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
function configReader(root, ts, inputs, diagnostics) {
|
|
2795
|
+
const cache = /* @__PURE__ */ new Map();
|
|
2796
|
+
return async (file) => {
|
|
2797
|
+
if (cache.has(file)) return cache.get(file);
|
|
2798
|
+
cache.set(file, void 0);
|
|
2799
|
+
if (!await exists(root, file)) {
|
|
2800
|
+
diagnostics.push({
|
|
2801
|
+
code: "missing",
|
|
2802
|
+
path: file,
|
|
2803
|
+
message: `Project configuration does not exist: ${file}`
|
|
2804
|
+
});
|
|
2805
|
+
inputs[file] = "missing";
|
|
2806
|
+
return;
|
|
2807
|
+
}
|
|
2808
|
+
const original = await readText(root, file, inputs);
|
|
2809
|
+
const parsed = ts.parseConfigFileTextToJson(file, original);
|
|
2810
|
+
if (parsed.error) {
|
|
2811
|
+
diagnostics.push({
|
|
2812
|
+
code: "config",
|
|
2813
|
+
path: file,
|
|
2814
|
+
message: ts.flattenDiagnosticMessageText(parsed.error.messageText, "\n")
|
|
2815
|
+
});
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
const config = parsed.config;
|
|
2819
|
+
if (!config || typeof config !== "object" || Array.isArray(config) || config.references !== void 0 && (!Array.isArray(config.references) || config.references.some((ref) => !ref || typeof ref !== "object" || typeof ref.path !== "string"))) {
|
|
2820
|
+
diagnostics.push({
|
|
2821
|
+
code: "config",
|
|
2822
|
+
path: file,
|
|
2823
|
+
message: "Expected a tsconfig object and references containing string paths."
|
|
2824
|
+
});
|
|
2825
|
+
return;
|
|
2826
|
+
}
|
|
2827
|
+
if (ts.parseJsonText(file, original).statements[0].expression.properties.filter((property) => property.name && ts.isStringLiteral(property.name) && property.name.text === "references").length > 1) {
|
|
2828
|
+
diagnostics.push({
|
|
2829
|
+
code: "config",
|
|
2830
|
+
path: file,
|
|
2831
|
+
message: "Duplicate references properties are ambiguous."
|
|
2832
|
+
});
|
|
2833
|
+
return;
|
|
2834
|
+
}
|
|
2835
|
+
const command = ts.getParsedCommandLineOfConfigFile(path.join(root, file), {}, {
|
|
2836
|
+
...ts.sys,
|
|
2837
|
+
readFile(filename) {
|
|
2838
|
+
const value = ts.sys.readFile(filename);
|
|
2839
|
+
inputs[`compiler:${path.normalize(filename)}`] = value === void 0 ? "missing" : hash(value);
|
|
2840
|
+
return value;
|
|
2841
|
+
},
|
|
2842
|
+
onUnRecoverableConfigFileDiagnostic(error) {
|
|
2843
|
+
diagnostics.push({
|
|
2844
|
+
code: "config",
|
|
2845
|
+
path: file,
|
|
2846
|
+
message: ts.flattenDiagnosticMessageText(error.messageText, "\n")
|
|
2847
|
+
});
|
|
2848
|
+
}
|
|
2849
|
+
});
|
|
2850
|
+
for (const error of command?.errors ?? []) if (error.code !== 18003 && error.code !== 18002) diagnostics.push({
|
|
2851
|
+
code: "config",
|
|
2852
|
+
path: file,
|
|
2853
|
+
message: ts.flattenDiagnosticMessageText(error.messageText, "\n")
|
|
2854
|
+
});
|
|
2855
|
+
const result = {
|
|
2856
|
+
path: file,
|
|
2857
|
+
original,
|
|
2858
|
+
references: config.references ?? [],
|
|
2859
|
+
options: command?.options ?? {}
|
|
2860
|
+
};
|
|
2861
|
+
cache.set(file, result);
|
|
2862
|
+
return result;
|
|
2863
|
+
};
|
|
2864
|
+
}
|
|
2865
|
+
async function validateGraph(starts, projected, read, diagnostics) {
|
|
2866
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2867
|
+
const visiting = [];
|
|
2868
|
+
const validated = /* @__PURE__ */ new Set();
|
|
2869
|
+
const visit = async (file) => {
|
|
2870
|
+
if (visiting.includes(file)) {
|
|
2871
|
+
diagnostics.push({
|
|
2872
|
+
code: "cycle",
|
|
2873
|
+
path: file,
|
|
2874
|
+
message: `Project reference cycle: ${[...visiting.slice(visiting.indexOf(file)), file].join(" -> ")}`
|
|
2875
|
+
});
|
|
2876
|
+
return;
|
|
2877
|
+
}
|
|
2878
|
+
if (visited.has(file)) return;
|
|
2879
|
+
const config = await read(file);
|
|
2880
|
+
if (!config) return;
|
|
2881
|
+
visiting.push(file);
|
|
2882
|
+
for (const reference of projected.get(file) ?? config.references) {
|
|
2883
|
+
let target;
|
|
2884
|
+
try {
|
|
2885
|
+
target = referenceTarget(file, reference.path);
|
|
2886
|
+
} catch (error) {
|
|
2887
|
+
diagnostics.push({
|
|
2888
|
+
code: "config",
|
|
2889
|
+
path: file,
|
|
2890
|
+
message: error.message
|
|
2891
|
+
});
|
|
2892
|
+
continue;
|
|
2893
|
+
}
|
|
2894
|
+
const dependency = await read(target);
|
|
2895
|
+
if (dependency && !validated.has(target)) {
|
|
2896
|
+
validated.add(target);
|
|
2897
|
+
if (dependency.options.composite !== true || dependency.options.declaration === false || dependency.options.noEmit === true) diagnostics.push({
|
|
2898
|
+
code: "incompatible",
|
|
2899
|
+
path: target,
|
|
2900
|
+
message: "Referenced projects require composite and declaration output; repoctl does not change compiler options."
|
|
2901
|
+
});
|
|
2902
|
+
}
|
|
2903
|
+
await visit(target);
|
|
2904
|
+
}
|
|
2905
|
+
visiting.pop();
|
|
2906
|
+
visited.add(file);
|
|
2907
|
+
};
|
|
2908
|
+
for (const file of starts) await visit(file);
|
|
2909
|
+
}
|
|
2910
|
+
//#endregion
|
|
2911
|
+
//#region src/commands/generate/exports.ts
|
|
2912
|
+
function updateGeneratorExports(workspace, barrel, original, source, symbol, vue) {
|
|
2913
|
+
const ts = loadCompiler(workspace);
|
|
2914
|
+
const parsed = ts.createSourceFile(barrel, original, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
2915
|
+
if (parsed.parseDiagnostics.length) throw new Error(`Cannot update invalid TypeScript barrel: ${barrel}`);
|
|
2916
|
+
const relative = path.relative(path.dirname(barrel), source);
|
|
2917
|
+
const specifier = (relative.startsWith(".") ? relative : `./${relative}`).replace(/\.(?:ts|tsx)$/, "");
|
|
2918
|
+
const hasBinding = (name) => ts.isIdentifier(name) ? name.text === symbol : name.elements.some((element) => ts.isBindingElement(element) && hasBinding(element.name));
|
|
2919
|
+
let existing = false;
|
|
2920
|
+
let insertBefore;
|
|
2921
|
+
for (const statement of parsed.statements) {
|
|
2922
|
+
if (ts.isExportAssignment(statement) && statement.isExportEquals) throw new Error(`Cannot add named exports to a CommonJS export assignment: ${barrel}`);
|
|
2923
|
+
if (ts.isExportDeclaration(statement)) {
|
|
2924
|
+
const module = statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : void 0;
|
|
2925
|
+
if (module && module.localeCompare(specifier, "en", { numeric: true }) > 0 && !insertBefore) insertBefore = statement;
|
|
2926
|
+
if (!statement.exportClause) throw new Error(`Cannot prove export names behind export * in ${barrel}; omit --export and update the barrel manually.`);
|
|
2927
|
+
if (ts.isNamedExports(statement.exportClause)) {
|
|
2928
|
+
for (const entry of statement.exportClause.elements) if (entry.name.text === symbol) {
|
|
2929
|
+
const expected = vue ? "default" : symbol;
|
|
2930
|
+
if (module !== specifier || (entry.propertyName?.text ?? entry.name.text) !== expected || entry.isTypeOnly || statement.isTypeOnly) throw new Error(`Export name already exists in ${barrel}: ${symbol}`);
|
|
2931
|
+
existing = true;
|
|
2932
|
+
}
|
|
2933
|
+
} else if (statement.exportClause.name.text === symbol) throw new Error(`Export name already exists in ${barrel}: ${symbol}`);
|
|
2934
|
+
} else if (ts.canHaveModifiers(statement) && ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
2935
|
+
const named = statement;
|
|
2936
|
+
const variable = ts.isVariableStatement(statement) && statement.declarationList.declarations.some((declaration) => hasBinding(declaration.name));
|
|
2937
|
+
if (named.name?.text === symbol || variable) throw new Error(`Export name already exists in ${barrel}: ${symbol}`);
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
if (existing) return original;
|
|
2941
|
+
const newline = original.includes("\r\n") ? "\r\n" : "\n";
|
|
2942
|
+
const declaration = ts.factory.createExportDeclaration(void 0, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, vue ? ts.factory.createIdentifier("default") : void 0, ts.factory.createIdentifier(symbol))]), ts.factory.createStringLiteral(specifier, true));
|
|
2943
|
+
const printed = ts.createPrinter({
|
|
2944
|
+
newLine: newline === "\r\n" ? ts.NewLineKind.CarriageReturnLineFeed : ts.NewLineKind.LineFeed,
|
|
2945
|
+
omitTrailingSemicolon: true
|
|
2946
|
+
}).printNode(ts.EmitHint.Unspecified, declaration, parsed);
|
|
2947
|
+
if (insertBefore) {
|
|
2948
|
+
const start = (ts.getLeadingCommentRanges(original, insertBefore.getFullStart()) ?? [])[0]?.pos ?? insertBefore.getStart(parsed);
|
|
2949
|
+
const position = original.lastIndexOf("\n", start - 1) + 1;
|
|
2950
|
+
if (original.slice(position, start).trim()) throw new Error(`Cannot safely insert an export into a compact barrel: ${barrel}`);
|
|
2951
|
+
return `${original.slice(0, position)}${printed}${newline}${original.slice(position)}`;
|
|
2952
|
+
}
|
|
2953
|
+
return `${original}${original && !original.endsWith("\n") ? newline : ""}${printed}${newline}`;
|
|
2954
|
+
}
|
|
2955
|
+
//#endregion
|
|
2956
|
+
//#region src/commands/generate/render.ts
|
|
2957
|
+
const generators = [
|
|
2958
|
+
"vue-component",
|
|
2959
|
+
"react-component",
|
|
2960
|
+
"hono-route"
|
|
2961
|
+
];
|
|
2962
|
+
function generatorIdentity(name) {
|
|
2963
|
+
if (typeof name !== "string" || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) || name.length > 80) throw new Error("parameters.name must be a kebab-case name of at most 80 characters.");
|
|
2964
|
+
return {
|
|
2965
|
+
name,
|
|
2966
|
+
symbol: name.split("-").map((part) => part[0].toUpperCase() + part.slice(1)).join("")
|
|
2967
|
+
};
|
|
2968
|
+
}
|
|
2969
|
+
function renderGenerator(generator, symbol, specifier) {
|
|
2970
|
+
specifier = specifier.replaceAll("'", "\\'");
|
|
2971
|
+
if (generator === "vue-component") return {
|
|
2972
|
+
extension: "vue",
|
|
2973
|
+
testExtension: "ts",
|
|
2974
|
+
source: `<script setup lang="ts">
|
|
2975
|
+
withDefaults(defineProps<{ label?: string, disabled?: boolean }>(), { label: '${symbol}', disabled: false })
|
|
2976
|
+
const emit = defineEmits<{ activate: [] }>()
|
|
2977
|
+
<\/script>
|
|
2978
|
+
|
|
2979
|
+
<template>
|
|
2980
|
+
<button type="button" :disabled="disabled" @click="emit('activate')">
|
|
2981
|
+
{{ label }}
|
|
2982
|
+
</button>
|
|
2983
|
+
</template>
|
|
2984
|
+
`,
|
|
2985
|
+
test: `import { mount } from '@vue/test-utils'
|
|
2986
|
+
import { expect, it } from 'vitest'
|
|
2987
|
+
import ${symbol} from '${specifier}.vue'
|
|
2988
|
+
|
|
2989
|
+
it('renders its label and emits activation', async () => {
|
|
2990
|
+
const wrapper = mount(${symbol}, { props: { label: 'Open' } })
|
|
2991
|
+
expect(wrapper.text()).toBe('Open')
|
|
2992
|
+
await wrapper.get('button').trigger('click')
|
|
2993
|
+
expect(wrapper.emitted('activate')).toHaveLength(1)
|
|
2994
|
+
wrapper.unmount()
|
|
2995
|
+
})
|
|
2996
|
+
|
|
2997
|
+
it('prevents activation while disabled', async () => {
|
|
2998
|
+
const wrapper = mount(${symbol}, { props: { disabled: true } })
|
|
2999
|
+
await wrapper.get('button').trigger('click')
|
|
3000
|
+
expect(wrapper.emitted('activate')).toBeUndefined()
|
|
3001
|
+
wrapper.unmount()
|
|
3002
|
+
})
|
|
3003
|
+
`
|
|
3004
|
+
};
|
|
3005
|
+
if (generator === "react-component") return {
|
|
3006
|
+
extension: "tsx",
|
|
3007
|
+
testExtension: "tsx",
|
|
3008
|
+
source: `export interface ${symbol}Props {
|
|
3009
|
+
label?: string
|
|
3010
|
+
disabled?: boolean
|
|
3011
|
+
onActivate?: () => void
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
export function ${symbol}({ label = '${symbol}', disabled = false, onActivate }: ${symbol}Props) {
|
|
3015
|
+
return <button type="button" disabled={disabled} onClick={onActivate}>{label}</button>
|
|
3016
|
+
}
|
|
3017
|
+
`,
|
|
3018
|
+
test: `import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
|
3019
|
+
import { afterEach, expect, it, vi } from 'vitest'
|
|
3020
|
+
import { ${symbol} } from '${specifier}'
|
|
3021
|
+
|
|
3022
|
+
afterEach(cleanup)
|
|
3023
|
+
|
|
3024
|
+
it('renders its label and calls activation', () => {
|
|
3025
|
+
const onActivate = vi.fn()
|
|
3026
|
+
render(<${symbol} label="Open" onActivate={onActivate} />)
|
|
3027
|
+
fireEvent.click(screen.getByRole('button', { name: 'Open' }))
|
|
3028
|
+
expect(onActivate).toHaveBeenCalledOnce()
|
|
3029
|
+
})
|
|
3030
|
+
|
|
3031
|
+
it('prevents activation while disabled', () => {
|
|
3032
|
+
const onActivate = vi.fn()
|
|
3033
|
+
render(<${symbol} disabled onActivate={onActivate} />)
|
|
3034
|
+
fireEvent.click(screen.getByRole('button'))
|
|
3035
|
+
expect(onActivate).not.toHaveBeenCalled()
|
|
3036
|
+
})
|
|
3037
|
+
`
|
|
3038
|
+
};
|
|
3039
|
+
return {
|
|
3040
|
+
extension: "ts",
|
|
3041
|
+
testExtension: "ts",
|
|
3042
|
+
source: `import { Hono } from 'hono'
|
|
3043
|
+
|
|
3044
|
+
export const ${symbol} = new Hono().get('/', c => c.json({ message: '${symbol}' }))
|
|
3045
|
+
`,
|
|
3046
|
+
test: `import { expect, it } from 'vitest'
|
|
3047
|
+
import { ${symbol} } from '${specifier}'
|
|
3048
|
+
|
|
3049
|
+
it('responds to GET with its public JSON response', async () => {
|
|
3050
|
+
const response = await ${symbol}.request('/')
|
|
3051
|
+
expect(response.status).toBe(200)
|
|
3052
|
+
expect(await response.json()).toEqual({ message: '${symbol}' })
|
|
3053
|
+
})
|
|
3054
|
+
|
|
3055
|
+
it('does not accept unsupported methods', async () => {
|
|
3056
|
+
const response = await ${symbol}.request('/', { method: 'POST' })
|
|
3057
|
+
expect(response.status).toBe(404)
|
|
3058
|
+
})
|
|
3059
|
+
`
|
|
3060
|
+
};
|
|
3061
|
+
}
|
|
3062
|
+
//#endregion
|
|
3063
|
+
//#region src/commands/generate/plan.ts
|
|
3064
|
+
function declared(manifest, dependency) {
|
|
3065
|
+
return [
|
|
3066
|
+
"dependencies",
|
|
3067
|
+
"devDependencies",
|
|
3068
|
+
"peerDependencies",
|
|
3069
|
+
"optionalDependencies"
|
|
3070
|
+
].some((field) => {
|
|
3071
|
+
const values = manifest[field];
|
|
3072
|
+
return values && typeof values === "object" && Object.hasOwn(values, dependency);
|
|
3073
|
+
});
|
|
3074
|
+
}
|
|
3075
|
+
/** Resolve one package, validate its framework, and derive every byte without writing. */
|
|
3076
|
+
async function planGenerate(options) {
|
|
3077
|
+
if (!options || !generators.includes(options.generator) || typeof options.package !== "string" || !options.package) throw new Error("Choose a supported generator and an exact workspace package name or relative directory.");
|
|
3078
|
+
const parameters = resolveTemplateParameters({
|
|
3079
|
+
name: {
|
|
3080
|
+
type: "string",
|
|
3081
|
+
required: true
|
|
3082
|
+
},
|
|
3083
|
+
export: {
|
|
3084
|
+
type: "boolean",
|
|
3085
|
+
default: false
|
|
3086
|
+
}
|
|
3087
|
+
}, options.parameters);
|
|
3088
|
+
const { name, symbol: baseSymbol } = generatorIdentity(parameters.values["name"]);
|
|
3089
|
+
const symbol = options.generator === "hono-route" ? `${baseSymbol[0].toLowerCase()}${baseSymbol.slice(1)}Route` : baseSymbol;
|
|
3090
|
+
clearWorkspaceCache();
|
|
3091
|
+
const data = await getWorkspaceData(options.cwd, { ignorePrivatePackage: false });
|
|
3092
|
+
const workspaceDir = path.normalize(await realpath(data.workspaceDir));
|
|
3093
|
+
const selected = data.packages.filter((pkg) => pkg.manifest["name"] === options.package || path.relative(workspaceDir, pkg.rootDir) === options.package);
|
|
3094
|
+
if (selected.length !== 1) throw new Error(`Expected exactly one workspace package for ${options.package}; found ${selected.length}.`);
|
|
3095
|
+
const pkg = selected[0];
|
|
3096
|
+
const relativeDir = generatorPath(path.relative(workspaceDir, pkg.rootDir));
|
|
3097
|
+
const packageDir = path.join(workspaceDir, relativeDir);
|
|
3098
|
+
const packageText = await generatorFile(workspaceDir, `${relativeDir}/package.json`);
|
|
3099
|
+
if (packageText === null) throw new Error("The selected package has no package.json.");
|
|
3100
|
+
const manifest = JSON.parse(packageText);
|
|
3101
|
+
const dependency = options.generator === "vue-component" ? "vue" : options.generator === "react-component" ? "react" : "hono";
|
|
3102
|
+
if (!declared(manifest, dependency)) throw new Error(`Generator ${options.generator} requires the selected package to declare ${dependency}.`);
|
|
3103
|
+
const directory = generatorPath(options.directory ?? (options.generator === "hono-route" ? "src/routes" : "src/components"));
|
|
3104
|
+
const barrel = generatorPath(options.barrel ?? "src/index.ts");
|
|
3105
|
+
if (parameters.values["export"] && !barrel.endsWith(".ts")) throw new Error("The export barrel must be a TypeScript .ts file.");
|
|
3106
|
+
const specifier = path.relative("test", `${directory}/${name}`);
|
|
3107
|
+
const rendered = renderGenerator(options.generator, symbol, specifier.startsWith(".") ? specifier : `./${specifier}`);
|
|
3108
|
+
const source = `${directory}/${name}.${rendered.extension}`;
|
|
3109
|
+
const test = `test/${name}.test.${rendered.testExtension}`;
|
|
3110
|
+
const desired = /* @__PURE__ */ new Map([[source, rendered.source], [test, rendered.test]]);
|
|
3111
|
+
const rootText = await generatorFile(workspaceDir, "package.json");
|
|
3112
|
+
const rootManifest = rootText ? JSON.parse(rootText) : {};
|
|
3113
|
+
const inputs = {
|
|
3114
|
+
"package.json": hash(packageText),
|
|
3115
|
+
"workspace:package.json": rootText === null ? "missing" : hash(rootText)
|
|
3116
|
+
};
|
|
3117
|
+
if (parameters.values["export"]) {
|
|
3118
|
+
if (desired.has(barrel)) throw new Error("The export barrel cannot be a generated source or test.");
|
|
3119
|
+
const original = await generatorFile(packageDir, barrel);
|
|
3120
|
+
desired.set(barrel, updateGeneratorExports(workspaceDir, barrel, original ?? "", source, symbol, options.generator === "vue-component"));
|
|
3121
|
+
inputs[barrel] = original === null ? "missing" : hash(original);
|
|
3122
|
+
}
|
|
3123
|
+
const nested = data.packages.map((item) => path.relative(packageDir, item.rootDir)).filter((item) => item && !item.startsWith("../") && !path.isAbsolute(item));
|
|
3124
|
+
const files = [];
|
|
3125
|
+
for (const [file, after] of desired) {
|
|
3126
|
+
if (nested.some((child) => file.startsWith(`${child}/`))) throw new Error(`Generator output belongs to a nested workspace package: ${file}`);
|
|
3127
|
+
const before = await generatorFile(packageDir, file);
|
|
3128
|
+
if (!(parameters.values["export"] && file === barrel) && before !== null && before !== after) throw new Error(`Generator file conflict: ${file}`);
|
|
3129
|
+
files.push({
|
|
3130
|
+
path: file,
|
|
3131
|
+
before,
|
|
3132
|
+
after,
|
|
3133
|
+
action: before === after ? "unchanged" : before === null ? "create" : "update"
|
|
3134
|
+
});
|
|
3135
|
+
}
|
|
3136
|
+
const nextSteps = [`Run pnpm --filter ./${relativeDir} build, lint, typecheck and test.`];
|
|
3137
|
+
const testing = options.generator === "vue-component" ? "@vue/test-utils" : options.generator === "react-component" ? "@testing-library/react" : void 0;
|
|
3138
|
+
const missing = ["vitest", ...testing ? [testing] : []].filter((value) => !declared(manifest, value) && !declared(rootManifest, value));
|
|
3139
|
+
if (missing.length) nextSteps.push(`Ensure ${missing.join(", ")} and a compatible Vitest environment are available in the selected package before running its generated tests.`);
|
|
3140
|
+
if (options.generator === "hono-route") nextSteps.push(`In your Hono application, import { ${symbol} } from './${source.replace(/^src\//, "").replace(/\.ts$/, "")}' and register app.route('/${name}', ${symbol}). Review the mount path and middleware ordering; repoctl does not infer the application entry.`);
|
|
3141
|
+
return {
|
|
3142
|
+
schemaVersion: 1,
|
|
3143
|
+
workspaceDir,
|
|
3144
|
+
packageDir,
|
|
3145
|
+
packageName: String(manifest["name"] ?? relativeDir),
|
|
3146
|
+
options: {
|
|
3147
|
+
cwd: workspaceDir,
|
|
3148
|
+
package: relativeDir,
|
|
3149
|
+
generator: options.generator,
|
|
3150
|
+
parameters: parameters.retained,
|
|
3151
|
+
directory,
|
|
3152
|
+
barrel
|
|
3153
|
+
},
|
|
3154
|
+
inputs,
|
|
3155
|
+
files: files.sort((a, b) => a.path.localeCompare(b.path)),
|
|
3156
|
+
nextSteps
|
|
3157
|
+
};
|
|
3158
|
+
}
|
|
3159
|
+
//#endregion
|
|
3160
|
+
//#region src/commands/generate/apply.ts
|
|
3161
|
+
async function applyLocked(plan) {
|
|
3162
|
+
const fresh = await planGenerate(plan.options);
|
|
3163
|
+
if (JSON.stringify(fresh) !== JSON.stringify(plan)) throw new Error("Generator plan is stale or modified; create and review a fresh plan.");
|
|
3164
|
+
const changes = fresh.files.filter((file) => file.action !== "unchanged");
|
|
3165
|
+
const result = {
|
|
3166
|
+
schemaVersion: 1,
|
|
3167
|
+
changed: [],
|
|
3168
|
+
recoveryFiles: [],
|
|
3169
|
+
nextSteps: fresh.nextSteps
|
|
3170
|
+
};
|
|
3171
|
+
if (!changes.length) return result;
|
|
3172
|
+
const placeholder = `repoctl-generator-${randomUUID()}\n`;
|
|
3173
|
+
const createdFiles = [];
|
|
3174
|
+
const createdDirectories = [];
|
|
3175
|
+
let transaction;
|
|
3176
|
+
const cleanupDirectories = async () => {
|
|
3177
|
+
for (const item of [...createdDirectories].reverse()) try {
|
|
3178
|
+
const stat = await lstat(item.path);
|
|
3179
|
+
if (stat.ino === item.identity.ino && stat.dev === item.identity.dev && !stat.isSymbolicLink()) await rmdir(item.path);
|
|
3180
|
+
} catch {}
|
|
3181
|
+
};
|
|
3182
|
+
try {
|
|
3183
|
+
for (const file of changes.filter((item) => item.before === null)) {
|
|
3184
|
+
let cursor = plan.packageDir;
|
|
3185
|
+
for (const part of path.dirname(file.path).split("/").filter((part) => part !== ".")) {
|
|
3186
|
+
cursor = path.join(cursor, part);
|
|
3187
|
+
try {
|
|
3188
|
+
await mkdir(cursor);
|
|
3189
|
+
createdDirectories.push({
|
|
3190
|
+
path: cursor,
|
|
3191
|
+
identity: await lstat(cursor)
|
|
3192
|
+
});
|
|
3193
|
+
} catch (error) {
|
|
3194
|
+
if (error.code !== "EEXIST") throw error;
|
|
3195
|
+
}
|
|
3196
|
+
const metadata = await lstat(cursor);
|
|
3197
|
+
if (!metadata.isDirectory() || metadata.isSymbolicLink()) throw new Error(`Generator directory changed: ${cursor}`);
|
|
3198
|
+
}
|
|
3199
|
+
if (await generatorFile(plan.packageDir, file.path) !== null) throw new Error(`Generator output appeared after planning: ${file.path}`);
|
|
3200
|
+
const handle = await open(path.join(plan.packageDir, file.path), "wx");
|
|
3201
|
+
const item = {
|
|
3202
|
+
path: file.path,
|
|
3203
|
+
identity: await handle.stat(),
|
|
3204
|
+
written: false
|
|
3205
|
+
};
|
|
3206
|
+
createdFiles.push(item);
|
|
3207
|
+
try {
|
|
3208
|
+
await handle.writeFile(placeholder);
|
|
3209
|
+
item.written = true;
|
|
3210
|
+
} finally {
|
|
3211
|
+
await handle.close();
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
transaction = await stageFileTransaction(changes.map((file) => ({
|
|
3215
|
+
path: file.path,
|
|
3216
|
+
original: file.before ?? placeholder,
|
|
3217
|
+
content: file.after
|
|
3218
|
+
})), (file) => safeFile(plan.packageDir, file), "generate");
|
|
3219
|
+
await transaction.apply();
|
|
3220
|
+
if ((await planGenerate(plan.options)).files.some((file) => file.action !== "unchanged")) throw new Error("Generator outputs changed during verification.");
|
|
3221
|
+
result.changed = changes.map((file) => file.path);
|
|
3222
|
+
} catch (error) {
|
|
3223
|
+
const recovery = await transaction?.rollback() ?? [];
|
|
3224
|
+
for (const file of createdFiles) try {
|
|
3225
|
+
const filename = await safeFile(plan.packageDir, file.path);
|
|
3226
|
+
const metadata = await lstat(filename);
|
|
3227
|
+
if (!(file.written ? await readFile(filename, "utf8") === placeholder : metadata.ino === file.identity.ino && metadata.dev === file.identity.dev)) throw new Error("Generator placeholder was modified");
|
|
3228
|
+
await unlink(filename);
|
|
3229
|
+
} catch {
|
|
3230
|
+
recovery.push(path.join(plan.packageDir, file.path));
|
|
3231
|
+
}
|
|
3232
|
+
await cleanupDirectories();
|
|
3233
|
+
if (recovery.length) throw new AggregateError([error], `Generator rollback needs attention; preserve recovery files: ${recovery.join(", ")}`);
|
|
3234
|
+
throw error;
|
|
3235
|
+
}
|
|
3236
|
+
result.recoveryFiles = await transaction.cleanup();
|
|
3237
|
+
return result;
|
|
3238
|
+
}
|
|
3239
|
+
async function applyGeneratePlan(plan) {
|
|
3240
|
+
if (plan?.schemaVersion !== 1 || typeof plan.packageDir !== "string" || path.normalize(await realpath(plan.packageDir)) !== plan.packageDir) throw new Error("Invalid generator plan or noncanonical package directory.");
|
|
3241
|
+
const fresh = await planGenerate(plan.options);
|
|
3242
|
+
if (JSON.stringify(fresh) !== JSON.stringify(plan)) throw new Error("Generator plan is stale or modified; create and review a fresh plan.");
|
|
3243
|
+
return withOperationLock(plan.packageDir, "generate", () => applyLocked(plan));
|
|
3244
|
+
}
|
|
3245
|
+
//#endregion
|
|
3246
|
+
//#region src/commands/generate/index.ts
|
|
3247
|
+
var generate_exports = /* @__PURE__ */ __exportAll({
|
|
3248
|
+
applyGeneratePlan: () => applyGeneratePlan,
|
|
3249
|
+
generators: () => generators,
|
|
3250
|
+
planGenerate: () => planGenerate
|
|
3251
|
+
});
|
|
3252
|
+
//#endregion
|
|
3253
|
+
//#region src/commands/template-instances/source.ts
|
|
3254
|
+
async function renderHistoricalTemplate(options) {
|
|
3255
|
+
const sourcePackageDir = options.sourceDir ? path.resolve(options.cwd, options.sourceDir) : packageDir;
|
|
3256
|
+
const definition = getTemplateDefinition(options.template) ?? {
|
|
3257
|
+
source: options.template,
|
|
3258
|
+
target: options.target
|
|
3259
|
+
};
|
|
3260
|
+
let actualVersion;
|
|
3261
|
+
try {
|
|
3262
|
+
actualVersion = await readTemplatePackageVersion(sourcePackageDir);
|
|
3263
|
+
} catch (error) {
|
|
3264
|
+
if (error.code === "ENOENT") return;
|
|
3265
|
+
throw error;
|
|
3266
|
+
}
|
|
3267
|
+
if (actualVersion !== options.version) {
|
|
3268
|
+
if (options.sourceDir) throw new Error(`Historical template package version is ${actualVersion}, not requested ${options.version}.`);
|
|
3269
|
+
return;
|
|
3270
|
+
}
|
|
3271
|
+
const sourceDir = await safeInstancePath(sourcePackageDir, `templates/${definition.source}`);
|
|
3272
|
+
if (!await fs$2.pathExists(sourceDir)) return;
|
|
3273
|
+
const original = await prepareTemplateInstanceSource(sourceDir, sourcePackageDir);
|
|
3274
|
+
let retainedParameters;
|
|
3275
|
+
const isolated = await mkdtemp(path.join(tmpdir(), "repoctl-template-baseline-"));
|
|
3276
|
+
try {
|
|
3277
|
+
const targetDir = path.join(isolated, options.target);
|
|
3278
|
+
await fs$2.ensureDir(targetDir);
|
|
3279
|
+
if (options.profile === "workspace-copy-v1") await scaffoldTemplate({
|
|
3280
|
+
sourceDir,
|
|
3281
|
+
targetDir
|
|
3282
|
+
});
|
|
3283
|
+
else {
|
|
3284
|
+
const renameJson = options.parameters?.renameJson ?? false;
|
|
3285
|
+
let snapshot;
|
|
3286
|
+
if (options.profile === "repo-new-parameters-v1") {
|
|
3287
|
+
const manifest = readTemplateParameterManifest(original.snapshot);
|
|
3288
|
+
if (!manifest) throw new Error("Parameterized template upgrades require an explicit repoctl.template.json contract.");
|
|
3289
|
+
if (Object.entries(manifest.parameters).some(([name, definition]) => definition.sensitive && Object.hasOwn(options.parameters?.templateValues ?? {}, name))) throw new Error("Historical template parameters must not contain sensitive values. Retain names and excluded output paths only.");
|
|
3290
|
+
const omitted = (file) => {
|
|
3291
|
+
const generated = file.replace(/(^|\/)gitignore$/u, "$1.gitignore");
|
|
3292
|
+
return options.excludedPaths?.some((item) => generated === item || generated.startsWith(`${item}/`)) ?? false;
|
|
3293
|
+
};
|
|
3294
|
+
const parameters = Object.fromEntries(Object.entries(manifest.parameters).map(([name, definition]) => [name, definition.sensitive && options.parameters?.sensitiveParameters?.includes(name) ? {
|
|
3295
|
+
...definition,
|
|
3296
|
+
required: false
|
|
3297
|
+
} : definition]));
|
|
3298
|
+
const values = resolveTemplateParameters(parameters, options.parameters?.templateValues ?? {});
|
|
3299
|
+
retainedParameters = {
|
|
3300
|
+
...options.parameters,
|
|
3301
|
+
templateValues: values.retained
|
|
3302
|
+
};
|
|
3303
|
+
const prepared = rewriteTemplateSnapshotReferences(original.snapshot, targetDir, isolated);
|
|
3304
|
+
snapshot = renderTemplateParameters({
|
|
3305
|
+
...prepared,
|
|
3306
|
+
files: prepared.files.filter((file) => !omitted(file.path)),
|
|
3307
|
+
directories: prepared.directories.filter((directory) => !omitted(directory))
|
|
3308
|
+
}, {
|
|
3309
|
+
...manifest,
|
|
3310
|
+
parameters,
|
|
3311
|
+
...manifest.interpolate ? { interpolate: manifest.interpolate.filter((file) => !omitted(file)) } : {},
|
|
3312
|
+
...manifest.conditions ? { conditions: manifest.conditions.map((condition) => ({
|
|
3313
|
+
...condition,
|
|
3314
|
+
...condition.files ? { files: condition.files.filter((file) => !omitted(file)) } : {}
|
|
3315
|
+
})) } : {}
|
|
3316
|
+
}, values).snapshot;
|
|
3317
|
+
}
|
|
3318
|
+
await renderCreateNewProject({
|
|
3319
|
+
cwd: isolated,
|
|
3320
|
+
sourceDir,
|
|
3321
|
+
targetDir,
|
|
3322
|
+
hasPackageJson: await fs$2.pathExists(path.join(sourceDir, "package.json")),
|
|
3323
|
+
packageName: options.parameters?.packageName ?? path.basename(options.target),
|
|
3324
|
+
packageJsonFileName: renameJson ? "package.mock.json" : "package.json",
|
|
3325
|
+
...snapshot ? { snapshot } : {}
|
|
3326
|
+
}, false);
|
|
3327
|
+
}
|
|
3328
|
+
const after = await captureTemplateSnapshot(sourceDir);
|
|
3329
|
+
if (snapshotDigest(after) !== snapshotDigest(original.snapshot)) throw new Error("Historical template source changed during baseline rendering.");
|
|
3330
|
+
return {
|
|
3331
|
+
original,
|
|
3332
|
+
rendered: await captureTemplateSnapshot(targetDir),
|
|
3333
|
+
...retainedParameters ? { parameters: retainedParameters } : {}
|
|
3334
|
+
};
|
|
3335
|
+
} finally {
|
|
3336
|
+
await rm(isolated, {
|
|
3337
|
+
recursive: true,
|
|
3338
|
+
force: true
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
//#endregion
|
|
3343
|
+
//#region src/commands/template-instances/link.ts
|
|
3344
|
+
function digest(value) {
|
|
3345
|
+
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
3346
|
+
}
|
|
3347
|
+
function normalizeOptions(input) {
|
|
3348
|
+
if (!isExactTemplateVersion(input.version)) throw new Error("Template linking requires an exact historical package version; floating tags and ranges are not supported.");
|
|
3349
|
+
if (!/^[a-z\d][a-z\d-]*$/iu.test(input.template)) throw new Error("Template linking requires a stable template key.");
|
|
3350
|
+
const profile = input.profile ?? "repo-new-v1";
|
|
3351
|
+
if (![
|
|
3352
|
+
"workspace-copy-v1",
|
|
3353
|
+
"repo-new-v1",
|
|
3354
|
+
"repo-new-parameters-v1"
|
|
3355
|
+
].includes(profile)) throw new Error("Unsupported template generation profile.");
|
|
3356
|
+
const cwd = path.resolve(input.cwd);
|
|
3357
|
+
const target = instanceRelativePath(cwd, path.resolve(cwd, input.target));
|
|
3358
|
+
const parameters = generationParameters(input.parameters);
|
|
3359
|
+
if (profile !== "repo-new-parameters-v1" && (parameters.templateValues !== void 0 || parameters.sensitiveParameters !== void 0)) throw new Error("Template parameter values require the parameterized generation profile and a verified historical contract.");
|
|
3360
|
+
if (profile === "repo-new-v1" || profile === "repo-new-parameters-v1") {
|
|
3361
|
+
parameters.packageName ??= path.basename(target);
|
|
3362
|
+
parameters.renameJson ??= false;
|
|
3363
|
+
} else if (Object.keys(parameters).length) throw new Error("The workspace-copy-v1 profile does not accept project rewrite parameters.");
|
|
3364
|
+
return {
|
|
3365
|
+
cwd,
|
|
3366
|
+
target,
|
|
3367
|
+
template: input.template,
|
|
3368
|
+
version: input.version,
|
|
3369
|
+
profile,
|
|
3370
|
+
parameters,
|
|
3371
|
+
allowUnverified: input.allowUnverified === true,
|
|
3372
|
+
...input.sourceDir ? { sourceDir: path.resolve(cwd, input.sourceDir) } : {}
|
|
3373
|
+
};
|
|
3374
|
+
}
|
|
3375
|
+
async function prepareLink(input) {
|
|
3376
|
+
const options = normalizeOptions(input);
|
|
3377
|
+
const safeTarget = await safeInstancePath(options.cwd, options.target);
|
|
3378
|
+
options.target = instanceRelativePath(await fs.realpath(options.cwd), await fs.realpath(safeTarget));
|
|
3379
|
+
const registry = await loadTemplateInstanceRegistry(options.cwd);
|
|
3380
|
+
const target = await captureTemplateSnapshot(await safeInstancePath(options.cwd, options.target));
|
|
3381
|
+
const existing = registry.instances.find((item) => item.target === options.target);
|
|
3382
|
+
let draft;
|
|
3383
|
+
if (!options.sourceDir && existing?.template === options.template && existing.source.version === options.version && existing.generator.profile === options.profile && JSON.stringify(existing.parameters) === JSON.stringify(options.parameters) && existing.baseline.status === "available") {
|
|
3384
|
+
const original = await loadTemplateBaseline(options.cwd, existing.baseline.original);
|
|
3385
|
+
const rendered = await loadTemplateBaseline(options.cwd, existing.baseline.rendered);
|
|
3386
|
+
draft = {
|
|
3387
|
+
instance: existing,
|
|
3388
|
+
snapshots: {
|
|
3389
|
+
[existing.baseline.original]: original,
|
|
3390
|
+
[existing.baseline.rendered]: rendered
|
|
3391
|
+
}
|
|
3392
|
+
};
|
|
3393
|
+
} else {
|
|
3394
|
+
const baseline = await renderHistoricalTemplate(options);
|
|
3395
|
+
if (options.profile === "repo-new-parameters-v1") {
|
|
3396
|
+
if (!baseline) throw new Error("Parameterized template linking requires the exact historical source to verify nonsensitive inputs; unverified registration is unavailable.");
|
|
3397
|
+
options.parameters = generationParameters(baseline.parameters);
|
|
3398
|
+
}
|
|
3399
|
+
const originalDigest = baseline ? snapshotDigest(baseline.original.snapshot) : void 0;
|
|
3400
|
+
const renderedDigest = baseline ? snapshotDigest(baseline.rendered) : void 0;
|
|
3401
|
+
draft = {
|
|
3402
|
+
instance: {
|
|
3403
|
+
id: templateInstanceId(options.target, options.template),
|
|
3404
|
+
target: options.target,
|
|
3405
|
+
template: options.template,
|
|
3406
|
+
provenance: "linked",
|
|
3407
|
+
source: baseline?.original.source ?? {
|
|
3408
|
+
kind: "package",
|
|
3409
|
+
packageName: "@icebreakers/monorepo-templates",
|
|
3410
|
+
version: options.version,
|
|
3411
|
+
templatePath: `templates/${getTemplateDefinition(options.template)?.source ?? options.template}`
|
|
3412
|
+
},
|
|
3413
|
+
generator: {
|
|
3414
|
+
profile: options.profile,
|
|
3415
|
+
version
|
|
3416
|
+
},
|
|
3417
|
+
parameters: options.parameters,
|
|
3418
|
+
baseline: originalDigest && renderedDigest ? {
|
|
3419
|
+
status: "available",
|
|
3420
|
+
original: originalDigest,
|
|
3421
|
+
rendered: renderedDigest
|
|
3422
|
+
} : {
|
|
3423
|
+
status: "unverified",
|
|
3424
|
+
reason: "source-unavailable"
|
|
3425
|
+
},
|
|
3426
|
+
...existing?.excludedPaths ? { excludedPaths: existing.excludedPaths } : {}
|
|
3427
|
+
},
|
|
3428
|
+
snapshots: baseline && originalDigest && renderedDigest ? {
|
|
3429
|
+
[originalDigest]: baseline.original.snapshot,
|
|
3430
|
+
[renderedDigest]: baseline.rendered
|
|
3431
|
+
} : {}
|
|
3432
|
+
};
|
|
3433
|
+
}
|
|
3434
|
+
const baseline = draft.instance.baseline;
|
|
3435
|
+
const same = existing && digest({
|
|
3436
|
+
...existing,
|
|
3437
|
+
id: "",
|
|
3438
|
+
provenance: ""
|
|
3439
|
+
}) === digest({
|
|
3440
|
+
...draft.instance,
|
|
3441
|
+
id: "",
|
|
3442
|
+
provenance: ""
|
|
3443
|
+
});
|
|
3444
|
+
const overlap = registry.instances.some((item) => item.target !== options.target && (item.target.startsWith(`${options.target}/`) || options.target.startsWith(`${item.target}/`)));
|
|
3445
|
+
const verifiable = existing && canVerifyTemplateInstance(existing, draft.instance);
|
|
3446
|
+
const action = overlap || existing && !same && !verifiable ? "conflict" : same ? "unchanged" : verifiable ? "verify" : "register";
|
|
3447
|
+
const content = {
|
|
3448
|
+
schemaVersion: 1,
|
|
3449
|
+
options,
|
|
3450
|
+
target: options.target,
|
|
3451
|
+
source: draft.instance.source,
|
|
3452
|
+
baselineStatus: baseline.status,
|
|
3453
|
+
action,
|
|
3454
|
+
limitations: baseline.status === "available" ? [] : [
|
|
3455
|
+
"source-unavailable",
|
|
3456
|
+
"reliable-upgrade-unavailable",
|
|
3457
|
+
"upstream-comparison-unavailable"
|
|
3458
|
+
],
|
|
3459
|
+
differences: baseline.status === "available" ? compareTemplateSnapshots(draft.snapshots[baseline.rendered], target) : [],
|
|
3460
|
+
registryDigest: digest(registry),
|
|
3461
|
+
targetDigest: snapshotDigest(target)
|
|
3462
|
+
};
|
|
3463
|
+
return {
|
|
3464
|
+
plan: {
|
|
3465
|
+
...content,
|
|
3466
|
+
fingerprint: digest(content)
|
|
3467
|
+
},
|
|
3468
|
+
draft
|
|
3469
|
+
};
|
|
3470
|
+
}
|
|
3471
|
+
async function planTemplateLink(options) {
|
|
3472
|
+
return (await prepareLink(options)).plan;
|
|
3473
|
+
}
|
|
3474
|
+
async function applyTemplateLinkPlan(plan) {
|
|
3475
|
+
const current = await prepareLink(plan.options);
|
|
3476
|
+
const { fingerprint, ...content } = plan;
|
|
3477
|
+
if (digest(content) !== fingerprint || current.plan.fingerprint !== fingerprint) throw new Error("Template link plan is stale; target files, source, or registry changed. Preview again before applying.");
|
|
3478
|
+
if (current.plan.action === "conflict") throw new Error("Template link conflicts with an existing registered instance; no business files or registry entries were changed.");
|
|
3479
|
+
if (current.plan.baselineStatus === "unverified" && !current.plan.options.allowUnverified) throw new Error("Historical source is unavailable. Provide the exact extracted package or explicitly allow an unverified association.");
|
|
3480
|
+
await registerTemplateInstances(current.plan.options.cwd, [current.draft], async (registry) => {
|
|
3481
|
+
const target = await captureTemplateSnapshot(await safeInstancePath(current.plan.options.cwd, current.plan.target));
|
|
3482
|
+
if (digest(registry) !== current.plan.registryDigest || snapshotDigest(target) !== current.plan.targetDigest) throw new Error("Template link plan became stale before metadata commit; preview again.");
|
|
3483
|
+
}, { allocateIdOnConflict: true });
|
|
3484
|
+
return {
|
|
3485
|
+
...current.plan,
|
|
3486
|
+
applied: true
|
|
3487
|
+
};
|
|
3488
|
+
}
|
|
3489
|
+
//#endregion
|
|
3490
|
+
//#region src/commands/template-instances/upgrade/current.ts
|
|
3491
|
+
/** Inspect only template-owned candidates; unrelated and explicitly unmanaged business data is not a template snapshot. */
|
|
3492
|
+
async function captureUpgradeTarget(root, paths, excluded = []) {
|
|
3493
|
+
if (!(await fs.stat(root)).isDirectory()) throw new Error("A template upgrade target must be an existing directory.");
|
|
3494
|
+
const snapshot = {
|
|
3495
|
+
schemaVersion: 1,
|
|
3496
|
+
files: [],
|
|
3497
|
+
directories: []
|
|
3498
|
+
};
|
|
3499
|
+
const candidates = new Set(paths);
|
|
3500
|
+
for (const filename of paths) {
|
|
3501
|
+
let parent = filename;
|
|
3502
|
+
while (parent.includes("/")) {
|
|
3503
|
+
parent = parent.slice(0, parent.lastIndexOf("/"));
|
|
3504
|
+
candidates.add(parent);
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
3507
|
+
let bytes = 0;
|
|
3508
|
+
for (const relative of [...candidates].sort()) {
|
|
3509
|
+
if (excluded.some((prefix) => relative === prefix || relative.startsWith(`${prefix}/`))) continue;
|
|
3510
|
+
try {
|
|
3511
|
+
const filename = await safeInstancePath(root, relative);
|
|
3512
|
+
const stat = await fs.lstat(filename);
|
|
3513
|
+
if (stat.isDirectory()) snapshot.directories.push(relative);
|
|
3514
|
+
else if (stat.isFile()) {
|
|
3515
|
+
bytes += stat.size;
|
|
3516
|
+
if (bytes > 33554432) throw new Error("Template-managed upgrade candidates exceed the supported snapshot size. Exclude business-owned paths explicitly.");
|
|
3517
|
+
snapshot.files.push({
|
|
3518
|
+
path: relative,
|
|
3519
|
+
content: (await fs.readFile(filename)).toString("base64"),
|
|
3520
|
+
executable: (stat.mode & 73) !== 0
|
|
3521
|
+
});
|
|
3522
|
+
} else throw new Error(`Unsupported template upgrade file: ${relative}`);
|
|
3523
|
+
} catch (error) {
|
|
3524
|
+
if (!["ENOENT", "ENOTDIR"].includes(error.code ?? "")) throw error;
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
return snapshot;
|
|
3528
|
+
}
|
|
3529
|
+
//#endregion
|
|
3530
|
+
//#region src/commands/template-instances/upgrade/digest.ts
|
|
3531
|
+
const upgradeDigest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
3532
|
+
//#endregion
|
|
3533
|
+
//#region src/commands/template-instances/upgrade/changes.ts
|
|
3534
|
+
function snapshotEntries(snapshot) {
|
|
3535
|
+
const result = /* @__PURE__ */ new Map();
|
|
3536
|
+
for (const directory of snapshot.directories) result.set(directory, { kind: "directory" });
|
|
3537
|
+
for (const file of snapshot.files) result.set(file.path, {
|
|
3538
|
+
kind: "file",
|
|
3539
|
+
content: file.content,
|
|
3540
|
+
executable: file.executable
|
|
3541
|
+
});
|
|
3542
|
+
return result;
|
|
3543
|
+
}
|
|
3544
|
+
function sameEntry(left, right) {
|
|
3545
|
+
if (!left || !right) return left === right;
|
|
3546
|
+
return left.kind === right.kind && (left.kind === "directory" || right.kind === "file" && left.content === right.content && left.executable === right.executable);
|
|
3547
|
+
}
|
|
3548
|
+
function change(filename, base, local, upstream, excluded) {
|
|
3549
|
+
const result = (after, status, reason) => ({
|
|
3550
|
+
path: filename,
|
|
3551
|
+
before: local,
|
|
3552
|
+
after,
|
|
3553
|
+
status,
|
|
3554
|
+
reason
|
|
3555
|
+
});
|
|
3556
|
+
const preserve = (reason) => result(local, "preserved", reason);
|
|
3557
|
+
const conflict = (reason) => result(local, "conflict", reason);
|
|
3558
|
+
const adopt = () => result(upstream, sameEntry(local, upstream) ? "unchanged" : local ? "modify" : "add", "upstream-update");
|
|
3559
|
+
if (excluded) return preserve("excluded-path");
|
|
3560
|
+
if (!base) return !upstream ? preserve("business-file") : !local || sameEntry(local, upstream) ? adopt() : conflict("upstream-addition-collision");
|
|
3561
|
+
if (!local) return preserve("user-deletion-preserved");
|
|
3562
|
+
if (!upstream) {
|
|
3563
|
+
if (base.kind === "directory" && local.kind === "directory") return preserve("directory-preserved");
|
|
3564
|
+
return sameEntry(local, base) ? result(null, "delete", "upstream-file-removed") : conflict("upstream-removal-conflict");
|
|
3565
|
+
}
|
|
3566
|
+
if (sameEntry(base, upstream)) return sameEntry(local, upstream) ? adopt() : preserve("local-changes-preserved");
|
|
3567
|
+
if (local.kind !== upstream.kind || base.kind !== upstream.kind) return conflict("entry-type-conflict");
|
|
3568
|
+
if (sameEntry(local, base) || sameEntry(local, upstream)) return adopt();
|
|
3569
|
+
if (base.kind === "file" && local.kind === "file" && upstream.kind === "file") {
|
|
3570
|
+
const merged = mergeText(Buffer.from(base.content, "base64"), Buffer.from(local.content, "base64"), Buffer.from(upstream.content, "base64"));
|
|
3571
|
+
if (!merged.content) return {
|
|
3572
|
+
...conflict(merged.reason),
|
|
3573
|
+
conflicts: merged.conflicts
|
|
3574
|
+
};
|
|
3575
|
+
const after = {
|
|
3576
|
+
kind: "file",
|
|
3577
|
+
content: merged.content.toString("base64"),
|
|
3578
|
+
executable: local.executable === base.executable ? upstream.executable : local.executable
|
|
3579
|
+
};
|
|
3580
|
+
return result(after, sameEntry(local, after) ? "unchanged" : "modify", merged.reason);
|
|
3581
|
+
}
|
|
3582
|
+
return adopt();
|
|
3583
|
+
}
|
|
3584
|
+
function computeTemplateUpgradeChanges(base, local, upstream, excluded) {
|
|
3585
|
+
const oldEntries = snapshotEntries(base);
|
|
3586
|
+
const current = snapshotEntries(local);
|
|
3587
|
+
const next = snapshotEntries(upstream);
|
|
3588
|
+
const changes = [.../* @__PURE__ */ new Set([...oldEntries.keys(), ...next.keys()])].sort().map((filename) => change(filename, oldEntries.get(filename) ?? null, current.get(filename) ?? null, next.get(filename) ?? null, excluded.some((prefix) => filename === prefix || filename.startsWith(`${prefix}/`))));
|
|
3589
|
+
const byPath = new Map(changes.map((item) => [item.path, item]));
|
|
3590
|
+
const desired = new Map(current);
|
|
3591
|
+
for (const item of changes) desired.set(item.path, item.after);
|
|
3592
|
+
for (const item of changes) {
|
|
3593
|
+
let parent = item.path;
|
|
3594
|
+
while (parent.includes("/")) {
|
|
3595
|
+
parent = parent.slice(0, parent.lastIndexOf("/"));
|
|
3596
|
+
if (item.after && desired.get(parent)?.kind !== "directory") {
|
|
3597
|
+
item.status = oldEntries.has(parent) && !current.has(parent) || byPath.get(parent)?.reason === "user-deletion-preserved" ? "preserved" : "conflict";
|
|
3598
|
+
item.reason = item.status === "preserved" ? "user-deletion-preserved" : "parent-type-conflict";
|
|
3599
|
+
item.after = item.before;
|
|
3600
|
+
desired.set(item.path, item.after);
|
|
3601
|
+
break;
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
return changes;
|
|
3606
|
+
}
|
|
3607
|
+
//#endregion
|
|
3608
|
+
//#region src/commands/template-instances/upgrade/source.ts
|
|
3609
|
+
/** Retain the original generation identity rather than sampling the current machine's Git configuration. */
|
|
3610
|
+
function preserveGenerationMetadata(snapshot, previous, instance) {
|
|
3611
|
+
if (!["repo-new-v1", "repo-new-parameters-v1"].includes(instance.generator.profile)) return snapshot;
|
|
3612
|
+
const filename = instance.parameters.renameJson ? "package.mock.json" : "package.json";
|
|
3613
|
+
const before = previous.files.find((file) => file.path === filename);
|
|
3614
|
+
const after = snapshot.files.find((file) => file.path === filename);
|
|
3615
|
+
if (!before || !after) return snapshot;
|
|
3616
|
+
const original = JSON.parse(Buffer.from(before.content, "base64").toString("utf8"));
|
|
3617
|
+
const next = JSON.parse(Buffer.from(after.content, "base64").toString("utf8"));
|
|
3618
|
+
for (const key of [
|
|
3619
|
+
"author",
|
|
3620
|
+
"bugs",
|
|
3621
|
+
"repository"
|
|
3622
|
+
]) if (Object.hasOwn(original, key)) next[key] = original[key];
|
|
3623
|
+
after.content = Buffer.from(`${JSON.stringify(next, null, 2)}\n`).toString("base64");
|
|
3624
|
+
return snapshot;
|
|
3625
|
+
}
|
|
3626
|
+
async function renderTemplateUpgradeSource(options, instance, previous) {
|
|
3627
|
+
const rendered = await renderHistoricalTemplate({
|
|
3628
|
+
cwd: options.cwd,
|
|
3629
|
+
target: instance.target,
|
|
3630
|
+
template: instance.template,
|
|
3631
|
+
version: options.version,
|
|
3632
|
+
profile: instance.generator.profile,
|
|
3633
|
+
parameters: instance.parameters,
|
|
3634
|
+
...options.exclude ?? instance.excludedPaths ? { excludedPaths: options.exclude ?? instance.excludedPaths } : {},
|
|
3635
|
+
...options.sourceDir ? { sourceDir: options.sourceDir } : {}
|
|
3636
|
+
});
|
|
3637
|
+
if (!rendered) throw new Error("The exact requested template source is unavailable. Supply its extracted package; no instance files were changed.");
|
|
3638
|
+
return {
|
|
3639
|
+
original: rendered.original,
|
|
3640
|
+
rendered: preserveGenerationMetadata(rendered.rendered, previous, instance)
|
|
3641
|
+
};
|
|
3642
|
+
}
|
|
3643
|
+
//#endregion
|
|
3644
|
+
//#region src/commands/template-instances/upgrade/transaction/state.ts
|
|
3645
|
+
async function readUpgradeFileState(root, relative) {
|
|
3646
|
+
const filename = await safeInstancePath(root, relative);
|
|
3647
|
+
try {
|
|
3648
|
+
const stat = await fs.lstat(filename);
|
|
3649
|
+
if (!stat.isFile() && !stat.isDirectory()) throw new Error(`Unsupported template upgrade path: ${relative}`);
|
|
3650
|
+
return {
|
|
3651
|
+
entry: stat.isDirectory() ? { kind: "directory" } : {
|
|
3652
|
+
kind: "file",
|
|
3653
|
+
content: (await fs.readFile(filename)).toString("base64"),
|
|
3654
|
+
executable: (stat.mode & 73) !== 0
|
|
3655
|
+
},
|
|
3656
|
+
mode: stat.mode & 511,
|
|
3657
|
+
atimeMs: stat.atimeMs,
|
|
3658
|
+
mtimeMs: stat.mtimeMs
|
|
3659
|
+
};
|
|
3660
|
+
} catch (error) {
|
|
3661
|
+
if (error.code === "ENOENT") return null;
|
|
3662
|
+
throw error;
|
|
3663
|
+
}
|
|
3664
|
+
}
|
|
3665
|
+
function stateMatches(left, right) {
|
|
3666
|
+
return sameEntry(left?.entry ?? null, right?.entry ?? null) && left?.mode === right?.mode;
|
|
3667
|
+
}
|
|
3668
|
+
function desiredUpgradeState(entry, before) {
|
|
3669
|
+
if (!entry) return null;
|
|
3670
|
+
if (process.platform === "win32") {
|
|
3671
|
+
const normalized = entry.kind === "file" ? {
|
|
3672
|
+
...entry,
|
|
3673
|
+
executable: false
|
|
3674
|
+
} : entry;
|
|
3675
|
+
const now = Date.now();
|
|
3676
|
+
return {
|
|
3677
|
+
entry: normalized,
|
|
3678
|
+
mode: before?.mode ?? 438,
|
|
3679
|
+
atimeMs: now,
|
|
3680
|
+
mtimeMs: now
|
|
3681
|
+
};
|
|
3682
|
+
}
|
|
3683
|
+
let mode = before?.mode ?? (entry.kind === "directory" || entry.executable ? 493 : 420) & ~process.umask();
|
|
3684
|
+
if (entry.kind === "file" && before?.entry.kind === "file" && entry.executable !== before.entry.executable) mode = entry.executable ? mode | (mode & 292) >> 2 | 64 : mode & -74;
|
|
3685
|
+
const now = Date.now();
|
|
3686
|
+
return {
|
|
3687
|
+
entry,
|
|
3688
|
+
mode,
|
|
3689
|
+
atimeMs: now,
|
|
3690
|
+
mtimeMs: now
|
|
3691
|
+
};
|
|
3692
|
+
}
|
|
3693
|
+
function validateUpgradeFileState(state) {
|
|
3694
|
+
if (state === null) return;
|
|
3695
|
+
if (!state || !Number.isInteger(state.mode) || state.mode < 0 || state.mode > 511 || !Number.isFinite(state.atimeMs) || !Number.isFinite(state.mtimeMs) || !state.entry || !["directory", "file"].includes(state.entry.kind)) throw new Error("Invalid template upgrade recovery file metadata.");
|
|
3696
|
+
if (state.entry.kind === "file" && (typeof state.entry.content !== "string" || typeof state.entry.executable !== "boolean" || Buffer.from(state.entry.content, "base64").toString("base64") !== state.entry.content || (state.mode & 73) !== 0 !== state.entry.executable)) throw new Error("Invalid template upgrade recovery file content.");
|
|
3697
|
+
}
|
|
3698
|
+
//#endregion
|
|
3699
|
+
//#region src/commands/template-instances/upgrade/transaction/journal.ts
|
|
3700
|
+
function templateUpgradeJournalPath(instanceId) {
|
|
3701
|
+
if (!/^[a-f0-9]{24}$/u.test(instanceId)) throw new Error("Invalid template instance recovery identity.");
|
|
3702
|
+
return `.repoctl/template-upgrades/${instanceId}.json`;
|
|
3703
|
+
}
|
|
3704
|
+
async function loadTemplateUpgradeJournal(cwd, instanceId) {
|
|
3705
|
+
const filename = await safeInstancePath(cwd, templateUpgradeJournalPath(instanceId));
|
|
3706
|
+
let content;
|
|
3707
|
+
try {
|
|
3708
|
+
content = await fs.readFile(filename, "utf8");
|
|
3709
|
+
} catch (error) {
|
|
3710
|
+
if (error.code === "ENOENT") return;
|
|
3711
|
+
throw error;
|
|
3712
|
+
}
|
|
3713
|
+
const journal = JSON.parse(content);
|
|
3714
|
+
const { digest, ...body } = journal;
|
|
3715
|
+
if (journal.schemaVersion !== 1 || journal.kind !== "template-instance-upgrade" || journal.instanceId !== instanceId || !/^[a-f0-9-]{36}$/u.test(journal.token) || journal.before?.id !== instanceId || journal.after?.id !== instanceId || journal.before.target !== journal.target || journal.after.target !== journal.target || !Array.isArray(journal.operations) || upgradeDigest(body) !== digest) throw new Error(`Invalid template upgrade recovery record: ${filename}`);
|
|
3716
|
+
const root = await safeInstancePath(cwd, journal.target);
|
|
3717
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3718
|
+
for (const operation of journal.operations) {
|
|
3719
|
+
if (!operation || typeof operation.path !== "string" || seen.has(operation.path)) throw new Error("Invalid template upgrade recovery paths.");
|
|
3720
|
+
await safeInstancePath(root, operation.path);
|
|
3721
|
+
seen.add(operation.path);
|
|
3722
|
+
validateUpgradeFileState(operation.before);
|
|
3723
|
+
validateUpgradeFileState(operation.after);
|
|
3724
|
+
if (!operation.before && !operation.after) throw new Error("Invalid empty template upgrade recovery operation.");
|
|
3725
|
+
}
|
|
3726
|
+
return journal;
|
|
3727
|
+
}
|
|
3728
|
+
async function createTemplateUpgradeJournal(plan, before) {
|
|
3729
|
+
const root = await safeInstancePath(plan.options.cwd, plan.target);
|
|
3730
|
+
const operations = [];
|
|
3731
|
+
for (const change of plan.changes.filter((item) => [
|
|
3732
|
+
"add",
|
|
3733
|
+
"modify",
|
|
3734
|
+
"delete"
|
|
3735
|
+
].includes(item.status))) {
|
|
3736
|
+
const state = await readUpgradeFileState(root, change.path);
|
|
3737
|
+
if (!sameEntry(state?.entry ?? null, change.before)) throw new Error(`Template instance changed before its recovery record was created: ${change.path}`);
|
|
3738
|
+
const after = desiredUpgradeState(change.after, state);
|
|
3739
|
+
validateUpgradeFileState(after);
|
|
3740
|
+
operations.push({
|
|
3741
|
+
path: change.path,
|
|
3742
|
+
before: state,
|
|
3743
|
+
after
|
|
3744
|
+
});
|
|
3745
|
+
}
|
|
3746
|
+
const body = {
|
|
3747
|
+
schemaVersion: 1,
|
|
3748
|
+
kind: "template-instance-upgrade",
|
|
3749
|
+
token: randomUUID(),
|
|
3750
|
+
instanceId: before.id,
|
|
3751
|
+
target: before.target,
|
|
3752
|
+
before,
|
|
3753
|
+
after: plan.nextInstance,
|
|
3754
|
+
operations
|
|
3755
|
+
};
|
|
3756
|
+
const journal = {
|
|
3757
|
+
...body,
|
|
3758
|
+
digest: upgradeDigest(body)
|
|
3759
|
+
};
|
|
3760
|
+
const filename = await safeInstancePath(plan.options.cwd, templateUpgradeJournalPath(before.id));
|
|
3761
|
+
await fs.mkdir(path.dirname(filename), { recursive: true });
|
|
3762
|
+
const temporary = `${filename}.${journal.token}.tmp`;
|
|
3763
|
+
let owned = false;
|
|
3764
|
+
try {
|
|
3765
|
+
const handle = await fs.open(temporary, "wx", 384);
|
|
3766
|
+
owned = true;
|
|
3767
|
+
try {
|
|
3768
|
+
await handle.writeFile(`${JSON.stringify(journal)}\n`);
|
|
3769
|
+
await handle.sync();
|
|
3770
|
+
} finally {
|
|
3771
|
+
await handle.close();
|
|
3772
|
+
}
|
|
3773
|
+
await fs.link(temporary, filename);
|
|
3774
|
+
} finally {
|
|
3775
|
+
if (owned) await fs.rm(temporary, { force: true });
|
|
3776
|
+
}
|
|
3777
|
+
return journal;
|
|
3778
|
+
}
|
|
3779
|
+
async function removeTemplateUpgradeJournal(cwd, journal) {
|
|
3780
|
+
const current = await loadTemplateUpgradeJournal(cwd, journal.instanceId);
|
|
3781
|
+
if (!current) return;
|
|
3782
|
+
if (current.token !== journal.token || current.digest !== journal.digest) throw new Error("The template recovery record was replaced; preserve it for its owning operation.");
|
|
3783
|
+
await fs.unlink(await safeInstancePath(cwd, templateUpgradeJournalPath(journal.instanceId)));
|
|
3784
|
+
}
|
|
3785
|
+
//#endregion
|
|
3786
|
+
//#region src/commands/template-instances/upgrade/plan.ts
|
|
3787
|
+
function nextInstance(previous, draft, excludedPaths) {
|
|
3788
|
+
return {
|
|
3789
|
+
...previous,
|
|
3790
|
+
source: draft.source,
|
|
3791
|
+
generator: {
|
|
3792
|
+
...previous.generator,
|
|
3793
|
+
version
|
|
3794
|
+
},
|
|
3795
|
+
baseline: {
|
|
3796
|
+
status: "available",
|
|
3797
|
+
original: snapshotDigest(draft.original),
|
|
3798
|
+
rendered: snapshotDigest(draft.rendered)
|
|
3799
|
+
},
|
|
3800
|
+
...excludedPaths.length ? { excludedPaths } : {}
|
|
3801
|
+
};
|
|
3802
|
+
}
|
|
3803
|
+
async function prepareTemplateUpgrade(input) {
|
|
3804
|
+
if (!isExactTemplateVersion(input.version)) throw new Error("Template upgrades require an exact target package version; floating tags and ranges are not supported.");
|
|
3805
|
+
const cwd = await fs.realpath(path.resolve(input.cwd));
|
|
3806
|
+
const registry = await loadTemplateInstanceRegistry(cwd);
|
|
3807
|
+
const instance = registry.instances.find((item) => item.id === input.instance) ?? registry.instances.find((item) => item.target === instanceRelativePath(cwd, path.resolve(cwd, input.instance)));
|
|
3808
|
+
if (!instance) throw new Error(`Unknown template instance: ${input.instance}`);
|
|
3809
|
+
if (instance.source.kind === "remote") throw new Error("This upgrade command accepts built-in template package versions. Remote source identity and retained baselines are preserved; remote npm/Git upgrades are not supported yet.");
|
|
3810
|
+
if (await loadTemplateUpgradeJournal(cwd, instance.id)) throw new Error(`This instance has a pending template upgrade. Inspect templates recover-upgrade ${instance.id} before starting another upgrade.`);
|
|
3811
|
+
if (instance.baseline.status !== "available") throw new Error("This instance has no reliable historical baseline. Verify its historical source before upgrading.");
|
|
3812
|
+
const original = await loadTemplateBaseline(cwd, instance.baseline.original);
|
|
3813
|
+
const baseline = await loadTemplateBaseline(cwd, instance.baseline.rendered);
|
|
3814
|
+
const excludedPaths = normalizeTemplateExclusions([...instance.excludedPaths ?? [], ...input.exclude ?? []]);
|
|
3815
|
+
const options = {
|
|
3816
|
+
cwd,
|
|
3817
|
+
instance: instance.id,
|
|
3818
|
+
version: input.version,
|
|
3819
|
+
exclude: excludedPaths,
|
|
3820
|
+
...input.sourceDir ? { sourceDir: path.resolve(input.cwd, input.sourceDir) } : {}
|
|
3821
|
+
};
|
|
3822
|
+
const sameVersion = instance.source.kind === "package" && instance.source.version === input.version;
|
|
3823
|
+
const source = sameVersion && !options.sourceDir ? {
|
|
3824
|
+
original: {
|
|
3825
|
+
source: instance.source,
|
|
3826
|
+
snapshot: original
|
|
3827
|
+
},
|
|
3828
|
+
rendered: baseline
|
|
3829
|
+
} : await renderTemplateUpgradeSource(options, instance, baseline);
|
|
3830
|
+
if (sameVersion && snapshotDigest(source.original.snapshot) !== instance.baseline.original) throw new Error("The selected source changed under the same package version. Use an immutable source with its correct version.");
|
|
3831
|
+
if (sameVersion) source.rendered = baseline;
|
|
3832
|
+
const snapshots = {
|
|
3833
|
+
[snapshotDigest(source.original.snapshot)]: source.original.snapshot,
|
|
3834
|
+
[snapshotDigest(source.rendered)]: source.rendered
|
|
3835
|
+
};
|
|
3836
|
+
const next = sameVersion ? {
|
|
3837
|
+
...instance,
|
|
3838
|
+
...excludedPaths.length ? { excludedPaths } : {}
|
|
3839
|
+
} : nextInstance(instance, {
|
|
3840
|
+
source: source.original.source,
|
|
3841
|
+
original: source.original.snapshot,
|
|
3842
|
+
rendered: source.rendered
|
|
3843
|
+
}, excludedPaths);
|
|
3844
|
+
const current = await captureUpgradeTarget(await safeInstancePath(cwd, instance.target), [...snapshotEntries(baseline).keys(), ...snapshotEntries(source.rendered).keys()], excludedPaths);
|
|
3845
|
+
const changes = computeTemplateUpgradeChanges(baseline, current, source.rendered, excludedPaths);
|
|
3846
|
+
const action = changes.some((item) => item.status === "conflict") ? "conflict" : upgradeDigest(next) === upgradeDigest(instance) && !changes.some((item) => [
|
|
3847
|
+
"add",
|
|
3848
|
+
"modify",
|
|
3849
|
+
"delete"
|
|
3850
|
+
].includes(item.status)) ? "unchanged" : "upgrade";
|
|
3851
|
+
const content = {
|
|
3852
|
+
schemaVersion: 1,
|
|
3853
|
+
options,
|
|
3854
|
+
instanceId: instance.id,
|
|
3855
|
+
target: instance.target,
|
|
3856
|
+
source: source.original.source,
|
|
3857
|
+
action,
|
|
3858
|
+
changes,
|
|
3859
|
+
registryDigest: upgradeDigest(registry),
|
|
3860
|
+
targetDigest: snapshotDigest(current),
|
|
3861
|
+
nextInstance: next
|
|
3862
|
+
};
|
|
3863
|
+
return {
|
|
3864
|
+
plan: {
|
|
3865
|
+
...content,
|
|
3866
|
+
fingerprint: upgradeDigest(content)
|
|
3867
|
+
},
|
|
3868
|
+
previous: instance,
|
|
3869
|
+
draft: {
|
|
3870
|
+
instance: next,
|
|
3871
|
+
snapshots
|
|
3872
|
+
}
|
|
3873
|
+
};
|
|
3874
|
+
}
|
|
3875
|
+
async function planTemplateUpgrade(options) {
|
|
3876
|
+
return (await prepareTemplateUpgrade(options)).plan;
|
|
3877
|
+
}
|
|
3878
|
+
//#endregion
|
|
3879
|
+
//#region src/commands/template-instances/upgrade/transaction/files.ts
|
|
3880
|
+
const temporaryPath = (operation, token) => `${operation.path}.repoctl-template-${token}.tmp`;
|
|
3881
|
+
async function removeTemporary(root, operation, token) {
|
|
3882
|
+
const relative = temporaryPath(operation, token);
|
|
3883
|
+
const current = await readUpgradeFileState(root, relative);
|
|
3884
|
+
if (!current) return;
|
|
3885
|
+
if (!stateMatches(current, operation.after)) throw new Error(`Unexpected contents in template transaction temporary file: ${relative}`);
|
|
3886
|
+
await fs.unlink(await safeInstancePath(root, relative));
|
|
3887
|
+
}
|
|
3888
|
+
async function applyUpgradeOperation(root, operation, token) {
|
|
3889
|
+
const target = await safeInstancePath(root, operation.path);
|
|
3890
|
+
if (!stateMatches(await readUpgradeFileState(root, operation.path), operation.before)) throw new Error(`Concurrent template instance change: ${operation.path}`);
|
|
3891
|
+
if (operation.after?.entry.kind === "directory") {
|
|
3892
|
+
if (operation.before) throw new Error(`Directory replacement is not automatic: ${operation.path}`);
|
|
3893
|
+
await fs.mkdir(target, { mode: operation.after.mode });
|
|
3894
|
+
return;
|
|
3895
|
+
}
|
|
3896
|
+
if (!operation.after) {
|
|
3897
|
+
if (operation.before?.entry.kind === "directory") await fs.rmdir(target);
|
|
3898
|
+
else await fs.unlink(target);
|
|
3899
|
+
return;
|
|
3900
|
+
}
|
|
3901
|
+
const temporary = await safeInstancePath(root, temporaryPath(operation, token));
|
|
3902
|
+
await fs.writeFile(temporary, Buffer.from(operation.after.entry.content, "base64"), {
|
|
3903
|
+
flag: "wx",
|
|
3904
|
+
mode: operation.after.mode
|
|
3905
|
+
});
|
|
3906
|
+
await fs.chmod(temporary, operation.after.mode);
|
|
3907
|
+
if (!stateMatches(await readUpgradeFileState(root, operation.path), operation.before)) throw new Error(`Concurrent template instance change: ${operation.path}`);
|
|
3908
|
+
if (operation.before === null) {
|
|
3909
|
+
await fs.link(temporary, target);
|
|
3910
|
+
await fs.unlink(temporary);
|
|
3911
|
+
} else await fs.rename(temporary, target);
|
|
3912
|
+
await fs.utimes(target, operation.after.atimeMs / 1e3, operation.after.mtimeMs / 1e3);
|
|
3913
|
+
}
|
|
3914
|
+
async function restoreUpgradeOperations(root, operations, token) {
|
|
3915
|
+
const failures = [];
|
|
3916
|
+
for (const operation of [...operations].reverse()) try {
|
|
3917
|
+
await removeTemporary(root, operation, token);
|
|
3918
|
+
const inverse = {
|
|
3919
|
+
...operation,
|
|
3920
|
+
before: operation.after,
|
|
3921
|
+
after: operation.before
|
|
3922
|
+
};
|
|
3923
|
+
await removeTemporary(root, inverse, `${token}-restore`);
|
|
3924
|
+
const current = await readUpgradeFileState(root, operation.path);
|
|
3925
|
+
if (stateMatches(current, operation.before)) continue;
|
|
3926
|
+
if (!stateMatches(current, operation.after)) throw new Error("Concurrent business edit must be preserved");
|
|
3927
|
+
await applyUpgradeOperation(root, inverse, `${token}-restore`);
|
|
3928
|
+
} catch {
|
|
3929
|
+
failures.push(operation.path);
|
|
3930
|
+
}
|
|
3931
|
+
if (failures.length) throw new Error(`Template file recovery is incomplete; preserve concurrent changes and the recovery record. Inspect: ${failures.join(", ")}`);
|
|
3932
|
+
}
|
|
3933
|
+
//#endregion
|
|
3934
|
+
//#region src/commands/template-instances/upgrade/apply.ts
|
|
3935
|
+
async function applyTemplateUpgradePlan(plan) {
|
|
3936
|
+
const { fingerprint, ...content } = plan;
|
|
3937
|
+
const current = await prepareTemplateUpgrade(plan.options);
|
|
3938
|
+
if (upgradeDigest(content) !== fingerprint || current.plan.fingerprint !== fingerprint) throw new Error("Template upgrade plan is stale or was edited; preview the current instance again.");
|
|
3939
|
+
if (current.plan.action === "conflict") throw new Error("Template upgrade has unresolved conflicts. Resolve or explicitly exclude those paths before applying.");
|
|
3940
|
+
const result = {
|
|
3941
|
+
schemaVersion: 1,
|
|
3942
|
+
instanceId: current.previous.id,
|
|
3943
|
+
target: current.previous.target
|
|
3944
|
+
};
|
|
3945
|
+
if (current.plan.action === "unchanged") return {
|
|
3946
|
+
...result,
|
|
3947
|
+
status: "unchanged",
|
|
3948
|
+
changed: []
|
|
3949
|
+
};
|
|
3950
|
+
const cwd = current.plan.options.cwd;
|
|
3951
|
+
const root = await safeInstancePath(cwd, current.previous.target);
|
|
3952
|
+
let journal;
|
|
3953
|
+
await replaceTemplateInstance(cwd, current.previous, current.draft, {
|
|
3954
|
+
apply: async () => {
|
|
3955
|
+
if (upgradeDigest(await loadTemplateInstanceRegistry(cwd)) !== current.plan.registryDigest || snapshotDigest(await captureUpgradeTarget(root, current.plan.changes.map((item) => item.path), current.plan.options.exclude)) !== current.plan.targetDigest) throw new Error("Template upgrade plan became stale before the registry lock was acquired; preview again.");
|
|
3956
|
+
journal = await createTemplateUpgradeJournal(current.plan, current.previous);
|
|
3957
|
+
for (const operation of journal.operations) await applyUpgradeOperation(root, operation, journal.token);
|
|
3958
|
+
},
|
|
3959
|
+
rollback: async () => {
|
|
3960
|
+
if (journal) {
|
|
3961
|
+
await restoreUpgradeOperations(root, journal.operations, journal.token);
|
|
3962
|
+
await removeTemplateUpgradeJournal(cwd, journal);
|
|
3963
|
+
}
|
|
3964
|
+
},
|
|
3965
|
+
committed: async () => {
|
|
3966
|
+
if (journal) try {
|
|
3967
|
+
await removeTemplateUpgradeJournal(cwd, journal);
|
|
3968
|
+
} catch (error) {
|
|
3969
|
+
throw new Error(`Template upgrade was applied, but its recovery record could not be removed: ${templateUpgradeJournalPath(current.previous.id)}. Inspect templates recover-upgrade before another update.`, { cause: error });
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
}).catch((error) => {
|
|
3973
|
+
if (error instanceof AggregateError && journal) throw new Error(`Template upgrade failed and recovery is incomplete. Preserve ${templateUpgradeJournalPath(current.previous.id)} and inspect templates recover-upgrade ${current.previous.id}.`, { cause: error });
|
|
3974
|
+
throw error;
|
|
3975
|
+
});
|
|
3976
|
+
return {
|
|
3977
|
+
...result,
|
|
3978
|
+
status: "applied",
|
|
3979
|
+
changed: current.plan.changes.filter((item) => [
|
|
3980
|
+
"add",
|
|
3981
|
+
"modify",
|
|
3982
|
+
"delete"
|
|
3983
|
+
].includes(item.status)).map((item) => item.path)
|
|
3984
|
+
};
|
|
3985
|
+
}
|
|
3986
|
+
//#endregion
|
|
3987
|
+
//#region src/commands/template-instances/upgrade/recover.ts
|
|
3988
|
+
/** Inspect or restore one interrupted operation, retaining every concurrent business edit. */
|
|
3989
|
+
async function recoverTemplateUpgrade(cwd, selector, apply = false) {
|
|
3990
|
+
cwd = await fs.realpath(path.resolve(cwd));
|
|
3991
|
+
const registry = await loadTemplateInstanceRegistry(cwd);
|
|
3992
|
+
const instance = registry.instances.find((item) => item.id === selector) ?? registry.instances.find((item) => item.target === instanceRelativePath(cwd, path.resolve(cwd, selector)));
|
|
3993
|
+
if (!instance) throw new Error(`Unknown template instance: ${selector}`);
|
|
3994
|
+
const journal = await loadTemplateUpgradeJournal(cwd, instance.id);
|
|
3995
|
+
if (!journal) return {
|
|
3996
|
+
schemaVersion: 1,
|
|
3997
|
+
instanceId: instance.id,
|
|
3998
|
+
status: "no-pending-upgrade",
|
|
3999
|
+
applied: false,
|
|
4000
|
+
files: []
|
|
4001
|
+
};
|
|
4002
|
+
const root = await safeInstancePath(cwd, instance.target);
|
|
4003
|
+
const recorded = upgradeDigest(instance);
|
|
4004
|
+
const registryStatus = recorded === upgradeDigest(journal.before) ? "before" : recorded === upgradeDigest(journal.after) ? "after" : "conflict";
|
|
4005
|
+
const inspect = async () => Promise.all(journal.operations.map(async (operation) => {
|
|
4006
|
+
const current = await readUpgradeFileState(root, operation.path);
|
|
4007
|
+
return {
|
|
4008
|
+
path: operation.path,
|
|
4009
|
+
state: stateMatches(current, operation.before) ? "before" : stateMatches(current, operation.after) ? "after" : "conflict"
|
|
4010
|
+
};
|
|
4011
|
+
}));
|
|
4012
|
+
const files = await inspect();
|
|
4013
|
+
const conflict = registryStatus === "conflict" || instance.target !== journal.target || files.some((file) => file.state === "conflict");
|
|
4014
|
+
if (!apply) return {
|
|
4015
|
+
schemaVersion: 1,
|
|
4016
|
+
instanceId: instance.id,
|
|
4017
|
+
status: conflict ? "conflict" : "recoverable",
|
|
4018
|
+
registryStatus,
|
|
4019
|
+
applied: false,
|
|
4020
|
+
files,
|
|
4021
|
+
recoveryPath: templateUpgradeJournalPath(instance.id)
|
|
4022
|
+
};
|
|
4023
|
+
if (conflict) throw new Error(`Template recovery would overwrite concurrent changes. Preserve them and inspect ${templateUpgradeJournalPath(instance.id)} before retrying.`);
|
|
4024
|
+
await replaceTemplateInstance(cwd, instance, {
|
|
4025
|
+
instance: journal.before,
|
|
4026
|
+
snapshots: {}
|
|
4027
|
+
}, {
|
|
4028
|
+
apply: async () => {
|
|
4029
|
+
if ((await loadTemplateUpgradeJournal(cwd, instance.id))?.digest !== journal.digest || (await inspect()).some((file) => file.state === "conflict")) throw new Error("Template recovery state changed; inspect it again before applying.");
|
|
4030
|
+
await restoreUpgradeOperations(root, journal.operations, journal.token);
|
|
4031
|
+
},
|
|
4032
|
+
rollback: async () => {},
|
|
4033
|
+
committed: async () => await removeTemplateUpgradeJournal(cwd, journal)
|
|
4034
|
+
});
|
|
4035
|
+
return {
|
|
4036
|
+
schemaVersion: 1,
|
|
4037
|
+
instanceId: instance.id,
|
|
4038
|
+
status: "recovered",
|
|
4039
|
+
applied: true,
|
|
4040
|
+
files: await inspect()
|
|
4041
|
+
};
|
|
4042
|
+
}
|
|
4043
|
+
//#endregion
|
|
4044
|
+
//#region src/commands/template-instances/index.ts
|
|
4045
|
+
var template_instances_exports = /* @__PURE__ */ __exportAll({
|
|
4046
|
+
applyTemplateLinkPlan: () => applyTemplateLinkPlan,
|
|
4047
|
+
applyTemplateUpgradePlan: () => applyTemplateUpgradePlan,
|
|
4048
|
+
listTemplateInstances: () => listTemplateInstances,
|
|
4049
|
+
loadTemplateBaseline: () => loadTemplateBaseline$1,
|
|
4050
|
+
loadTemplateInstanceRegistry: () => loadTemplateInstanceRegistry$1,
|
|
4051
|
+
planTemplateLink: () => planTemplateLink,
|
|
4052
|
+
planTemplateUpgrade: () => planTemplateUpgrade,
|
|
4053
|
+
rebuildTemplateInstanceBaseline: () => rebuildTemplateInstanceBaseline,
|
|
4054
|
+
recoverTemplateUpgrade: () => recoverTemplateUpgrade,
|
|
4055
|
+
relocateTemplateInstance: () => relocateTemplateInstance
|
|
4056
|
+
});
|
|
4057
|
+
//#endregion
|
|
4058
|
+
//#region src/core/codeowners/block.ts
|
|
4059
|
+
const beginMarker = "# BEGIN repoctl workspace owners";
|
|
4060
|
+
const endMarker = "# END repoctl workspace owners";
|
|
4061
|
+
function mayOverlap(pattern, directory) {
|
|
4062
|
+
if (pattern.startsWith("!") || pattern.includes("[")) return false;
|
|
4063
|
+
const relative = pattern.replace(/^\//u, "");
|
|
4064
|
+
if (!pattern.startsWith("/") && !relative.replace(/\/$/u, "").includes("/") || directory === ".") return true;
|
|
4065
|
+
const wildcard = relative.search(/[?*]/u);
|
|
4066
|
+
if (wildcard >= 0) {
|
|
4067
|
+
const prefix = relative.slice(0, wildcard);
|
|
4068
|
+
return directory.startsWith(prefix) || prefix.startsWith(`${directory}/`);
|
|
4069
|
+
}
|
|
4070
|
+
const fixed = relative.replace(/\/$/u, "");
|
|
4071
|
+
return directory === fixed || directory.startsWith(`${fixed}/`) || fixed.startsWith(`${directory}/`) || fixed === "";
|
|
4072
|
+
}
|
|
4073
|
+
function firstPattern(line) {
|
|
4074
|
+
return /^((?:\\ |\S)+)/u.exec(line.trim())?.[1]?.replaceAll("\\ ", " ");
|
|
4075
|
+
}
|
|
4076
|
+
function updateOwnersBlock(before, packages, diagnostics) {
|
|
4077
|
+
const newline = before.includes("\r\n") ? "\r\n" : "\n";
|
|
4078
|
+
const lines = before.split(/\r?\n/u);
|
|
4079
|
+
const starts = lines.flatMap((line, index) => line === "# BEGIN repoctl workspace owners" ? [index] : []);
|
|
4080
|
+
const ends = lines.flatMap((line, index) => line === "# END repoctl workspace owners" ? [index] : []);
|
|
4081
|
+
if (starts.length > 1 || ends.length > 1 || starts.length !== ends.length || starts.length === 1 && starts[0] >= ends[0]) {
|
|
4082
|
+
diagnostics.push({
|
|
4083
|
+
code: "INVALID_MARKERS",
|
|
4084
|
+
severity: "error",
|
|
4085
|
+
source: "CODEOWNERS",
|
|
4086
|
+
message: "Expected zero or one correctly ordered repoctl managed block."
|
|
4087
|
+
});
|
|
4088
|
+
return before;
|
|
4089
|
+
}
|
|
4090
|
+
const rules = packages.filter((pkg) => pkg.owners.length).sort((a, b) => a.path === "." ? -1 : b.path === "." ? 1 : a.path.localeCompare(b.path)).map((pkg) => `${pkg.path === "." ? "*" : `/${pkg.path.replaceAll(" ", "\\ ")}/`} ${pkg.owners.join(" ")}`);
|
|
4091
|
+
const block = [
|
|
4092
|
+
beginMarker,
|
|
4093
|
+
...rules,
|
|
4094
|
+
endMarker
|
|
4095
|
+
].join(newline);
|
|
4096
|
+
if (!starts.length) return `${before}${before && !before.endsWith("\n") ? newline : ""}${block}${newline}`;
|
|
4097
|
+
const start = starts[0];
|
|
4098
|
+
const end = ends[0];
|
|
4099
|
+
for (let index = end + 1; index < lines.length; index++) {
|
|
4100
|
+
const line = lines[index].trim();
|
|
4101
|
+
if (!line || line.startsWith("#")) continue;
|
|
4102
|
+
const pattern = firstPattern(line);
|
|
4103
|
+
for (const pkg of packages.filter((pkg) => pkg.owners.length)) if (pattern && mayOverlap(pattern, pkg.path)) diagnostics.push({
|
|
4104
|
+
code: "POSSIBLE_SHADOW",
|
|
4105
|
+
severity: "warning",
|
|
4106
|
+
source: pkg.path,
|
|
4107
|
+
line: index + 1,
|
|
4108
|
+
message: `Later rule ${pattern} may override this workspace or its descendants; GitHub uses the last matching rule, including ownerless rules.`
|
|
4109
|
+
});
|
|
4110
|
+
}
|
|
4111
|
+
const offsets = [0, ...[...before.matchAll(/\n/gu)].map((match) => match.index + 1)];
|
|
4112
|
+
return `${before.slice(0, offsets[start])}${block}${before.slice(offsets[end] + 30)}`;
|
|
4113
|
+
}
|
|
4114
|
+
function ownersDiff(file, before, after) {
|
|
4115
|
+
if (before === after) return "";
|
|
4116
|
+
return [
|
|
4117
|
+
`--- ${before === null ? "/dev/null" : file}`,
|
|
4118
|
+
`+++ ${file}`,
|
|
4119
|
+
`@@ -${before === null ? "0,0" : `1,${before.split("\n").length}`} +1,${after.split("\n").length} @@`,
|
|
4120
|
+
...before === null ? [] : before.split("\n").map((line) => `-${line}`),
|
|
4121
|
+
...after.split("\n").map((line) => `+${line}`)
|
|
4122
|
+
].join("\n");
|
|
4123
|
+
}
|
|
4124
|
+
//#endregion
|
|
4125
|
+
//#region src/core/codeowners/files.ts
|
|
4126
|
+
const codeownersPaths = [
|
|
4127
|
+
".github/CODEOWNERS",
|
|
4128
|
+
"CODEOWNERS",
|
|
4129
|
+
"docs/CODEOWNERS"
|
|
4130
|
+
];
|
|
4131
|
+
async function readOptional(file) {
|
|
4132
|
+
try {
|
|
4133
|
+
return await readFile(file, "utf8");
|
|
4134
|
+
} catch (error) {
|
|
4135
|
+
if (error.code === "ENOENT") return null;
|
|
4136
|
+
throw error;
|
|
4137
|
+
}
|
|
4138
|
+
}
|
|
4139
|
+
function hashContent(content) {
|
|
4140
|
+
return content === null ? null : createHash("sha256").update(content).digest("hex");
|
|
4141
|
+
}
|
|
4142
|
+
async function validateOwnersTarget(workspaceDir, file) {
|
|
4143
|
+
const root = await realpath(workspaceDir);
|
|
4144
|
+
const target = path$1.resolve(root, file);
|
|
4145
|
+
const relative = path$1.relative(root, target).replaceAll("\\", "/");
|
|
4146
|
+
if (!codeownersPaths.includes(relative)) throw new Error("Explicitly select .github/CODEOWNERS, CODEOWNERS, or docs/CODEOWNERS inside the workspace.");
|
|
4147
|
+
let current = root;
|
|
4148
|
+
for (const part of relative.split("/")) {
|
|
4149
|
+
current = path$1.join(current, part);
|
|
4150
|
+
try {
|
|
4151
|
+
const stat = await lstat(current);
|
|
4152
|
+
if (stat.isSymbolicLink() || (current === target ? !stat.isFile() || stat.nlink !== 1 : !stat.isDirectory())) throw new Error(`Refusing unsafe CODEOWNERS path: ${current}`);
|
|
4153
|
+
} catch (error) {
|
|
4154
|
+
if (error.code !== "ENOENT") throw error;
|
|
4155
|
+
}
|
|
4156
|
+
}
|
|
4157
|
+
return target;
|
|
4158
|
+
}
|
|
4159
|
+
async function replaceOwnersFile(workspaceDir, file, before, after) {
|
|
4160
|
+
const target = await validateOwnersTarget(workspaceDir, file);
|
|
4161
|
+
const parent = path$1.dirname(target);
|
|
4162
|
+
await mkdir(parent, { recursive: true });
|
|
4163
|
+
const temp = path$1.join(parent, `.repoctl-codeowners-${randomUUID()}.tmp`);
|
|
4164
|
+
try {
|
|
4165
|
+
const mode = before === null ? 420 : (await lstat(target)).mode;
|
|
4166
|
+
const handle = await open(temp, "wx", mode);
|
|
4167
|
+
try {
|
|
4168
|
+
await handle.writeFile(after, "utf8");
|
|
4169
|
+
await handle.sync();
|
|
4170
|
+
} finally {
|
|
4171
|
+
await handle.close();
|
|
4172
|
+
}
|
|
4173
|
+
await validateOwnersTarget(workspaceDir, file);
|
|
4174
|
+
if (await readOptional(target) !== before) throw new Error("CODEOWNERS changed after preview; regenerate the plan.");
|
|
4175
|
+
await rename(temp, target);
|
|
4176
|
+
} finally {
|
|
4177
|
+
await rm(temp, { force: true });
|
|
4178
|
+
}
|
|
4179
|
+
}
|
|
4180
|
+
//#endregion
|
|
4181
|
+
//#region src/core/codeowners/ownership.ts
|
|
4182
|
+
const ownerPattern = /^(?:@[a-z\d](?:[a-z\d-]*[a-z\d])?(?:\/[a-z\d](?:[\w-]*[a-z\d])?)?|[^\s@#]+@[^\s#@][^\s#.@]*\.[^\s#@]+)$/iu;
|
|
4183
|
+
async function inspectWorkspaceOwners(options) {
|
|
4184
|
+
clearWorkspaceCache();
|
|
4185
|
+
const { workspaceDir, packages } = await getWorkspaceData(await realpath(options.cwd), {
|
|
4186
|
+
ignorePrivatePackage: false,
|
|
4187
|
+
ignoreRootPackage: false
|
|
4188
|
+
});
|
|
4189
|
+
const report = {
|
|
4190
|
+
schemaVersion: 1,
|
|
4191
|
+
workspaceDir,
|
|
4192
|
+
configFile: null,
|
|
4193
|
+
configFiles: [],
|
|
4194
|
+
packages: [],
|
|
4195
|
+
diagnostics: []
|
|
4196
|
+
};
|
|
4197
|
+
const records = packages.map((pkg) => ({
|
|
4198
|
+
path: path$1.relative(workspaceDir, pkg.rootDir).replaceAll("\\", "/") || ".",
|
|
4199
|
+
...pkg.manifest.name ? { name: pkg.manifest.name } : {},
|
|
4200
|
+
private: pkg.manifest.private === true,
|
|
4201
|
+
owners: [],
|
|
4202
|
+
sources: []
|
|
4203
|
+
}));
|
|
4204
|
+
const loaded = await loadMonorepoConfigDetails(workspaceDir, { refresh: true }).catch((error) => {
|
|
4205
|
+
if (!(error instanceof ConfigValidationError)) throw error;
|
|
4206
|
+
report.diagnostics.push(...error.diagnostics.map((item) => ({
|
|
4207
|
+
code: "INVALID_CONFIG",
|
|
4208
|
+
severity: "error",
|
|
4209
|
+
source: item.path,
|
|
4210
|
+
message: `${item.id}: ${item.suggestion}`
|
|
4211
|
+
})));
|
|
4212
|
+
return null;
|
|
4213
|
+
});
|
|
4214
|
+
if (!loaded) {
|
|
4215
|
+
report.packages = records.filter((pkg) => pkg.path !== ".").sort((a, b) => a.path.localeCompare(b.path));
|
|
4216
|
+
return report;
|
|
4217
|
+
}
|
|
4218
|
+
report.configFile = loaded.file;
|
|
4219
|
+
report.configFiles = loaded.files;
|
|
4220
|
+
const config = loaded.config.codeowners;
|
|
4221
|
+
const mappings = config?.owners ?? {};
|
|
4222
|
+
if (config !== void 0 && (!config || typeof config !== "object" || Array.isArray(config) || config.owners === void 0) || !mappings || typeof mappings !== "object" || Array.isArray(mappings)) report.diagnostics.push({
|
|
4223
|
+
code: "INVALID_CONFIG",
|
|
4224
|
+
severity: "error",
|
|
4225
|
+
source: "codeowners.owners",
|
|
4226
|
+
message: "Expected an object mapping exact workspace names or paths to owner arrays."
|
|
4227
|
+
});
|
|
4228
|
+
else for (const [key, value] of Object.entries(mappings).sort(([a], [b]) => a.localeCompare(b))) {
|
|
4229
|
+
const source = `codeowners.owners[${JSON.stringify(key)}]`;
|
|
4230
|
+
const matches = records.filter((pkg) => pkg.name === key || pkg.path === key.replace(/^\.\//u, "").replace(/\/$/u, ""));
|
|
4231
|
+
if (matches.length !== 1) {
|
|
4232
|
+
report.diagnostics.push({
|
|
4233
|
+
code: matches.length ? "AMBIGUOUS_WORKSPACE" : "UNKNOWN_WORKSPACE",
|
|
4234
|
+
severity: "error",
|
|
4235
|
+
source,
|
|
4236
|
+
message: `Expected one workspace for ${key}; found ${matches.length}.`
|
|
4237
|
+
});
|
|
4238
|
+
continue;
|
|
4239
|
+
}
|
|
4240
|
+
const pkg = matches[0];
|
|
4241
|
+
pkg.sources.push(source);
|
|
4242
|
+
if (!Array.isArray(value) || !value.length || value.some((owner) => typeof owner !== "string" || /\s/u.test(owner) || !ownerPattern.test(owner))) {
|
|
4243
|
+
report.diagnostics.push({
|
|
4244
|
+
code: "INVALID_OWNER",
|
|
4245
|
+
severity: "error",
|
|
4246
|
+
source,
|
|
4247
|
+
message: "Use a nonempty array of @user, @org/team, or email owners; identities are not verified remotely."
|
|
4248
|
+
});
|
|
4249
|
+
continue;
|
|
4250
|
+
}
|
|
4251
|
+
pkg.owners = [.../* @__PURE__ */ new Set([...pkg.owners, ...value])].sort();
|
|
4252
|
+
}
|
|
4253
|
+
report.packages = records.filter((pkg) => pkg.path !== "." || pkg.sources.length > 0).sort((a, b) => a.path.localeCompare(b.path));
|
|
4254
|
+
for (const pkg of report.packages) {
|
|
4255
|
+
if (!pkg.owners.length) report.diagnostics.push({
|
|
4256
|
+
code: "MISSING_OWNER",
|
|
4257
|
+
severity: "warning",
|
|
4258
|
+
source: pkg.path,
|
|
4259
|
+
message: `No owner is configured for ${pkg.name ?? pkg.path}.`
|
|
4260
|
+
});
|
|
4261
|
+
if (pkg.path.startsWith("../") || /[\n\r\t*?[\]\\#]/u.test(pkg.path)) report.diagnostics.push({
|
|
4262
|
+
code: "UNSUPPORTED_PATH",
|
|
4263
|
+
severity: "error",
|
|
4264
|
+
source: pkg.path,
|
|
4265
|
+
message: "This workspace path cannot be represented safely as a literal CODEOWNERS directory rule."
|
|
4266
|
+
});
|
|
4267
|
+
}
|
|
4268
|
+
if (options.query) report.packages = report.packages.filter((pkg) => pkg.name === options.query || pkg.path === options.query);
|
|
4269
|
+
return report;
|
|
4270
|
+
}
|
|
4271
|
+
//#endregion
|
|
4272
|
+
//#region src/core/codeowners/index.ts
|
|
4273
|
+
/** Read-only preview; the output file must be explicitly selected. */
|
|
4274
|
+
async function planCodeowners(options) {
|
|
4275
|
+
const report = await inspectWorkspaceOwners(options);
|
|
4276
|
+
const { workspaceDir } = report;
|
|
4277
|
+
const target = await validateOwnersTarget(workspaceDir, options.file);
|
|
4278
|
+
const file = path$1.relative(workspaceDir, target).replaceAll("\\", "/");
|
|
4279
|
+
const before = await readOptional(target);
|
|
4280
|
+
const after = updateOwnersBlock(before ?? "", report.packages, report.diagnostics);
|
|
4281
|
+
const paths = [
|
|
4282
|
+
...report.configFiles,
|
|
4283
|
+
...codeownersPaths.slice(0, codeownersPaths.indexOf(file)).map((file) => path$1.join(workspaceDir, file)),
|
|
4284
|
+
...getRepoctlConfigCandidates(workspaceDir),
|
|
4285
|
+
path$1.join(workspaceDir, "pnpm-workspace.yaml"),
|
|
4286
|
+
path$1.join(workspaceDir, "package.json"),
|
|
4287
|
+
...report.packages.map((pkg) => path$1.join(workspaceDir, pkg.path, "package.json"))
|
|
4288
|
+
];
|
|
4289
|
+
const inputs = {};
|
|
4290
|
+
for (const input of [...new Set(paths)].sort()) inputs[path$1.relative(workspaceDir, input).replaceAll("\\", "/")] = hashContent(await readOptional(input));
|
|
4291
|
+
for (const preferred of codeownersPaths.slice(0, codeownersPaths.indexOf(file))) if (await readOptional(path$1.join(workspaceDir, preferred)) !== null) {
|
|
4292
|
+
report.diagnostics.push({
|
|
4293
|
+
code: "INACTIVE_FILE",
|
|
4294
|
+
severity: "warning",
|
|
4295
|
+
source: file,
|
|
4296
|
+
message: `GitHub selects ${preferred} before ${file}; this output may not be the active ownership file.`
|
|
4297
|
+
});
|
|
4298
|
+
break;
|
|
4299
|
+
}
|
|
4300
|
+
return {
|
|
4301
|
+
...report,
|
|
4302
|
+
file,
|
|
4303
|
+
before,
|
|
4304
|
+
after,
|
|
4305
|
+
diff: ownersDiff(file, before, after),
|
|
4306
|
+
changed: before !== after,
|
|
4307
|
+
inputs
|
|
4308
|
+
};
|
|
4309
|
+
}
|
|
4310
|
+
/** Recompute the preview and reject changed inputs before atomically replacing one file. */
|
|
4311
|
+
async function applyCodeownersPlan(plan) {
|
|
4312
|
+
if (plan.schemaVersion !== 1) throw new Error("Unsupported CODEOWNERS plan schema.");
|
|
4313
|
+
const fresh = await planCodeowners({
|
|
4314
|
+
cwd: plan.workspaceDir,
|
|
4315
|
+
file: plan.file
|
|
4316
|
+
});
|
|
4317
|
+
if (fresh.diagnostics.some((item) => item.severity === "error") || plan.diagnostics.some((item) => item.severity === "error")) throw new Error("Resolve CODEOWNERS errors before applying the plan.");
|
|
4318
|
+
if (JSON.stringify(fresh.inputs) !== JSON.stringify(plan.inputs) || JSON.stringify(fresh.packages) !== JSON.stringify(plan.packages) || fresh.after !== plan.after) throw new Error("CODEOWNERS inputs or generated content changed; regenerate the plan.");
|
|
4319
|
+
if (fresh.before === plan.after) return {
|
|
4320
|
+
status: "unchanged",
|
|
4321
|
+
file: fresh.file
|
|
4322
|
+
};
|
|
4323
|
+
if (fresh.before !== plan.before) throw new Error("CODEOWNERS changed after preview; regenerate the plan.");
|
|
4324
|
+
await replaceOwnersFile(fresh.workspaceDir, fresh.file, fresh.before, fresh.after);
|
|
4325
|
+
return {
|
|
4326
|
+
status: "applied",
|
|
4327
|
+
file: fresh.file
|
|
4328
|
+
};
|
|
4329
|
+
}
|
|
4330
|
+
//#endregion
|
|
4331
|
+
//#region src/core/workspace-tasks/location.ts
|
|
4332
|
+
/** Absolute directory queries never fall through to package-name fuzzy search. */
|
|
4333
|
+
async function locationCandidates(packages, query) {
|
|
4334
|
+
const normalizedPath = path.normalize(query);
|
|
4335
|
+
const normalized = normalizedPath.length > path.parse(normalizedPath).root.length ? normalizedPath.replace(/\/$/u, "") : normalizedPath;
|
|
4336
|
+
if (path.isAbsolute(normalized) || /^[a-z]:/iu.test(query)) {
|
|
4337
|
+
if (!path$1.isAbsolute(query)) return [];
|
|
4338
|
+
let directory;
|
|
4339
|
+
try {
|
|
4340
|
+
directory = path.normalize(await realpath(query));
|
|
4341
|
+
} catch (error) {
|
|
4342
|
+
if ([
|
|
4343
|
+
"ENOENT",
|
|
4344
|
+
"ENOTDIR",
|
|
4345
|
+
"EINVAL"
|
|
4346
|
+
].includes(error.code ?? "")) return [];
|
|
4347
|
+
throw error;
|
|
4348
|
+
}
|
|
4349
|
+
return packages.filter((pkg) => path.normalize(pkg.directory) === directory);
|
|
4350
|
+
}
|
|
4351
|
+
const relative = normalized.replace(/^\.\//u, "") || ".";
|
|
4352
|
+
const exact = packages.filter((pkg) => pkg.name === query || pkg.id === relative);
|
|
4353
|
+
const lower = query.toLowerCase();
|
|
4354
|
+
return exact.length ? exact : packages.filter((pkg) => [
|
|
4355
|
+
pkg.id,
|
|
4356
|
+
pkg.name,
|
|
4357
|
+
pkg.description
|
|
4358
|
+
].some((value) => value?.toLowerCase().includes(lower)));
|
|
4359
|
+
}
|
|
4360
|
+
//#endregion
|
|
4361
|
+
//#region src/core/workspace-tasks/index.ts
|
|
4362
|
+
function order(left, right) {
|
|
4363
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
4364
|
+
}
|
|
4365
|
+
/** Discover script capabilities; commands remain data and are never executed. */
|
|
4366
|
+
async function getWorkspaceTaskCatalog(cwd, options = {}) {
|
|
4367
|
+
if (options.script !== void 0 && !options.script.trim()) throw new Error("A nonempty script name is required.");
|
|
4368
|
+
clearWorkspaceCache();
|
|
4369
|
+
const data = await getWorkspaceData(cwd, {
|
|
4370
|
+
ignoreRootPackage: false,
|
|
4371
|
+
ignorePrivatePackage: false
|
|
4372
|
+
});
|
|
4373
|
+
const result = {
|
|
4374
|
+
schemaVersion: 1,
|
|
4375
|
+
workspaceDir: data.workspaceDir,
|
|
4376
|
+
packages: [],
|
|
4377
|
+
excluded: []
|
|
4378
|
+
};
|
|
4379
|
+
const query = options.query?.toLowerCase();
|
|
4380
|
+
for (const pkg of data.packages) {
|
|
4381
|
+
const id = path.relative(data.workspaceDir, pkg.rootDir) || ".";
|
|
4382
|
+
const scripts = pkg.manifest.scripts ?? {};
|
|
4383
|
+
const tasks = Object.entries(scripts).filter((entry) => typeof entry[1] === "string" && !!entry[1].trim()).sort(([a], [b]) => order(a, b)).map(([name, command]) => ({
|
|
4384
|
+
name,
|
|
4385
|
+
command,
|
|
4386
|
+
invocation: {
|
|
4387
|
+
executable: "pnpm",
|
|
4388
|
+
args: [
|
|
4389
|
+
"--dir",
|
|
4390
|
+
pkg.rootDir,
|
|
4391
|
+
"run",
|
|
4392
|
+
name
|
|
4393
|
+
]
|
|
4394
|
+
}
|
|
4395
|
+
}));
|
|
4396
|
+
const summary = {
|
|
4397
|
+
id,
|
|
4398
|
+
...pkg.manifest.name ? { name: pkg.manifest.name } : {},
|
|
4399
|
+
...pkg.manifest.description ? { description: pkg.manifest.description } : {},
|
|
4400
|
+
directory: pkg.rootDir,
|
|
4401
|
+
private: pkg.manifest.private === true,
|
|
4402
|
+
root: id === ".",
|
|
4403
|
+
tasks
|
|
4404
|
+
};
|
|
4405
|
+
const reason = options.includePrivate === false && summary.private ? "private_package" : options.includeRoot === false && summary.root ? "root_package" : query && ![
|
|
4406
|
+
id,
|
|
4407
|
+
summary.name,
|
|
4408
|
+
summary.description,
|
|
4409
|
+
...tasks.map((task) => task.name)
|
|
4410
|
+
].some((value) => value?.toLowerCase().includes(query)) ? "query_mismatch" : options.script && !tasks.some((task) => task.name === options.script) ? "missing_script" : void 0;
|
|
4411
|
+
if (reason) result.excluded.push({
|
|
4412
|
+
id,
|
|
4413
|
+
reason
|
|
4414
|
+
});
|
|
4415
|
+
else result.packages.push(summary);
|
|
4416
|
+
}
|
|
4417
|
+
result.packages.sort((a, b) => order(a.id, b.id));
|
|
4418
|
+
result.excluded.sort((a, b) => order(a.id, b.id));
|
|
4419
|
+
return result;
|
|
4420
|
+
}
|
|
4421
|
+
/** Prefer exact names/paths, then literal fuzzy search; never silently choose a candidate. */
|
|
4422
|
+
async function locateWorkspace(cwd, query) {
|
|
4423
|
+
if (!query.trim()) throw new Error("A nonempty workspace query is required.");
|
|
4424
|
+
const catalog = await getWorkspaceTaskCatalog(cwd);
|
|
4425
|
+
const candidates = await locationCandidates(catalog.packages, query);
|
|
4426
|
+
return {
|
|
4427
|
+
schemaVersion: 1,
|
|
4428
|
+
workspaceDir: catalog.workspaceDir,
|
|
4429
|
+
query,
|
|
4430
|
+
status: candidates.length === 1 ? "found" : candidates.length ? "ambiguous" : "not_found",
|
|
4431
|
+
candidates
|
|
4432
|
+
};
|
|
4433
|
+
}
|
|
4434
|
+
//#endregion
|
|
4435
|
+
export { WorkspaceGraphQueryError as $, referenceTarget as A, exists$1 as At, saveKnipBaseline as B, writeJSON as Bt, loadCompiler as C, message as Ct, ownershipFile as D, copy as Dt, exists as E, supportedLocales as Et, env_cache_exports as F, outputJson as Ft, cache_exports as G, getWorkspacePackages as Gt, signalExitCode as H, clearWorkspaceCache as Ht, getKnipConfigurationSuggestions as I, pathExists as It, getWorkspaceGraph as J, mergeText as K, workspace_exports as Kt, knip_exports as L, readJSON as Lt, formatEnvironmentCache as M, isIgnorableFsError as Mt, format_exports as N, outputFile as Nt, readText as O, ensureDir as Ot, checkEnvironmentCache as P, outputJSON as Pt, whyWorkspaceDependency as Q, planKnipCheck as R, readJson as Rt, configReader as S, localize as St, compare$1 as T, resolveRepoctlLocale as Tt, stopCheckProcessTree as U, getWorkspaceData as Ut, executeCheckTask as V, writeJson as Vt, analyzeTurboRuns as W, getWorkspacePackageSummaries as Wt, filterWorkspaceGraph as X, parseDependencyReference as Y, getWorkspaceImpact as Z, planTemplateLink as _, assetsDir$1 as _t, inspectWorkspaceOwners as a, record$2 as at, planGenerate as b, rootDir as bt, loadTemplateInstanceRegistry$1 as c, renderCreateNewProject as ct, template_instances_exports as d, migrateLegacyToolingReferences as dt, compareGraphValues as et, recoverTemplateUpgrade as f, setByPath as ft, applyTemplateLinkPlan as g, validateCleanTargets as gt, loadTemplateUpgradeJournal as h, isWithin as ht, planCodeowners as i, readInput as it, relativeFile as j, fs$2 as jt, referencePath as k, ensureFile as kt, rebuildTemplateInstanceBaseline as l, rewriteTemplateSnapshotReferences as lt, planTemplateUpgrade as m, assertSafePath as mt, locateWorkspace as n, workspaceDependencyTypes as nt, listTemplateInstances as o, safeFile as ot, applyTemplateUpgradePlan as p, stageFileTransaction as pt, withOperationLock as q, GitClient as qt, applyCodeownersPlan as r, hash as rt, loadTemplateBaseline$1 as s, updateManifest as st, getWorkspaceTaskCatalog as t, resolveWorkspaceGraphNode as tt, relocateTemplateInstance as u, hasLegacyToolingReference as ut, generate_exports as v, cliName as vt, validateGraph as w, repoctlLocale as wt, generators as x, templatesDir as xt, applyGeneratePlan as y, packageDir$1 as yt, runKnipCheck as z, remove as zt };
|