@infly/libs 2.4.2 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -71,18 +71,6 @@ function runShellCommand(command, label, cwd) {
71
71
  run(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", command], label, cwd);
72
72
  }
73
73
 
74
- function runShellCommandAsync(command, label, cwd) {
75
- if (/[\r\n&|<>^]/.test(command)) {
76
- throw new Error(`${label}包含不安全的 Windows shell 字符`);
77
- }
78
- return runAsync(
79
- process.env.ComSpec || "cmd.exe",
80
- ["/d", "/s", "/c", command],
81
- label,
82
- cwd
83
- );
84
- }
85
-
86
74
  function buildPnpmScriptSpawn(scriptName) {
87
75
  if (!SAFE_SCRIPT_NAME.test(scriptName)) {
88
76
  throw new Error(`dockerRelease.checks 包含非法脚本名: ${scriptName}`);
@@ -102,11 +90,6 @@ function buildPnpmScriptSpawn(scriptName) {
102
90
  return { command: "pnpm", args: ["run", scriptName], label };
103
91
  }
104
92
 
105
- function runPnpmScript(scriptName, cwd) {
106
- const { command, args, label } = buildPnpmScriptSpawn(scriptName);
107
- run(command, args, label, cwd);
108
- }
109
-
110
93
  async function runPnpmScriptAsync(scriptName, cwd) {
111
94
  const { command, args, label } = buildPnpmScriptSpawn(scriptName);
112
95
  return runAsync(command, args, label, cwd);
@@ -116,11 +99,9 @@ async function runProjectChecks(scriptNames, cwd) {
116
99
  const results = await Promise.allSettled(
117
100
  scriptNames.map((scriptName) => runPnpmScriptAsync(scriptName, cwd))
118
101
  );
119
- const failures = results
120
- .map((result, index) => ({ result, scriptName: scriptNames[index] }))
121
- .filter(({ result }) => result.status === "rejected");
102
+ const failures = results.filter((result) => result.status === "rejected");
122
103
  if (failures.length === 0) return;
123
- const lines = failures.map(({ result }) => ` - ${result.reason.message}`);
104
+ const lines = failures.map(({ reason }) => ` - ${reason.message}`);
124
105
  throw new Error(
125
106
  `项目检查未全部通过(失败 ${failures.length}/${scriptNames.length}):\n${lines.join("\n")}`
126
107
  );
@@ -0,0 +1,22 @@
1
+ const { createHash, randomBytes } = require("node:crypto");
2
+
3
+ function createReleaseId(commit, token = randomBytes(6).toString("hex")) {
4
+ if (!/^[0-9a-f]{40}$/.test(commit) || !/^[0-9a-f]{12}$/.test(token)) throw new Error("发布标识必须包含完整业务提交及 12 位随机标识");
5
+ return `${commit}-r${token}`;
6
+ }
7
+
8
+ function createBuildProvenance({ releaseId, component, businessRevision, workspaceRevision = null,
9
+ configurationRevision = null, workspaceRemote = null, platform, mode, target, buildArgs = {} }) {
10
+ return { schemaVersion: 1, releaseId, component, businessRevision, workspaceRevision,
11
+ configurationRevision, workspaceRemote, platform, mode, target,
12
+ // 不把构建参数值写入来源记录,避免将使用方的私有配置带入日志或发布清单。
13
+ buildArgsSha256: createHash("sha256").update(JSON.stringify(Object.entries(buildArgs).sort(([a], [b]) => a.localeCompare(b)))).digest("hex") };
14
+ }
15
+
16
+ function readRegistryDigest(capture, image) {
17
+ const manifest = JSON.parse(capture("docker", ["buildx", "imagetools", "inspect", "--format", "{{json .Manifest}}", image]));
18
+ if (!/^sha256:[0-9a-f]{64}$/.test(manifest.digest || "")) throw new Error("Registry 没有返回合法的镜像 digest");
19
+ return manifest.digest;
20
+ }
21
+
22
+ module.exports = { createReleaseId, createBuildProvenance, readRegistryDigest };
@@ -11,39 +11,21 @@ function detectReleaseContext({
11
11
  const resolvedProjectDir = path.resolve(projectDir);
12
12
  const projectGitRoot = resolveGitWorktreeRoot(resolvedProjectDir);
13
13
 
14
- if (standalone) {
15
- if (resolvedProjectDir !== projectGitRoot) {
16
- throw new Error("--standalone 必须在当前 Git 仓库根目录执行");
17
- }
18
- return {
19
- mode: "standalone",
20
- isStandalone: true,
21
- contextRoot: resolvedProjectDir,
22
- projectDir: resolvedProjectDir,
23
- projectRelativeDir: ".",
24
- };
14
+ if (standalone && resolvedProjectDir !== projectGitRoot) {
15
+ throw new Error("--standalone 必须在当前 Git 仓库根目录执行");
25
16
  }
26
17
 
27
- const outerWorkspaceRoot = findOuterWorkspaceRoot(projectGitRoot);
28
- if (outerWorkspaceRoot) {
29
- return {
30
- mode: "monorepo",
31
- isStandalone: false,
32
- contextRoot: outerWorkspaceRoot,
33
- projectDir: resolvedProjectDir,
34
- projectRelativeDir: path.relative(outerWorkspaceRoot, resolvedProjectDir).split(path.sep).join("/"),
35
- };
36
- }
37
-
38
- const isStandalone = resolvedProjectDir === projectGitRoot;
18
+ const workspaceRoot = standalone ? null : findOuterWorkspaceRoot(projectGitRoot);
19
+ const contextRoot = workspaceRoot || projectGitRoot;
20
+ const isStandalone = !workspaceRoot && resolvedProjectDir === projectGitRoot;
39
21
  return {
40
22
  mode: isStandalone ? "standalone" : "monorepo",
41
23
  isStandalone,
42
- contextRoot: isStandalone ? resolvedProjectDir : projectGitRoot,
24
+ contextRoot,
43
25
  projectDir: resolvedProjectDir,
44
26
  projectRelativeDir: isStandalone
45
27
  ? "."
46
- : path.relative(projectGitRoot, resolvedProjectDir).split(path.sep).join("/"),
28
+ : path.relative(contextRoot, resolvedProjectDir).split(path.sep).join("/"),
47
29
  };
48
30
  }
49
31
 
@@ -0,0 +1,30 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ function inside(root, relative) {
5
+ if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
6
+ const result = path.resolve(root, relative);
7
+ const offset = path.relative(root, result);
8
+ if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
9
+ return result;
10
+ }
11
+
12
+ function confinedPath(root, relative, io = fs) {
13
+ const candidate = inside(root, relative);
14
+ let existing = candidate;
15
+ while (existing !== root && !io.existsSync(existing)) {
16
+ if (io.lstatSync) {
17
+ try {
18
+ if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
19
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
20
+ }
21
+ existing = path.dirname(existing);
22
+ }
23
+ if (io.realpathSync && io.existsSync(existing)) {
24
+ const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
25
+ if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
26
+ }
27
+ return candidate;
28
+ }
29
+
30
+ module.exports = { inside, confinedPath };
@@ -0,0 +1,204 @@
1
+ const path = require("node:path");
2
+ const { inside } = require("./release-paths");
3
+ const { normalizeMonorepoContextFiles } = require("./minimal-context");
4
+
5
+ function normalizeSourceDirectories(value, name) {
6
+ const directories = Array.isArray(value) ? value : [value];
7
+ if (!directories.length || directories.some((item) => typeof item !== "string" || !item.trim())) {
8
+ throw new Error(`${name} source.directory 必须是非空路径字符串或非空路径数组`);
9
+ }
10
+ return [...new Set(directories.map((item) => item.trim()))];
11
+ }
12
+
13
+ function resolveSourceDirectories(projectDir, value, name) {
14
+ return normalizeSourceDirectories(value, name).map((directory) => path.resolve(projectDir, directory));
15
+ }
16
+
17
+ const SAFE_GIT_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
18
+ const SAFE_DOCKER_PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9._-]+)?$/;
19
+ const SAFE_VERSION_REQUIREMENT = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
20
+ const PRE_BUILD_MODES = new Set(["always", "monorepo", "standalone"]);
21
+ const BUILD_STRATEGIES = new Set(["artifact", "source"]);
22
+
23
+ function normalizePreBuildCommand(value, target) {
24
+ const entry = Array.isArray(value) ? { command: value, when: "always" } : value;
25
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
26
+ || !Array.isArray(entry.command) || entry.command.length === 0
27
+ || entry.command.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg))
28
+ || (entry.when != null && !PRE_BUILD_MODES.has(entry.when))) {
29
+ throw new Error(`${target} preBuild 必须是命令参数数组,或包含 command 与合法 when 的对象`);
30
+ }
31
+ return { command: entry.command, when: entry.when || "always" };
32
+ }
33
+
34
+ function compareVersions(actual, required) {
35
+ const actualMatch = String(actual).trim().replace(/^v/, "").match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
36
+ const requiredMatch = String(required).match(SAFE_VERSION_REQUIREMENT);
37
+ if (!actualMatch || !requiredMatch) return false;
38
+ for (let index = 1; index <= 3; index++) {
39
+ const left = Number(actualMatch[index] || 0);
40
+ const right = Number(requiredMatch[index] || 0);
41
+ if (left !== right) return left > right;
42
+ }
43
+ return true;
44
+ }
45
+
46
+ function validateReleaseProfile(profile, target) {
47
+ const instructions = profile.deployment?.instructions;
48
+ if (instructions != null && (!Array.isArray(instructions)
49
+ || instructions.some((line) => typeof line !== "string" || !line.trim()))) {
50
+ throw new Error(`${target} deployment.instructions 必须是非空文本组成的列表`);
51
+ }
52
+ if (profile.recordConfigurationRevision != null && typeof profile.recordConfigurationRevision !== "boolean") {
53
+ throw new Error(`${target} recordConfigurationRevision 必须是布尔值`);
54
+ }
55
+ if (profile.pushBranch != null && (typeof profile.pushBranch !== "string"
56
+ || !SAFE_GIT_NAME.test(profile.pushBranch) || profile.pushBranch.startsWith("-")
57
+ || profile.pushBranch.includes(".."))) {
58
+ throw new Error(`${target} pushBranch 必须是合法 Git 分支名`);
59
+ }
60
+ if (profile.pushRef != null && (typeof profile.pushRef !== "string"
61
+ || !SAFE_GIT_NAME.test(profile.pushRef) || profile.pushRef.startsWith("-")
62
+ || profile.pushRef.includes("..") || !profile.pushRef.includes("/"))) {
63
+ throw new Error(`${target} pushRef 必须使用 remote/branch 格式`);
64
+ }
65
+ if ((profile.pushBranch == null) !== (profile.pushRef == null)) {
66
+ throw new Error(`${target} pushBranch 和 pushRef 必须同时配置`);
67
+ }
68
+ if (profile.requirements != null) {
69
+ if (!profile.requirements || typeof profile.requirements !== "object"
70
+ || Array.isArray(profile.requirements)) throw new Error(`${target} requirements 必须是对象`);
71
+ for (const [tool, requirement] of Object.entries(profile.requirements)) {
72
+ if (!["node", "pnpm"].includes(tool) || typeof requirement !== "string"
73
+ || !SAFE_VERSION_REQUIREMENT.test(requirement)) {
74
+ throw new Error(`${target} requirements 只支持 node/pnpm 的 >=x.y.z 版本约束`);
75
+ }
76
+ }
77
+ }
78
+ if (profile.preBuild != null && (!Array.isArray(profile.preBuild) || profile.preBuild.length === 0)) {
79
+ throw new Error(`${target} preBuild 必须是非空列表`);
80
+ }
81
+ for (const command of profile.preBuild || []) normalizePreBuildCommand(command, target);
82
+ }
83
+
84
+ function validateComponent(component, name, guardedByProfile = false) {
85
+ if (!component || !/^[a-z0-9][a-z0-9._:/-]*$/.test(component.repository || "") || component.repository.includes("@")) {
86
+ throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
87
+ }
88
+ if (component.repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
89
+ if (!component.expectedRef && !component.source?.branch && !guardedByProfile) {
90
+ throw new Error(`${name} 必须配置 expectedRef、source.branch 或 target pushRef`);
91
+ }
92
+ if (component.source) {
93
+ normalizeSourceDirectories(component.source.directory, name);
94
+ if (component.source.standalone != null && typeof component.source.standalone !== "boolean") {
95
+ throw new Error(`${name} source.standalone 必须是布尔值`);
96
+ }
97
+ if (!component.source.branch || component.source.branch.startsWith("-")) {
98
+ throw new Error(`${name} source 必须配置合法 branch`);
99
+ }
100
+ }
101
+ inside("/config", component.dockerfile || "Dockerfile");
102
+ if (component.dockerfileFromConfig != null) {
103
+ inside("/config", component.dockerfileFromConfig);
104
+ if (!component.source || component.buildStrategy !== "source" || component.dockerfile != null) {
105
+ throw new Error(`${name} dockerfileFromConfig 只支持外部源码构建,不能同时配置 dockerfile`);
106
+ }
107
+ }
108
+ if (component.contextFiles != null) {
109
+ if (!component.source || component.buildStrategy !== "source" || !Array.isArray(component.contextFiles)
110
+ || !component.contextFiles.length) throw new Error(`${name} contextFiles 只支持外部源码构建的非空列表`);
111
+ const destinations = new Set();
112
+ for (const entry of component.contextFiles) {
113
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
114
+ || Object.keys(entry).some((key) => !["from", "to"].includes(key))) throw new Error(`${name} contextFiles 仅支持 from/to`);
115
+ inside("/config", entry.from); inside("/config", entry.to);
116
+ const destination = path.normalize(entry.to);
117
+ if (destination === "." || destination.split(path.sep).includes(".git") || destinations.has(destination)) {
118
+ throw new Error(`${name} contextFiles 目标不能为根、Git 元数据或重复路径`);
119
+ }
120
+ destinations.add(destination);
121
+ }
122
+ }
123
+ inside("/config", component.context || ".");
124
+ if (component.sourceCheck != null && (!Array.isArray(component.sourceCheck)
125
+ || component.sourceCheck.length === 0
126
+ || component.sourceCheck.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg)))) {
127
+ throw new Error(`${name} sourceCheck 必须是非空命令参数数组`);
128
+ }
129
+ if (component.target != null && (typeof component.target !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(component.target))) {
130
+ throw new Error(`${name} target 必须是合法 Docker stage`);
131
+ }
132
+ if (component.platform != null && (typeof component.platform !== "string"
133
+ || !SAFE_DOCKER_PLATFORM.test(component.platform))) {
134
+ throw new Error(`${name} platform 必须是 linux/amd64 等合法 Docker 平台`);
135
+ }
136
+ if (component.mutableTags != null && typeof component.mutableTags !== "boolean") {
137
+ throw new Error(`${name} mutableTags 必须是布尔值`);
138
+ }
139
+ if (component.tagPrefix != null && (typeof component.tagPrefix !== "string"
140
+ || !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,87}$/.test(component.tagPrefix))) {
141
+ throw new Error(`${name} tagPrefix 必须是 1 到 88 位合法 Docker 标签前缀`);
142
+ }
143
+ if (component.buildStrategy != null && !BUILD_STRATEGIES.has(component.buildStrategy)) {
144
+ throw new Error(`${name} buildStrategy 只支持 artifact 或 source`);
145
+ }
146
+ if (component.buildStrategy === "source" && component.files != null) {
147
+ throw new Error(`${name} source 构建不能同时配置 files 产物上下文`);
148
+ }
149
+ if (component.monorepoContextFiles != null) {
150
+ if (component.buildStrategy !== "source") throw new Error(`${name} monorepoContextFiles 仅用于 source 构建`);
151
+ normalizeMonorepoContextFiles(component.monorepoContextFiles);
152
+ }
153
+ if (component.projectInstall != null) {
154
+ if (typeof component.projectInstall !== "boolean" || !component.source || component.buildStrategy !== "source" || component.monorepoContextFiles != null) {
155
+ throw new Error(`${name} projectInstall 必须是布尔值,只用于外部源码构建,不能与 monorepoContextFiles 同时配置`);
156
+ }
157
+ }
158
+ if (component.releaseIdentity != null && (typeof component.releaseIdentity !== "boolean"
159
+ || component.buildStrategy !== "source" || !component.source)) {
160
+ throw new Error(`${name} releaseIdentity 仅支持外部 source 构建的布尔值`);
161
+ }
162
+ if (component.workspaceRef != null && (typeof component.workspaceRef !== "string"
163
+ || !SAFE_GIT_NAME.test(component.workspaceRef) || !component.workspaceRef.includes("/") || component.workspaceRef.includes(".."))) {
164
+ throw new Error(`${name} workspaceRef 必须使用 remote/branch`);
165
+ }
166
+ if (component.releaseIdentity && (component.tagPrefix || "").length > 74) throw new Error(`${name} 唯一发布标签的前缀过长`);
167
+ if (component.releaseIdentity && !component.platform) throw new Error(`${name} 唯一发布必须明确声明 platform`);
168
+ if (component.releaseChannel != null && (typeof component.releaseChannel !== "boolean" || !component.releaseIdentity)) {
169
+ throw new Error(`${name} releaseChannel 仅支持启用 releaseIdentity 的布尔值`);
170
+ }
171
+ if (component.buildArgs != null && (!component.buildArgs || typeof component.buildArgs !== "object"
172
+ || Array.isArray(component.buildArgs) || Object.entries(component.buildArgs).some(([key, value]) =>
173
+ !/^[A-Z_][A-Z0-9_]*$/.test(key) || !["string", "number", "boolean"].includes(typeof value)))) {
174
+ throw new Error(`${name} buildArgs 必须是合法构建参数对象`);
175
+ }
176
+ if (component.requiredFiles) {
177
+ if (!Array.isArray(component.requiredFiles)) throw new Error(`${name} requiredFiles 必须是数组`);
178
+ for (const file of component.requiredFiles) inside("/config", file);
179
+ }
180
+ if (component.files) {
181
+ if (!Array.isArray(component.files) || component.files.length === 0) throw new Error(`${name} files 必须是非空数组`);
182
+ for (const file of component.files) { inside("/config", file.from); inside("/config", file.to); }
183
+ }
184
+ if (component.check) {
185
+ const { entrypoint, args, addHosts = [] } = component.check;
186
+ if (typeof entrypoint !== "string" || !entrypoint || !Array.isArray(args)
187
+ || !args.every((arg) => typeof arg === "string") || !Array.isArray(addHosts)
188
+ || !addHosts.every((host) => typeof host === "string" && host.includes(":"))) {
189
+ throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 数组`);
190
+ }
191
+ }
192
+ if (component.health != null) {
193
+ const health = component.health;
194
+ if (!health || typeof health !== "object" || Array.isArray(health)
195
+ || Object.keys(health).some((key) => !["timeoutSeconds", "addHost"].includes(key))
196
+ || !Number.isInteger(health.timeoutSeconds) || health.timeoutSeconds < 1 || health.timeoutSeconds > 600
197
+ || (health.addHost != null && (typeof health.addHost !== "string"
198
+ || !/^[A-Za-z0-9][A-Za-z0-9._-]*:(?:[A-Fa-f0-9:.]+|host-gateway)$/.test(health.addHost)))) {
199
+ throw new Error(`${name} health 必须声明 1 到 600 秒的 timeoutSeconds 及可选 addHost`);
200
+ }
201
+ }
202
+ }
203
+
204
+ module.exports = { compareVersions, normalizePreBuildCommand, resolveSourceDirectories, validateComponent, validateReleaseProfile };
@@ -0,0 +1,45 @@
1
+ const fs = require("node:fs");
2
+ const os = require("node:os");
3
+ const path = require("node:path");
4
+ const { execFileSync } = require("node:child_process");
5
+
6
+ /** 只导出指定提交跟踪的公共源码,忽略工作目录及其 ignored/untracked 内容。 */
7
+ function prepareWorkspaceSnapshot({ workspaceRoot, revision, run = execFileSync, temporaryRoot = os.tmpdir() }) {
8
+ if (!/^[0-9a-f]{40}$/.test(revision)) throw new Error("公共源码快照必须使用完整提交号");
9
+ const options = { cwd: workspaceRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
10
+ const entries = String(run("git", ["-C", workspaceRoot, "ls-tree", "-r", "-z", revision, "--", "packages"], options)).split("\0").filter(Boolean);
11
+ if (!entries.length) throw new Error("指定提交没有公共 packages 源码");
12
+ for (const entry of entries) {
13
+ const match = entry.match(/^(100644|100755) blob [0-9a-f]{40}\t(packages\/[\s\S]+)$/);
14
+ if (!match || match[2].split("/").some((part) => !part || part === "." || part === ".." || /[\\:\0]/.test(part))) {
15
+ throw new Error("公共源码快照拒绝符号链接、子模块或不安全路径");
16
+ }
17
+ }
18
+ const contextRoot = fs.mkdtempSync(path.join(temporaryRoot, "infly-workspace-source-"));
19
+ try {
20
+ const archive = path.join(contextRoot, "source.tar");
21
+ run("git", ["-C", workspaceRoot, "archive", "--format=tar", `--output=${archive}`, revision, "--", "packages"], options);
22
+ // GNU tar 会把 Windows 盘符中的冒号识别成远程地址;在临时目录内用相对文件名解压。
23
+ run("tar", ["-xf", path.basename(archive)], { ...options, cwd: contextRoot });
24
+ fs.unlinkSync(archive);
25
+ if (!fs.existsSync(path.join(contextRoot, "packages"))) throw new Error("公共源码快照为空,请检查 Git export 属性");
26
+ return { contextRoot, revision };
27
+ } catch (error) {
28
+ fs.rmSync(contextRoot, { recursive: true, force: true });
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ function verifyWorkspaceRemote({ workspaceRoot, revision, expectedRef, capture }) {
34
+ const match = String(expectedRef || "").match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._/-]*)$/);
35
+ if (!match || expectedRef.includes("..")) throw new Error("workspaceRef 必须是 remote/branch");
36
+ const remoteRef = `refs/heads/${match[2]}`;
37
+ const output = capture("git", ["-C", workspaceRoot, "ls-remote", "--exit-code", match[1], remoteRef]);
38
+ const lines = output.split(/\r?\n/).filter(Boolean);
39
+ if (lines.length !== 1 || lines[0] !== `${revision}\t${remoteRef}`) {
40
+ throw new Error(`主仓 HEAD 与 ${expectedRef} 不一致;请先手动更新/推送主仓,再重新启动发布命令`);
41
+ }
42
+ return { expectedRef, revision, verified: true };
43
+ }
44
+
45
+ module.exports = { prepareWorkspaceSnapshot, verifyWorkspaceRemote };
@@ -0,0 +1,189 @@
1
+ const os = require("node:os");
2
+ const path = require("node:path");
3
+ const { prepareMinimalMonorepoContext } = require("./minimal-context");
4
+ const { prepareProjectInstallContext, prepareStandaloneInstallContext } = require("./project-install");
5
+ const { createReleaseId, createBuildProvenance } = require("./release-identity");
6
+ const { confinedPath, inside } = require("./release-paths");
7
+
8
+ function buildTargetImage(item, {
9
+ target, configuration, projectDir, publicSnapshots, resources, verifyFrozen,
10
+ io, run, capture, log, dependencies, buildExecutableSpawn,
11
+ }) {
12
+ const { sourceDir, commit } = item.frozen;
13
+ let tempRoot;
14
+ verifyFrozen(item.frozen, item.name);
15
+ if (item.sourceCheck) {
16
+ // 检查消费同一冻结提交;失败直接中止,检查也不得改写镜像输入。
17
+ log(`执行 ${item.name} 冻结源码检查: ${commit}`);
18
+ const [command, ...args] = item.sourceCheck;
19
+ const invocation = buildExecutableSpawn(command, args, { platform: dependencies.platform, env: dependencies.env });
20
+ run(invocation.command, invocation.args, { cwd: projectDir, env: {
21
+ ...(dependencies.env || process.env),
22
+ INFLY_SOURCE_DIR: sourceDir,
23
+ INFLY_SOURCE_REVISION: commit,
24
+ INFLY_BUILD_PLATFORM: item.platform || "",
25
+ } });
26
+ verifyFrozen(item.frozen, item.name);
27
+ }
28
+ if (item.source) {
29
+ const sourceLabel = item.name === "backend" ? "后端" : (item.label || item.name);
30
+ log(`\x1b[0;32m✓ ${sourceLabel}构建分支:${item.source.branch}\x1b[0m`);
31
+ }
32
+ const buildStrategy = item.buildStrategy || "artifact";
33
+ const componentReleaseContext = item.releaseContext;
34
+ let buildProjectDir = componentReleaseContext.projectRelativeDir;
35
+ let context = buildStrategy === "source"
36
+ ? componentReleaseContext.contextRoot
37
+ : inside(sourceDir, item.context || ".");
38
+ let dockerfile = inside(sourceDir, item.dockerfile || "Dockerfile");
39
+ let workspaceRevision;
40
+ let internalPackages;
41
+ if (buildStrategy === "source" && componentReleaseContext.mode === "standalone" && item.projectInstall) {
42
+ const prepared = (dependencies.prepareStandaloneInstallContext || prepareStandaloneInstallContext)({
43
+ sourceDir,
44
+ registryManifest: dependencies.registryManifest || ((name) => {
45
+ const invocation = buildExecutableSpawn("pnpm", ["view", `${name}@latest`, "version", "dependencies", "optionalDependencies", "peerDependencies", "--json"],
46
+ { platform: dependencies.platform, env: dependencies.env });
47
+ return JSON.parse(capture(invocation.command, invocation.args));
48
+ }),
49
+ });
50
+ context = prepared.contextRoot;
51
+ tempRoot = context;
52
+ resources.push({ tempRoot });
53
+ internalPackages = prepared.packages;
54
+ buildProjectDir = ".";
55
+ }
56
+ if (buildStrategy === "source" && componentReleaseContext.mode === "monorepo") {
57
+ verifyFrozen(item.workspace, `${item.name} 的 monorepo 构建上下文`);
58
+ workspaceRevision = item.workspace.commit;
59
+ const prepared = item.projectInstall
60
+ ? (dependencies.prepareProjectInstallContext || prepareProjectInstallContext)({
61
+ workspaceRoot: publicSnapshots.get(componentReleaseContext.contextRoot).contextRoot,
62
+ sourceDir,
63
+ })
64
+ : (dependencies.prepareMinimalMonorepoContext || prepareMinimalMonorepoContext)({
65
+ workspaceRoot: componentReleaseContext.contextRoot,
66
+ projectDir: item.source ? item.source.directory : sourceDir,
67
+ additionalFiles: item.monorepoContextFiles || [],
68
+ ...(item.source ? { sourceDir } : {}),
69
+ io,
70
+ });
71
+ tempRoot = prepared.contextRoot;
72
+ resources.push({ tempRoot });
73
+ context = prepared.contextRoot;
74
+ internalPackages = prepared.packages;
75
+ buildProjectDir = prepared.projectRelativeDir;
76
+ dockerfile = inside(context, `${prepared.projectRelativeDir}/${item.dockerfile || "Dockerfile"}`);
77
+ log(item.projectInstall
78
+ ? `项目安装上下文: 自身 workspace/lockfile + 临时源码安装锁 + ${prepared.packages.join(", ")}`
79
+ : `最小上下文: ${prepared.projectRelativeDir} + packages + 根安装文件 + ${item.monorepoContextFiles?.length || 0} 个显式声明文件`);
80
+ }
81
+ // 部署仓提供 Dockerfile/运行配置;独立模式也先复制上下文,绝不改写冻结源码。
82
+ if (item.contextFiles) {
83
+ if (!tempRoot) {
84
+ tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-context-"));
85
+ resources.push({ tempRoot });
86
+ context = path.join(tempRoot, "context");
87
+ io.cpSync(sourceDir, context, { recursive: true, dereference: false,
88
+ filter: (file) => !path.relative(sourceDir, file).split(path.sep).includes(".git") });
89
+ }
90
+ const destinationRoot = componentReleaseContext.mode === "monorepo"
91
+ ? inside(context, buildProjectDir) : context;
92
+ for (const entry of item.contextFiles) {
93
+ const from = confinedPath(projectDir, entry.from, io);
94
+ const to = confinedPath(destinationRoot, entry.to, io);
95
+ if (!io.existsSync(from)) throw new Error(`缺少部署构建文件: ${entry.from}`);
96
+ io.mkdirSync(path.dirname(to), { recursive: true });
97
+ io.cpSync(from, to, { recursive: true, dereference: true,
98
+ filter: (file) => { confinedPath(projectDir, path.relative(projectDir, file), io); return true; } });
99
+ }
100
+ }
101
+ if (item.dockerfileFromConfig) dockerfile = confinedPath(projectDir, item.dockerfileFromConfig, io);
102
+ const effectiveBuildArgs = {
103
+ ...(item.buildArgs || {}),
104
+ ...(buildStrategy === "source" ? { BUILD_MODE: componentReleaseContext.mode, PROJECT_DIR: buildProjectDir } : {}),
105
+ ...(item.projectInstall && componentReleaseContext.mode === "standalone" ? { REFRESH_INTERNAL: true } : {}),
106
+ };
107
+ let provenance;
108
+ const releaseId = item.releaseIdentity ? createReleaseId(commit, dependencies.releaseToken?.()) : commit;
109
+ if (item.releaseIdentity) {
110
+ if (!tempRoot) throw new Error("唯一发布标识必须使用隔离构建上下文");
111
+ provenance = createBuildProvenance({ releaseId, component: item.name, businessRevision: commit,
112
+ workspaceRevision, configurationRevision: configuration?.commit,
113
+ workspaceRemote: item.workspace?.remote, platform: item.platform || "linux/amd64",
114
+ mode: componentReleaseContext.mode, target, buildArgs: effectiveBuildArgs });
115
+ provenance.internalPackages = internalPackages || [];
116
+ io.writeFileSync(path.join(context, ".infly-release.json"), `${JSON.stringify(provenance, null, 2)}\n`);
117
+ }
118
+ for (const file of item.requiredFiles || []) {
119
+ if (!io.existsSync(inside(sourceDir, file))) throw new Error(`缺少必需构建产物: ${file}`);
120
+ }
121
+ if (item.files) {
122
+ if (!tempRoot) {
123
+ tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
124
+ resources.push({ tempRoot });
125
+ }
126
+ context = path.join(tempRoot, "context");
127
+ io.mkdirSync(context, { recursive: true });
128
+ for (const file of item.files) {
129
+ const from = inside(sourceDir, file.from);
130
+ const to = inside(context, file.to);
131
+ // 仅复制配置声明的产物,避免把整个 monorepo 发送给 Docker。
132
+ io.mkdirSync(path.dirname(to), { recursive: true });
133
+ io.cpSync(from, to, { recursive: true, dereference: false });
134
+ }
135
+ dockerfile = inside(context, item.dockerfile || "Dockerfile");
136
+ }
137
+ if (!io.existsSync(dockerfile)) throw new Error(`缺少 Dockerfile: ${dockerfile}`);
138
+ const image = `${item.repository}:${item.tagPrefix || ""}${releaseId}`;
139
+ // 作者、提交说明与镜像 revision 取自同一冻结提交,部署端无需再检出业务仓查询。
140
+ const sourceAuthor = capture("git", ["-C", sourceDir, "show", "-s", "--format=%an", commit])
141
+ .replace(/[\r\n\u0000-\u001f\u007f]+/g, " ").trim();
142
+ const sourceMessage = capture("git", ["-C", sourceDir, "show", "-s", "--format=%s", commit])
143
+ .replace(/[\r\n\u0000-\u001f\u007f]+/g, " ").trim();
144
+ const latestImage = item.mutableTags === false ? null : `${item.repository}:latest`;
145
+ // --load 只把当前构建节点平台的镜像载入本地镜像存储;发布流程直接使用单平台镜像。
146
+ const buildOptions = ["buildx", "build", "--load", "--file", dockerfile];
147
+ if (item.platform) buildOptions.push("--platform", item.platform);
148
+ if (item.target) buildOptions.push("--target", item.target);
149
+ for (const [key, value] of Object.entries(effectiveBuildArgs)) {
150
+ buildOptions.push("--build-arg", `${key}=${value}`);
151
+ }
152
+ run("docker", [...buildOptions,
153
+ "--label", `org.opencontainers.image.revision=${commit}`, "--label", `org.opencontainers.image.version=${releaseId}`,
154
+ ...(sourceAuthor ? ["--label", `com.infly.source.author=${sourceAuthor}`] : []),
155
+ ...(sourceMessage ? ["--label", `com.infly.source.message=${sourceMessage}`] : []),
156
+ ...(item.releaseIdentity ? ["--label", `com.infly.release.id=${releaseId}`] : []),
157
+ ...(workspaceRevision ? ["--label", `com.infly.workspace.revision=${workspaceRevision}`] : []),
158
+ ...(configuration ? ["--label", `com.infly.deployment.revision=${configuration.commit}`] : []),
159
+ "--label", `com.infly.platform=${target}`, "--tag", image,
160
+ ...(latestImage ? ["--tag", latestImage] : []), context], { cwd: projectDir });
161
+ if (capture("docker", ["image", "inspect", "--format", '{{ index .Config.Labels "org.opencontainers.image.revision" }}', image]) !== commit) {
162
+ throw new Error(`${item.name} 镜像 revision 校验失败`);
163
+ }
164
+ if (item.check) {
165
+ const hosts = (item.check.addHosts || []).flatMap((host) => ["--add-host", host]);
166
+ run("docker", ["run", "--rm", ...hosts, "--entrypoint", item.check.entrypoint, image, ...item.check.args], { cwd: projectDir });
167
+ }
168
+ return { commit, image, latestImage, releaseId, provenance };
169
+ }
170
+
171
+ function finishTargetImage(item, { commit, image, latestImage, releaseId, provenance }, { target, capture, log }) {
172
+ log(`${item.name}_commit=${commit}`);
173
+ log(`${item.name}=${image}`);
174
+ if (latestImage) log(`${item.name}_latest=${latestImage}`);
175
+ const identity = {};
176
+ if (item.releaseIdentity) {
177
+ identity.releaseId = releaseId;
178
+ identity.imageId = capture("docker", ["image", "inspect", "--format", "{{.Id}}", image]);
179
+ if (!/^sha256:[0-9a-f]{64}$/.test(identity.imageId)) throw new Error("本地镜像内容 ID 无效");
180
+ identity.provenance = provenance;
181
+ }
182
+ const channelImage = item.releaseChannel ? `${item.repository}:${item.tagPrefix || ""}${target}-latest` : null;
183
+ if (channelImage && !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(channelImage.slice(channelImage.lastIndexOf(":") + 1))) {
184
+ throw new Error("环境最新镜像标签无效");
185
+ }
186
+ return { component: item.name, commit, image, latestImage, ...(channelImage ? { channelImage } : {}), pushed: false, ...identity };
187
+ }
188
+
189
+ module.exports = { buildTargetImage, finishTargetImage };