@infly/libs 2.2.14 → 2.2.16

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 CHANGED
@@ -109,6 +109,8 @@ infly-libs build:docker --local --health-check --health-timeout=60
109
109
  - `--commit-only`:只构建并推送 commit 标签,不更新环境标签或 `latest`。
110
110
  - `--tag-prefix <prefix>`:为本次调用产生的全部镜像标签添加统一前缀(如隔离标签 `qc-`)。前缀必须以字母或数字开头,最多 40 字符,只允许字母、数字、点、下划线和连字符。设置前缀后本地不产生裸发布标签,发布标签应由 CI 在质量门禁通过后晋升产生。
111
111
 
112
+ `build:docker` 的 monorepo 与 standalone 模式共用应用目录内的同一个 `Dockerfile`。公共工具会根据运行模式选择根仓或应用仓作为 context,并自动传入 `BUILD_MODE=monorepo|standalone` 与 `PROJECT_DIR`;应用 Dockerfile 可据此分别使用 workspace 公共包源码或 registry 中的已发布公共包,不再需要维护 `Dockerfile.monorepo` 副本。
113
+
112
114
  ### 可复用的本地质量发布
113
115
 
114
116
  需要在多个前端复用“项目检查 → 可选 SonarQube → 构建/健康门禁/推送”时,在应用 `package.json` 声明项目差异:
@@ -133,7 +135,9 @@ infly-libs release:docker --local --health-check --health-timeout=60
133
135
 
134
136
  `checks` 中的名称必须对应应用已有的 pnpm script;任一检查、覆盖率文件验证、Sonar Quality Gate 或镜像健康门禁失败,命令都会退出且不会推送镜像。`sonar` 默认为 `true`;设为 `false` 时由 CI 单独负责扫描和 Quality Gate。本地启用 Sonar 时必须通过当前进程环境或应用根目录下被 Git 忽略的 `.env.production.local` 提供 `SONAR_TOKEN`,并确保 `sonar-scanner` CLI 可执行;当前进程环境变量的优先级更高。`release:docker` 会拒绝含未提交文件的应用工作树,固定使用完整 40 位应用 commit 作为镜像标签及 OCI revision/version;普通 `build:docker` 未显式传版本时同样使用完整 commit。应用差异保留在应用配置,通用编排由 `infly-libs` 维护。
135
137
 
136
- `infly-libs beforeBuild` 要求应用通过 `infly.buildConfigs.gitAutoPushReposBranchMap` 声明可构建分支;当前应用、可选产物仓、历史独立 packages 仓以及 monorepo 根仓更新均只允许 fast-forward,分支发生分叉时立即停止,不自动创建 merge commit。只需要更新应用和根仓源码的项目应显式设置 `gitAuto: false` 与 `gitAutoPushRepos: false`,避免进入产物自动提交或产物仓分支处理。兄弟应用依赖会从 `vue.config.js`、`vite.config.js/mjs/ts` 和 `next.config.js/mjs/ts` 的相对路径 alias 中静态识别,不执行配置文件;识别到的兄弟仓同样要求工作树干净并以 fast-forward-only 更新。
138
+ `infly-libs beforeBuild` 在应用未配置 `infly.buildConfigs.gitAutoPushReposBranchMap` 时,默认使用 `{ "master": "master", "develop": "develop" }`;应用显式配置的映射(包括空对象)会整体覆盖默认值,不合并分支。默认映射不会隐式启用产物仓推送;显式映射仍沿用原有启用行为,`gitAutoPushRepos: false` 始终优先。当前应用、可选产物仓、历史独立 packages 仓以及 monorepo 根仓更新均只允许 fast-forward,分支发生分叉时立即停止,不自动创建 merge commit。只需要更新应用和根仓源码的项目应显式设置 `gitAuto: false` 与 `gitAutoPushRepos: false`,避免进入产物自动提交或产物仓分支处理。兄弟应用依赖会从 `vue.config.js`、`vite.config.js/mjs/ts` 和 `next.config.js/mjs/ts` 的相对路径 alias 中静态识别,不执行配置文件;识别到的兄弟仓同样要求工作树干净并以 fast-forward-only 更新。
139
+
140
+ `beforeBuild` 优先使用当前调用的显式 `--mode`:测试发布推荐 `infly-libs beforeBuild --mode staging`,正式发布推荐 `infly-libs beforeBuild --mode production`。未传参数时,按构建/发布脚本名的冒号分段识别 `test/stage/staging` 或 `pro/prod/production`,兼容现有 `build:stage`、`build:prod` 和 `release:*:test:docker`、`release:prod:docker`;不再从整条脚本的其他命令中推测环境。测试模式沿用现有映射选择测试分支,正式模式选择 `master`;环境未知或命令名同时包含两种环境字段时保留原有校验提示,Docker 发布不统一绕过确认。显式未知模式不会回退到命令名识别。
137
141
 
138
142
  受控紧急构建可使用 `--emergency` 跳过 `checks`、覆盖率文件校验和 Sonar,但必须提供 8~200 个字符且无控制字符的 `--emergency-reason`,并同时启用 `--standalone --commit-only --health-check`。紧急模式仍执行工作树干净检查、commit/revision 解析、镜像构建、健康检查和推送;缺少任一保护参数会在调用 Docker 前失败。
139
143
 
@@ -278,7 +282,7 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
278
282
 
279
283
  维护归属:公共构建工具;以 `bin/cli.js`、`build/docker/target-release.js` 和 `deployment-bundle.js` 为实现契约。新增配置字段时同步此节及测试。
280
284
 
281
- `infly-libs docker:release` 先单选 target,再多选该 target 的 components。构建在执行命令的机器进行。默认不推送;`--push` 构建、验证后先推送不可变 `<完整40位提交版本>`,再更新 `latest`;组件显式设置 `mutableTags: false` 时只生成、推送不可变提交标签。`--dry-run` 只解析配置,不联网、不运行 Git/Docker、不创建目录。未使用下述新增字段的既有 target 保持原有构建参数、commit + latest 标签和推送顺序。
285
+ `infly-libs release:docker` 是统一发布入口:项目配置 `infly.docker` 或传入 target/component 参数时进入目标化发布,项目只配置 `infly.dockerRelease` 时保持原有单镜像质量发布。目标化发布先单选 target,再多选该 target 的 components;默认不推送,`--push` 构建、验证后先推送不可变 `<完整40位提交版本>`,再更新 `latest`,组件显式设置 `mutableTags: false` 时只生成、推送不可变提交标签。`--dry-run` 只解析配置,不联网、不运行 Git/Docker、不创建目录。旧命令 `docker:release` 仅作为目标化发布兼容别名保留,不再用于新脚本。
282
286
 
283
287
  当 Docker 配置较大时,推荐在 `package.json` 只保留配置入口和真正需要被 Jenkins 直接读取的部署差异:
284
288
 
@@ -313,9 +317,9 @@ targets:
313
317
  ```json
314
318
  {
315
319
  "scripts": {
316
- "build:prod:docker": "infly-libs docker:release --no-push",
317
- "release:frontend:docker": "infly-libs docker:release --push --components frontend",
318
- "release:backend:docker": "infly-libs docker:release --push --components backend"
320
+ "build:prod:docker": "infly-libs release:docker --no-push",
321
+ "release:frontend:docker": "infly-libs release:docker --push --components frontend",
322
+ "release:backend:docker": "infly-libs release:docker --push --components backend"
319
323
  },
320
324
  "infly": {
321
325
  "docker": {
@@ -394,6 +398,7 @@ targets:
394
398
  ```
395
399
 
396
400
  - `files`:从组件源码仓复制到独立临时上下文,仅发送指定产物;配置后 `dockerfile` 相对临时上下文。未配置时 `context`、`dockerfile` 相对组件源码仓。
401
+ - `buildStrategy`:组件构建策略,默认 `artifact`,保持现有宿主机产物封装行为;设为 `source` 时自动识别 `monorepo` / `standalone`。monorepo 模式会从外层 workspace 生成只包含根安装契约、`packages/` 与当前项目的临时最小 Docker context;standalone 模式使用当前源码仓。两种模式都会自动注入 `BUILD_MODE` 与 `PROJECT_DIR` 构建参数。`source` 不能与 `files` 产物上下文同时使用;monorepo workspace 必须保持干净,并写入 `com.infly.workspace.revision` 镜像标签。
397
402
  - `config`:`infly.docker` 中的外部配置路径,支持 JSON、YAML、JS;外部配置为基础,package 中的同名对象递归覆盖。循环引用和未知格式会直接失败。
398
403
  - `compose`:组件构建配置来源,必须指定 `file` 和 `service`。工具从 Compose 服务读取镜像仓库、上下文、Dockerfile、stage 与构建参数;组件显式字段仍可覆盖解析结果。
399
404
  - `target` / `buildArgs`:分别映射到 `docker buildx build --target` 和 `--build-arg`;使用 `compose` 时通常无需重复填写。
@@ -402,10 +407,10 @@ targets:
402
407
  - `requiredFiles`:构建前必须存在的源码仓相对路径,例如前端产物的 `index.html`;缺失时停止构建。
403
408
  - `pushBranch` / `pushRef`:target 级可选推送门禁,必须成对配置,例如 `develop` 与 `origin/develop`。仅 `--push` 时要求当前分支匹配、主动 fetch 对应 remote/branch,并要求本地 HEAD 与远端提交相同;`--no-push` 仍允许在其他分支本地验证镜像。
404
409
  - `requirements`:target 级可选本机工具最低版本,目前只支持 `node`、`pnpm` 和 `>=x.y.z` 格式。
405
- - `preBuild`:target 级可选命令参数数组列表,例如 `[["pnpm", "install", "--frozen-lockfile"], ["pnpm", "run", "build:test"]]`。命令不经过 shell,在干净工作树和推送门禁之后、Docker 检查与 `requiredFiles` 校验之前执行;配置具有代码执行权限,必须与源码一样评审。
410
+ - `preBuild`:target 级可选准备命令列表。原有命令参数数组继续表示始终执行,例如 `["pnpm", "run", "build:test"]`;需要兼容根 monorepo 与独立子仓时,可使用 `{ "when": "standalone", "command": ["pnpm", "install", "--frozen-lockfile"] }`,其中 `when` 支持 `always`、`monorepo`、`standalone`。它与 `buildStrategy` 共用同一个模式探测器,避免宿主机准备步骤和 Docker context 判断漂移。命令在干净工作树和推送门禁之后、Docker 检查与 `requiredFiles` 校验之前执行;配置具有代码执行权限,必须与源码一样评审。
406
411
  - `source`:可选独立源码仓;`directory` 支持单个路径或按优先级排列的候选路径数组,路径均从项目目录解析,采用第一个包含 `.git` 的目录。fetch 后使用指定分支的临时 detached worktree,不切换当前开发分支。交互终端找不到候选仓库时会列出已检查路径、展示路径示例并等待手动输入;取消或非交互环境仍明确说明未执行构建或推送,打印编号化的 clone、fetch 和重跑步骤,全部构建停止,CLI 返回 2。
407
412
  - `targetPresets` 与 `targets.*.extends`:可选的具名公共目标配置。preset 可以继续 `extends` 另一个 preset;目标只继承显式指定的 preset,未声明 `extends` 的历史目标不受影响。同名普通对象递归合并;数组、字符串、数字、布尔值和 `null` 由下层整项替换,不按数组下标混合。未知 preset 或循环继承直接失败。本地构建、Compose 发布和部署包生成共用同一解析规则。
408
- - `releaseScripts`:可选的组件重跑脚本覆盖。默认从项目 scripts 自动识别严格匹配 `release:<组件>:docker` 的脚本,例如 `release:backend:docker`;源码仓缺失时提示 `pnpm run <脚本> -- --platform ...`。只有脚本名称不遵循约定时才需要显式配置;无匹配时提示通用 `pnpm exec infly-libs docker:release` 命令。
413
+ - `releaseScripts`:可选的组件重跑脚本覆盖。默认从项目 scripts 自动识别严格匹配 `release:<组件>:docker` 的脚本,例如 `release:backend:docker`;源码仓缺失时提示 `pnpm run <脚本> -- --platform ...`。只有脚本名称不遵循约定时才需要显式配置;无匹配时提示通用 `pnpm exec infly-libs release:docker` 命令。
409
414
  - 无 `source` 时构建当前项目,要求干净工作树;通常配置组件 `expectedRef` 并要求 HEAD 与其相同。target 已配置 `pushBranch` / `pushRef` 时可以省略组件 `expectedRef`,推送同步由 target 门禁负责。有 `source` 时校验临时工作树对应的 origin 分支。
410
415
  - `check`:可选镜像内校验,使用 `entrypoint`、`args` 数组及 `addHosts` 数组;失败不推送。配置命令具有代码执行权限,应与源码一样评审,不能来自不可信输入。
411
416
  - `deployment`:仅用于部署包生成;`ready=false` 会阻止生成。可设置 `lockName`,默认 `.infly-release.lock`。服务归属和 imageEnv 必须唯一。
@@ -414,9 +419,9 @@ targets:
414
419
  - 路径、分支、镜像、服务、健康检查由项目配置决定;公共包不内置项目映射。Dockerfile、Compose、Nginx 由项目保留。
415
420
 
416
421
  ```bash
417
- infly-libs docker:release --target demo --components frontend,backend --push
418
- infly-libs docker:release --platform demo --components backend --backend-dir ../api --no-push
419
- infly-libs docker:release --project-dir ./deployment --config docker.yaml --target demo --components frontend --dry-run
422
+ infly-libs release:docker --target demo --components frontend,backend --push
423
+ infly-libs release:docker --platform demo --components backend --backend-dir ../api --no-push
424
+ infly-libs release:docker --project-dir ./deployment --config docker.yaml --target demo --components frontend --dry-run
420
425
  infly-libs docker:config --project-dir ./deployment
421
426
  infly-libs docker:bundle --target demo --output .infly-deploy-123
422
427
  infly-libs docker:bundle --target demo --dry-run
@@ -428,6 +433,6 @@ infly-libs docker:bundle --target demo --dry-run
428
433
 
429
434
  `docker:bundle` 只生成本地脚本包,不自动部署;输出须是项目内尚不存在的独立子目录。包内包含 config.sh、Compose 覆盖文件和公共 shell 脚本。Jenkins 可直接传入部署项目 `package.json` 声明的精确版本或 caret 范围获取公共包;`docker:bundle` 会在执行时输出实际解析到的 `@infly/libs` 精确版本,供 Jenkins 日志追溯。镜像不需要 Infly 专用版本标签,因此独立项目使用普通 `docker build` 生成的镜像仍可部署。Jenkins 使用既有凭据,调用 `deploy.sh component=repository:commit` 传输并执行。包内仍保留 `promote-image.sh` 供既有 qc 晋升流程兼容使用;低频定制平台直接在本地推送不可变提交标签与 `latest`,Jenkins 不再调用晋升脚本。运行部署脚本会操作服务器,必须由开发者手动触发既定任务。
430
435
 
431
- `docker:release` 不是强制构建入口。独立源码仓可以直接使用 Dockerfile 或 Compose 构建,但若镜像要进入这里生成的部署流程,必须自行保证仓库名、不可变完整 40 位提交标签以及 `org.opencontainers.image.revision`、`org.opencontainers.image.version`、`com.infly.platform` 标签与目标配置一致;公共发布入口只是自动化这些校验和映射。部署侧仅为既有镜像保留旧 12 位标签兼容,新构建不再生成 12 位标签。
436
+ `release:docker` 不是强制构建入口。独立源码仓可以直接使用 Dockerfile 或 Compose 构建,但若镜像要进入这里生成的部署流程,必须自行保证仓库名、不可变完整 40 位提交标签以及 `org.opencontainers.image.revision`、`org.opencontainers.image.version`、`com.infly.platform` 标签与目标配置一致;公共发布入口只是自动化这些校验和映射。部署侧仅为既有镜像保留旧 12 位标签兼容,新构建不再生成 12 位标签。
432
437
 
433
438
  远端发布持锁后读取全部组件镜像基线,保存 .release-history;配置 `runtimeEnv` 时先从服务器总环境文件按白名单原子生成应用专用文件,再仅更新传入组件的服务(up -d --no-deps)。首次接入可由发布入口显式传入 `--initialize-baseline`:仅在 `deploy.env` 不存在时,从配置声明的运行中服务读取唯一且仓库匹配的 RepoDigest,保存权限受限的 `.onboarding-backup` 接入证据并原子创建基线;已有基线时拒绝覆盖,未显式初始化时仍要求基线预先存在。失败恢复镜像环境文件、应用专用环境文件及选中服务;回滚验证失败明确报错。不创建总环境文件,不创建/修改数据库,不更新未配置的基础设施。服务器不需要 npm/Node,仍需 Bash、Docker Compose 和 curl。
package/bin/cli.js CHANGED
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+
3
6
  function loadBuildDist() {
4
7
  return require("../build/build-dist");
5
8
  }
@@ -100,6 +103,62 @@ function parseProjectArgs(argv) {
100
103
  if (hasNoWebhook) options.noWebhook = true;
101
104
  return options;
102
105
  }
106
+
107
+ const TARGET_RELEASE_FLAGS = new Set([
108
+ "--target", "--platform", "--components", "--backend-dir", "--config", "--no-push", "--output",
109
+ ]);
110
+ const QUALITY_RELEASE_FLAGS = new Set([
111
+ "--local", "--standalone", "--commit-only", "--emergency", "--emergency-reason",
112
+ "--health-check", "--health-timeout", "--health-add-host", "--tag-prefix", "--env",
113
+ ]);
114
+
115
+ function argumentFlag(value) {
116
+ return String(value).split("=", 1)[0];
117
+ }
118
+
119
+ function optionValue(argv, name) {
120
+ for (let index = 0; index < argv.length; index++) {
121
+ const value = argv[index];
122
+ if (value.startsWith(`${name}=`)) return value.slice(name.length + 1);
123
+ if (value === name) return argv[index + 1];
124
+ }
125
+ return undefined;
126
+ }
127
+
128
+ function loadReleasePackage(argv, cwd = process.cwd()) {
129
+ const projectDir = optionValue(argv, "--project-dir");
130
+ const root = path.resolve(cwd, projectDir || ".");
131
+ const manifestPath = path.join(root, "package.json");
132
+ if (!fs.existsSync(manifestPath)) return {};
133
+ return JSON.parse(fs.readFileSync(manifestPath, "utf8"));
134
+ }
135
+
136
+ function resolveReleaseDockerMode(argv, packageObject = {}) {
137
+ const flags = new Set(argv.map(argumentFlag));
138
+ const explicitTarget = [...TARGET_RELEASE_FLAGS].some((flag) => flags.has(flag));
139
+ const explicitQuality = [...QUALITY_RELEASE_FLAGS].some((flag) => flags.has(flag));
140
+ if (explicitTarget && explicitQuality) {
141
+ throw new Error("release:docker 不能混用目标化发布参数和单镜像质量发布参数");
142
+ }
143
+ if (explicitTarget) return "target";
144
+ if (explicitQuality) return "quality";
145
+
146
+ const infly = packageObject.infly || {};
147
+ const hasTargetConfig = Boolean(infly.docker?.config || infly.docker?.targets);
148
+ const hasQualityConfig = Boolean(infly.dockerRelease);
149
+ if (hasTargetConfig && hasQualityConfig) {
150
+ throw new Error("项目同时配置 infly.docker 与 infly.dockerRelease,请通过 target/components 或质量发布参数明确模式");
151
+ }
152
+ return hasTargetConfig ? "target" : "quality";
153
+ }
154
+
155
+ async function runTargetReleaseCommand(args) {
156
+ const { parseReleaseArgs, runTargetRelease } = require("../build/docker/target-release");
157
+ const result = await runTargetRelease(parseReleaseArgs(args));
158
+ if (result.missingSources?.length) process.exitCode = 2;
159
+ return result;
160
+ }
161
+
103
162
  async function main(argv = process.argv.slice(2)) {
104
163
  const command = argv[0];
105
164
  const commandMap = {
@@ -120,12 +179,8 @@ async function main(argv = process.argv.slice(2)) {
120
179
  console.log(JSON.stringify(result, null, 2));
121
180
  return result;
122
181
  },
123
- "docker:release": async () => {
124
- const { parseReleaseArgs, runTargetRelease } = require("../build/docker/target-release");
125
- const result = await runTargetRelease(parseReleaseArgs(argv.slice(1)));
126
- if (result.missingSources?.length) process.exitCode = 2;
127
- return result;
128
- },
182
+ // 兼容旧脚本;新项目和生成配置统一使用 release:docker。
183
+ "docker:release": () => runTargetReleaseCommand(argv.slice(1)),
129
184
  afterBuild: () => loadBuildDist().init(),
130
185
  initZip: () => loadBuildDist().init(),
131
186
  preview: () => loadPreview().init(),
@@ -143,8 +198,10 @@ async function main(argv = process.argv.slice(2)) {
143
198
  return require("../build/docker/docker-build-push").dockerBuildPush(opts);
144
199
  },
145
200
  "release:docker": () => {
146
- const opts = parseArgs(argv.slice(1));
147
- return require("../build/docker/release-docker").releaseDocker(opts);
201
+ const args = argv.slice(1);
202
+ const mode = resolveReleaseDockerMode(args, loadReleasePackage(args));
203
+ if (mode === "target") return runTargetReleaseCommand(args);
204
+ return require("../build/docker/release-docker").releaseDocker(parseArgs(args));
148
205
  },
149
206
  "docker:compose": () => {
150
207
  const opts = parseArgs(argv.slice(1));
@@ -173,4 +230,4 @@ if (require.main === module) {
173
230
  });
174
231
  }
175
232
 
176
- module.exports = { main, parseArgs, parseProjectArgs };
233
+ module.exports = { main, parseArgs, parseProjectArgs, resolveReleaseDockerMode };
@@ -0,0 +1,26 @@
1
+ const modes = new Map([
2
+ ["test", "stage"],
3
+ ["stage", "stage"],
4
+ ["staging", "stage"],
5
+ ["pro", "prod"],
6
+ ["prod", "prod"],
7
+ ["production", "prod"],
8
+ ]);
9
+
10
+ function resolveBuildMode(modeArg, lifecycleEvent = "") {
11
+ // 显式环境优先,未知参数不再通过命令名猜测环境。
12
+ if (modeArg) {
13
+ return modes.get(modeArg) || "";
14
+ }
15
+
16
+ const fields = lifecycleEvent.split(":");
17
+ if (!fields.includes("build") && !fields.includes("release")) {
18
+ return "";
19
+ }
20
+
21
+ const inferredModes = new Set(fields.map((field) => modes.get(field)).filter(Boolean));
22
+ // 命令名同时包含测试和正式环境字段时,交给原有校验提示处理。
23
+ return inferredModes.size === 1 ? [...inferredModes][0] : "";
24
+ }
25
+
26
+ module.exports = { resolveBuildMode };
@@ -0,0 +1,18 @@
1
+ function applyBuildConfigDefaults(config) {
2
+ const buildConfigs = config.buildConfigs || {};
3
+
4
+ return {
5
+ ...config,
6
+ buildConfigs: {
7
+ gitAutoPushReposBranchMap: { master: "master", develop: "develop" },
8
+ ...buildConfigs,
9
+ // 默认映射只声明可构建分支;不能因此隐式启用产物仓推送。
10
+ gitAutoPushRepos:
11
+ buildConfigs.gitAutoPushRepos === undefined
12
+ ? buildConfigs.gitAutoPushReposBranchMap || false
13
+ : buildConfigs.gitAutoPushRepos,
14
+ },
15
+ };
16
+ }
17
+
18
+ module.exports = { applyBuildConfigDefaults };
@@ -24,6 +24,8 @@ const { init: previewInit } = require("../../adapters/vue2/project-preview.js");
24
24
  const { postVersionFileAndMsg } = require("../build-utils/webhook-single.js");
25
25
  const { scriptWrite, targetProjectFileResolve, currentProjectFileResolve } = require("../project-files.js");
26
26
  const { shouldManageBuildScripts } = require("./script-management.js");
27
+ const { applyBuildConfigDefaults } = require("./config.js");
28
+ const { resolveBuildMode } = require("./build-mode.js");
27
29
  const {
28
30
  autoBranchProcess,
29
31
  autoGitProcess,
@@ -162,25 +164,7 @@ function getNextStandaloneServerPath(distPath) {
162
164
  }
163
165
 
164
166
  function getBuildMode() {
165
- const modeArg = getArgValue("--mode");
166
- const lifecycleText = [process.env.npm_lifecycle_event, process.env.npm_lifecycle_script, ...process.argv]
167
- .filter(Boolean)
168
- .join(" ");
169
-
170
- if (modeArg === "staging" || lifecycleText.includes("build:stage") || lifecycleText.includes("--mode staging")) {
171
- return "stage";
172
- }
173
-
174
- if (
175
- modeArg === "production" ||
176
- modeArg === "prod" ||
177
- lifecycleText.includes("build:prod") ||
178
- lifecycleText.includes("build:pro")
179
- ) {
180
- return "prod";
181
- }
182
-
183
- return "";
167
+ return resolveBuildMode(getArgValue("--mode"), process.env.npm_lifecycle_event);
184
168
  }
185
169
 
186
170
  function getStageBranch(branchMap = {}, branch = currentBranch) {
@@ -336,6 +320,8 @@ function normalizeBuildConfig(config, packageKey, branch, title) {
336
320
  normalizedConfig = normalizedConfig[packageKey];
337
321
  }
338
322
 
323
+ normalizedConfig = applyBuildConfigDefaults(normalizedConfig);
324
+
339
325
  // 自动启用 gitAutoPushRepos
340
326
  if (!normalizedConfig.gitAutoPushRepos && normalizedConfig.gitAutoPushReposBranchMap) {
341
327
  normalizedConfig.gitAutoPushRepos = true;
@@ -416,9 +402,8 @@ async function validateConfig(buildConfig, targetBranch = currentBranch) {
416
402
  }
417
403
 
418
404
  const buildMode = getBuildMode();
419
- const lifecycleEvent = process.env.npm_lifecycle_event || "";
420
- const isProdBuild = buildMode === "prod" || lifecycleEvent.includes("prod");
421
- const isStageBuild = buildMode === "stage" || lifecycleEvent.includes("stage");
405
+ const isProdBuild = buildMode === "prod";
406
+ const isStageBuild = buildMode === "stage";
422
407
 
423
408
  if (targetBranch === "master" && !isProdBuild) {
424
409
  console.error(global.logColor.error, `❌ 目标分支为 master 分支,请使用正式环境构建命令进行构建`);
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * 支持两种运行模式(自动检测):
5
5
  *
6
- * 1. Monorepo 模式 — 检测到 git submodule (--show-superproject-working-tree 有值)
7
- * 构建上下文 = superproject 根,Dockerfile 使用 Dockerfile.monorepo
6
+ * 1. Monorepo 模式 — 检测到外层 workspace
7
+ * 从 superproject 根生成最小构建上下文,Dockerfile 仍使用应用内的统一 Dockerfile
8
8
  * @infly/* 包从 workspace 源码解析
9
9
  *
10
10
  * 2. 独立模式 — 非 submodule 且 cwd = git 根
@@ -20,6 +20,8 @@
20
20
  const { execSync, spawn } = require("child_process");
21
21
  const fs = require("fs");
22
22
  const path = require("path");
23
+ const { detectReleaseContext } = require("./release-mode");
24
+ const { prepareMinimalMonorepoContext } = require("./minimal-context");
23
25
 
24
26
  // ---------- 默认配置 ----------
25
27
  const DEFAULT_REGISTRY = "ccr.ccs.tencentyun.com";
@@ -83,33 +85,30 @@ function formatCicdLink(value, deployParams) {
83
85
  }
84
86
 
85
87
  function detectMode({ standalone = false } = {}) {
86
- const cwd = path.resolve(process.cwd());
88
+ const { isStandalone, contextRoot } = detectReleaseContext({
89
+ projectDir: process.cwd(),
90
+ standalone,
91
+ });
92
+ return { isStandalone, contextRoot };
93
+ }
87
94
 
88
- if (standalone) {
89
- const gitRoot = execSync("git rev-parse --show-toplevel", { encoding: "utf-8" }).trim();
90
- if (path.resolve(cwd) !== path.resolve(gitRoot)) {
91
- throw new Error("--standalone 必须在当前 Git 仓库根目录执行");
92
- }
93
- return { isStandalone: true, contextRoot: cwd };
95
+ function resolveDockerBuildLayout({ cwd, contextRoot, isStandalone }) {
96
+ const resolvedCwd = path.resolve(cwd);
97
+ const resolvedContextRoot = path.resolve(contextRoot);
98
+ if (isStandalone) {
99
+ return {
100
+ buildContext: resolvedCwd,
101
+ dockerfileArg: "Dockerfile",
102
+ projectDirArg: ".",
103
+ modeLabel: "独立模式",
104
+ };
94
105
  }
95
-
96
- // git submodule → monorepo 模式,contextRoot = superproject 根
97
- try {
98
- const superproject = execSync("git rev-parse --show-superproject-working-tree", {
99
- encoding: "utf-8", stdio: "pipe",
100
- }).trim();
101
- if (superproject) {
102
- return { isStandalone: false, contextRoot: superproject };
103
- }
104
- } catch {}
105
-
106
- // 非 submodule:cwd = git 根 → 独立模式,否则 monorepo 模式
107
- const gitRoot = execSync("git rev-parse --show-toplevel", { encoding: "utf-8" }).trim();
108
- const isStandalone = path.resolve(cwd) === path.resolve(gitRoot);
109
-
106
+ const appDir = path.relative(resolvedContextRoot, resolvedCwd).replace(/\\/g, "/");
110
107
  return {
111
- isStandalone,
112
- contextRoot: isStandalone ? cwd : gitRoot,
108
+ buildContext: resolvedContextRoot,
109
+ dockerfileArg: `${appDir}/Dockerfile`,
110
+ projectDirArg: appDir,
111
+ modeLabel: `monorepo 模式 (${appDir})`,
113
112
  };
114
113
  }
115
114
 
@@ -135,7 +134,7 @@ function isDockerContextBusyError(error) {
135
134
  && /(being used by another process|used by another process|process cannot access the file)/i.test(detail);
136
135
  }
137
136
 
138
- function executeDocker(commandArgs, { cwd } = {}) {
137
+ function executeDocker(commandArgs, { cwd, inheritOutput = false } = {}) {
139
138
  return new Promise((resolve, reject) => {
140
139
  let stderr = "";
141
140
  let settled = false;
@@ -143,7 +142,7 @@ function executeDocker(commandArgs, { cwd } = {}) {
143
142
  cwd: cwd || process.cwd(),
144
143
  env: process.env,
145
144
  shell: false,
146
- stdio: ["inherit", "pipe", "pipe"],
145
+ stdio: inheritOutput ? "inherit" : ["inherit", "pipe", "pipe"],
147
146
  windowsHide: true,
148
147
  });
149
148
  const finish = (callback) => {
@@ -151,11 +150,13 @@ function executeDocker(commandArgs, { cwd } = {}) {
151
150
  settled = true;
152
151
  callback();
153
152
  };
154
- child.stdout.on("data", (chunk) => process.stdout.write(chunk));
155
- child.stderr.on("data", (chunk) => {
156
- stderr = `${stderr}${chunk}`.slice(-128 * 1024);
157
- process.stderr.write(chunk);
158
- });
153
+ if (!inheritOutput) {
154
+ child.stdout.on("data", (chunk) => process.stdout.write(chunk));
155
+ child.stderr.on("data", (chunk) => {
156
+ stderr = `${stderr}${chunk}`.slice(-128 * 1024);
157
+ process.stderr.write(chunk);
158
+ });
159
+ }
159
160
  child.once("error", (cause) => finish(() => {
160
161
  const error = new Error(`docker ${commandArgs[0]} 无法启动: ${cause.message}`, { cause });
161
162
  error.stderr = stderr;
@@ -176,29 +177,29 @@ function executeDocker(commandArgs, { cwd } = {}) {
176
177
 
177
178
  function shouldUseDockerTtyProgress({
178
179
  local,
179
- platform = process.platform,
180
180
  stdoutIsTTY = process.stdout.isTTY,
181
181
  stderrIsTTY = process.stderr.isTTY,
182
182
  } = {}) {
183
- // Windows Docker CLI 无法在当前管道化 stderr 上初始化 TTY console;强制 tty 会直接报 handle invalid。
184
- return Boolean(local && platform !== "win32" && stdoutIsTTY && stderrIsTTY);
183
+ // tty 模式必须让 Docker 直接继承真实终端;Windows 只有在不经过 Node 管道时才不会报 handle invalid。
184
+ return Boolean(local && stdoutIsTTY && stderrIsTTY);
185
185
  }
186
186
 
187
187
  async function runDockerBuildWithRetry(commandArgs, {
188
188
  cwd,
189
189
  local = false,
190
+ inheritOutput = false,
190
191
  platform = process.platform,
191
192
  execute = executeDocker,
192
193
  sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
193
194
  log = console.warn,
194
195
  } = {}) {
195
196
  try {
196
- await execute(commandArgs, { cwd });
197
+ await execute(commandArgs, { cwd, inheritOutput });
197
198
  } catch (error) {
198
199
  if (!local || platform !== "win32" || !isDockerContextBusyError(error)) throw error;
199
200
  log("检测到 Docker context 元数据被临时占用,1 秒后自动重试构建…");
200
201
  await sleep(1000);
201
- await execute(commandArgs, { cwd });
202
+ await execute(commandArgs, { cwd, inheritOutput });
202
203
  }
203
204
  }
204
205
 
@@ -323,7 +324,7 @@ function startDockerDesktop() {
323
324
  }
324
325
  }
325
326
 
326
- async function dockerBuildPush(options = {}) {
327
+ async function dockerBuildPush(options = {}, dependencies = {}) {
327
328
  const {
328
329
  env = "prod",
329
330
  registry = DEFAULT_REGISTRY,
@@ -352,24 +353,14 @@ async function dockerBuildPush(options = {}) {
352
353
  process.exit(1);
353
354
  }
354
355
 
355
- let buildContext, dockerfileArg, modeLabel;
356
- if (isStandalone) {
357
- if (!fs.existsSync(path.join(cwd, "Dockerfile"))) {
358
- console.error("错误: 当前目录下缺少 Dockerfile");
359
- process.exit(1);
360
- }
361
- buildContext = cwd;
362
- dockerfileArg = "Dockerfile";
363
- modeLabel = "独立模式";
364
- } else {
365
- const appDir = path.relative(contextRoot, cwd).replace(/\\/g, "/");
366
- if (!fs.existsSync(path.join(contextRoot, appDir, "Dockerfile.monorepo"))) {
367
- console.error("错误: 缺少 Dockerfile.monorepo");
368
- process.exit(1);
369
- }
370
- buildContext = contextRoot;
371
- dockerfileArg = `${appDir}/Dockerfile.monorepo`;
372
- modeLabel = `monorepo 模式 (${appDir})`;
356
+ const { buildContext, dockerfileArg, modeLabel, projectDirArg } = resolveDockerBuildLayout({
357
+ cwd,
358
+ contextRoot,
359
+ isStandalone,
360
+ });
361
+ if (!fs.existsSync(path.join(buildContext, dockerfileArg))) {
362
+ console.error(`错误: 缺少 Dockerfile: ${dockerfileArg}`);
363
+ process.exit(1);
373
364
  }
374
365
 
375
366
  // 2. 从 package.json 推导镜像名
@@ -425,20 +416,41 @@ async function dockerBuildPush(options = {}) {
425
416
 
426
417
  // 7. 构建
427
418
  console.log("\x1b[0;32m>>> 开始构建 Docker 镜像\x1b[0m");
419
+ let effectiveBuildContext = buildContext;
420
+ let preparedContext;
421
+ if (!isStandalone && !dryRun) {
422
+ preparedContext = (dependencies.prepareMinimalMonorepoContext || prepareMinimalMonorepoContext)({
423
+ workspaceRoot: contextRoot,
424
+ projectDir: cwd,
425
+ });
426
+ effectiveBuildContext = preparedContext.contextRoot;
427
+ console.log(`最小上下文: ${projectDirArg} + packages + 根锁文件`);
428
+ }
428
429
  const buildArgs = ["build", "-f", dockerfileArg];
429
430
  tags.forEach((tag) => buildArgs.push("-t", tag));
430
431
  buildArgs.push(
431
432
  "--build-arg", `GIT_COMMIT=${fullCommit}`,
433
+ "--build-arg", `BUILD_MODE=${isStandalone ? "standalone" : "monorepo"}`,
434
+ "--build-arg", `PROJECT_DIR=${projectDirArg}`,
432
435
  "--label", `org.opencontainers.image.revision=${fullCommit}`,
433
436
  "--label", `org.opencontainers.image.version=${commitHash}`
434
437
  );
435
- // 捕获 stderr 会让 Docker 子进程看到管道;非 Windows 本地交互终端可显式保留彩色紧凑输出。
436
- if (shouldUseDockerTtyProgress({ local })) buildArgs.push("--progress=tty");
438
+ // 本地交互构建让 Docker 直接继承真实终端;CI/重定向输出继续使用可捕获的 plain 进度。
439
+ const useTtyProgress = shouldUseDockerTtyProgress({ local });
440
+ if (useTtyProgress) buildArgs.push("--progress=tty");
437
441
  buildArgs.push(".");
438
- if (dryRun) {
439
- console.log(` [DRY RUN] docker ${buildArgs.join(" ")}`);
440
- } else {
441
- await runDockerBuildWithRetry(buildArgs, { cwd: buildContext, local });
442
+ try {
443
+ if (dryRun) {
444
+ console.log(` [DRY RUN] docker ${buildArgs.join(" ")}`);
445
+ } else {
446
+ await runDockerBuildWithRetry(buildArgs, {
447
+ cwd: effectiveBuildContext,
448
+ local,
449
+ inheritOutput: useTtyProgress,
450
+ });
451
+ }
452
+ } finally {
453
+ if (preparedContext) fs.rmSync(preparedContext.contextRoot, { recursive: true, force: true });
442
454
  }
443
455
  console.log("\x1b[0;32m✓ 镜像构建完成\x1b[0m");
444
456
 
@@ -487,6 +499,7 @@ module.exports = {
487
499
  isDockerContextBusyError,
488
500
  normalizeHealthOptions,
489
501
  normalizeTagPrefix,
502
+ resolveDockerBuildLayout,
490
503
  resolveImageTags,
491
504
  runDockerBuildWithRetry,
492
505
  shouldUseDockerTtyProgress,
@@ -0,0 +1,79 @@
1
+ const fs = require("node:fs");
2
+ const os = require("node:os");
3
+ const path = require("node:path");
4
+
5
+ const ROOT_ENTRIES = [
6
+ "package.json",
7
+ "pnpm-lock.yaml",
8
+ "pnpm-workspace.yaml",
9
+ ".npmrc",
10
+ ".pnpmfile.cjs",
11
+ "patches",
12
+ "packages",
13
+ ];
14
+
15
+ const EXCLUDED_DIRECTORIES = new Set([
16
+ ".git",
17
+ ".turbo",
18
+ "coverage",
19
+ "dist",
20
+ "node_modules",
21
+ ]);
22
+
23
+ function isInside(root, candidate) {
24
+ const relative = path.relative(root, candidate);
25
+ return relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
26
+ }
27
+
28
+ function shouldCopy(source) {
29
+ return !source.split(path.sep).some((segment) => EXCLUDED_DIRECTORIES.has(segment));
30
+ }
31
+
32
+ function copyEntry(io, workspaceRoot, contextRoot, relative) {
33
+ const source = path.join(workspaceRoot, relative);
34
+ if (!io.existsSync(source)) return false;
35
+ const destination = path.join(contextRoot, relative);
36
+ io.mkdirSync(path.dirname(destination), { recursive: true });
37
+ io.cpSync(source, destination, {
38
+ recursive: true,
39
+ dereference: false,
40
+ filter: shouldCopy,
41
+ });
42
+ return true;
43
+ }
44
+
45
+ /**
46
+ * 为 monorepo 源码镜像准备保持原目录布局的最小上下文。
47
+ * 只带根安装契约、公共 packages 和当前应用,避免把其他产品线发送给 Docker。
48
+ */
49
+ function prepareMinimalMonorepoContext({
50
+ workspaceRoot,
51
+ projectDir,
52
+ io = fs,
53
+ temporaryRoot = os.tmpdir(),
54
+ } = {}) {
55
+ const resolvedWorkspace = path.resolve(workspaceRoot);
56
+ const resolvedProject = path.resolve(projectDir);
57
+ if (!isInside(resolvedWorkspace, resolvedProject)) {
58
+ throw new Error(`项目目录不在 monorepo 根目录内: ${resolvedProject}`);
59
+ }
60
+ const projectRelativeDir = path.relative(resolvedWorkspace, resolvedProject);
61
+ const contextRoot = io.mkdtempSync(path.join(temporaryRoot, "infly-docker-context-"));
62
+ try {
63
+ for (const entry of ROOT_ENTRIES) copyEntry(io, resolvedWorkspace, contextRoot, entry);
64
+ if (!projectRelativeDir.startsWith(`packages${path.sep}`)) {
65
+ copyEntry(io, resolvedWorkspace, contextRoot, projectRelativeDir);
66
+ }
67
+ return { contextRoot, projectRelativeDir: projectRelativeDir.split(path.sep).join("/") };
68
+ } catch (error) {
69
+ io.rmSync(contextRoot, { recursive: true, force: true });
70
+ throw error;
71
+ }
72
+ }
73
+
74
+ module.exports = {
75
+ EXCLUDED_DIRECTORIES,
76
+ ROOT_ENTRIES,
77
+ prepareMinimalMonorepoContext,
78
+ shouldCopy,
79
+ };
@@ -0,0 +1,57 @@
1
+ const path = require("node:path");
2
+ const {
3
+ findOuterWorkspaceRoot,
4
+ resolveGitWorktreeRoot,
5
+ } = require("../../script/git-automation/git-utils");
6
+
7
+ function detectReleaseContext({
8
+ projectDir = process.cwd(),
9
+ standalone = false,
10
+ } = {}) {
11
+ const resolvedProjectDir = path.resolve(projectDir);
12
+ const projectGitRoot = resolveGitWorktreeRoot(resolvedProjectDir);
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
+ };
25
+ }
26
+
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;
39
+ return {
40
+ mode: isStandalone ? "standalone" : "monorepo",
41
+ isStandalone,
42
+ contextRoot: isStandalone ? resolvedProjectDir : projectGitRoot,
43
+ projectDir: resolvedProjectDir,
44
+ projectRelativeDir: isStandalone
45
+ ? "."
46
+ : path.relative(projectGitRoot, resolvedProjectDir).split(path.sep).join("/"),
47
+ };
48
+ }
49
+
50
+ function detectReleaseMode(projectDir = process.cwd()) {
51
+ return detectReleaseContext({ projectDir }).mode;
52
+ }
53
+
54
+ module.exports = {
55
+ detectReleaseContext,
56
+ detectReleaseMode,
57
+ };
@@ -6,6 +6,8 @@ const { EXIT_SELECTION, inputText, selectOption, selectOptions } = require("../.
6
6
  const { composeRelease } = require("./compose-release");
7
7
  const { formatCicdLink } = require("./docker-build-push");
8
8
  const { loadDockerConfig } = require("./config-loader");
9
+ const { detectReleaseContext, detectReleaseMode } = require("./release-mode");
10
+ const { prepareMinimalMonorepoContext } = require("./minimal-context");
9
11
 
10
12
  // Jenkins 构建页“镜像版本”与 Webhook 通知均按北京时间展示。
11
13
  function beijingDateTime(now = new Date()) {
@@ -110,6 +112,21 @@ function trimPathInput(value) {
110
112
  const SAFE_GIT_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
111
113
  const SAFE_DOCKER_PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9._-]+)?$/;
112
114
  const SAFE_VERSION_REQUIREMENT = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
115
+ const WINDOWS_PACKAGE_MANAGERS = new Set(["npm", "npx", "pnpm", "yarn"]);
116
+ const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!\"]/;
117
+ const PRE_BUILD_MODES = new Set(["always", "monorepo", "standalone"]);
118
+ const BUILD_STRATEGIES = new Set(["artifact", "source"]);
119
+
120
+ function normalizePreBuildCommand(value, target) {
121
+ const entry = Array.isArray(value) ? { command: value, when: "always" } : value;
122
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
123
+ || !Array.isArray(entry.command) || entry.command.length === 0
124
+ || entry.command.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg))
125
+ || (entry.when != null && !PRE_BUILD_MODES.has(entry.when))) {
126
+ throw new Error(`${target} preBuild 必须是命令参数数组,或包含 command 与合法 when 的对象`);
127
+ }
128
+ return { command: entry.command, when: entry.when || "always" };
129
+ }
113
130
 
114
131
  function validateReleaseProfile(profile, target) {
115
132
  if (profile.pushBranch != null && (typeof profile.pushBranch !== "string"
@@ -135,11 +152,10 @@ function validateReleaseProfile(profile, target) {
135
152
  }
136
153
  }
137
154
  }
138
- if (profile.preBuild != null && (!Array.isArray(profile.preBuild) || profile.preBuild.length === 0
139
- || profile.preBuild.some((command) => !Array.isArray(command) || command.length === 0
140
- || command.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg))))) {
141
- throw new Error(`${target} preBuild 必须是非空命令参数数组列表`);
155
+ if (profile.preBuild != null && (!Array.isArray(profile.preBuild) || profile.preBuild.length === 0)) {
156
+ throw new Error(`${target} preBuild 必须是非空列表`);
142
157
  }
158
+ for (const command of profile.preBuild || []) normalizePreBuildCommand(command, target);
143
159
  }
144
160
 
145
161
  function compareVersions(actual, required) {
@@ -155,12 +171,43 @@ function compareVersions(actual, required) {
155
171
  }
156
172
 
157
173
  function windowsExecutable(command, platform = process.platform) {
158
- return platform === "win32" && ["npm", "npx", "pnpm", "yarn"].includes(command)
174
+ return platform === "win32" && WINDOWS_PACKAGE_MANAGERS.has(command)
159
175
  ? `${command}.cmd`
160
176
  : command;
161
177
  }
162
178
 
163
- function runReleasePreparation(profile, { run, capture, projectDir, push, platform = process.platform, log = console.log }) {
179
+ function quoteWindowsShellToken(value) {
180
+ const token = String(value);
181
+ if (UNSAFE_WINDOWS_SHELL_TOKEN.test(token)) {
182
+ throw new Error(`Windows 包管理器参数包含不安全字符: ${token}`);
183
+ }
184
+ return /[\s()]/.test(token) ? `"${token}"` : token;
185
+ }
186
+
187
+ function buildExecutableSpawn(command, args, {
188
+ platform = process.platform,
189
+ env = process.env,
190
+ } = {}) {
191
+ if (platform !== "win32" || !WINDOWS_PACKAGE_MANAGERS.has(command)) {
192
+ return { command, args };
193
+ }
194
+ const shellCommand = [command, ...args].map(quoteWindowsShellToken).join(" ");
195
+ return {
196
+ command: env.ComSpec || "cmd.exe",
197
+ args: ["/d", "/s", "/c", shellCommand],
198
+ };
199
+ }
200
+
201
+ function runReleasePreparation(profile, {
202
+ run,
203
+ capture,
204
+ projectDir,
205
+ push,
206
+ platform = process.platform,
207
+ env = process.env,
208
+ releaseMode = detectReleaseMode(projectDir),
209
+ log = console.log,
210
+ }) {
164
211
  validateReleaseProfile(profile, profile.label || "Docker target");
165
212
  const git = (...args) => capture("git", ["-C", projectDir, ...args]);
166
213
  if (git("status", "--porcelain", "--untracked-files=all")) {
@@ -182,16 +229,26 @@ function runReleasePreparation(profile, { run, capture, projectDir, push, platfo
182
229
  }
183
230
  }
184
231
  for (const [tool, requirement] of Object.entries(profile.requirements || {})) {
185
- const command = windowsExecutable(tool, platform);
186
232
  const args = tool === "node" ? ["--version"] : ["--version"];
187
- const actual = capture(command, args);
233
+ const invocation = buildExecutableSpawn(tool, args, { platform, env });
234
+ const actual = capture(invocation.command, invocation.args);
188
235
  if (!compareVersions(actual, requirement)) {
189
236
  throw new Error(`${tool} 必须满足 ${requirement},当前版本: ${actual || "无法识别"}`);
190
237
  }
191
238
  }
192
- for (const [command, ...args] of profile.preBuild || []) {
239
+ for (const rawCommand of profile.preBuild || []) {
240
+ const { command: commandArgs, when } = normalizePreBuildCommand(
241
+ rawCommand,
242
+ profile.label || "Docker target",
243
+ );
244
+ const [command, ...args] = commandArgs;
245
+ if (when !== "always" && when !== releaseMode) {
246
+ log(`跳过发布准备(当前 ${releaseMode} 模式,仅 ${when} 执行): ${commandArgs.join(" ")}`);
247
+ continue;
248
+ }
193
249
  log(`执行发布准备: ${command} ${args.join(" ")}`);
194
- run(windowsExecutable(command, platform), args, { cwd: projectDir });
250
+ const invocation = buildExecutableSpawn(command, args, { platform, env });
251
+ run(invocation.command, invocation.args, { cwd: projectDir });
195
252
  }
196
253
  }
197
254
 
@@ -221,6 +278,12 @@ function validateComponent(component, name, guardedByProfile = false) {
221
278
  if (component.mutableTags != null && typeof component.mutableTags !== "boolean") {
222
279
  throw new Error(`${name} mutableTags 必须是布尔值`);
223
280
  }
281
+ if (component.buildStrategy != null && !BUILD_STRATEGIES.has(component.buildStrategy)) {
282
+ throw new Error(`${name} buildStrategy 只支持 artifact 或 source`);
283
+ }
284
+ if (component.buildStrategy === "source" && component.files != null) {
285
+ throw new Error(`${name} source 构建不能同时配置 files 产物上下文`);
286
+ }
224
287
  if (component.buildArgs != null && (!component.buildArgs || typeof component.buildArgs !== "object"
225
288
  || Array.isArray(component.buildArgs) || Object.entries(component.buildArgs).some(([key, value]) =>
226
289
  !/^[A-Z_][A-Z0-9_]*$/.test(key) || !["string", "number", "boolean"].includes(typeof value)))) {
@@ -255,6 +318,7 @@ async function runTargetRelease(options = {}, dependencies = {}) {
255
318
  const targets = config?.targets;
256
319
  if (!targets || !Object.keys(targets).length) throw new Error("请配置 infly.docker.targets");
257
320
  const releaseScripts = config?.releaseScripts || {};
321
+ const releaseContext = detectReleaseContext({ projectDir });
258
322
  const log = dependencies.log || console.log;
259
323
  const cicdLink = formatCicdLink(options.cicdUrl);
260
324
  const target = options.target || await (dependencies.selectOption || selectOption)("请选择构建平台",
@@ -343,7 +407,7 @@ async function runTargetRelease(options = {}, dependencies = {}) {
343
407
  const overrides = `${options.backendDir ? ` --backend-dir "${options.backendDir}"` : ""}${options.config ? ` --config "${options.config}"` : ""}`;
344
408
  const rerun = releaseScript
345
409
  ? `pnpm run ${releaseScript} -- --platform ${target}${overrides}`
346
- : `pnpm exec infly-libs docker:release --project-dir "${projectDir}" --target ${target} --components ${components.join(",")}${overrides} ${options.push ? "--push" : "--no-push"}`;
410
+ : `pnpm exec infly-libs release:docker --project-dir "${projectDir}" --target ${target} --components ${components.join(",")}${overrides} ${options.push ? "--push" : "--no-push"}`;
347
411
  log(`${source.url ? "3" : "2"}. ${rerun}`);
348
412
  }
349
413
  return { target, missingSources: missing.map((item) => item.name) };
@@ -352,7 +416,8 @@ async function runTargetRelease(options = {}, dependencies = {}) {
352
416
  const capture = (command, args) => String(run(command, args, { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) || "").trim();
353
417
  if (profile.pushRef || profile.requirements || profile.preBuild) {
354
418
  runReleasePreparation(profile, { run, capture, projectDir, push: Boolean(options.push),
355
- platform: dependencies.platform, log });
419
+ platform: dependencies.platform, env: dependencies.env,
420
+ releaseMode: releaseContext.mode, log });
356
421
  }
357
422
  await checkDocker(run, projectDir, true, dependencies);
358
423
  const results = [];
@@ -381,8 +446,34 @@ async function runTargetRelease(options = {}, dependencies = {}) {
381
446
  const sourceLabel = item.name === "backend" ? "后端" : (item.label || item.name);
382
447
  log(`\x1b[0;32m✓ ${sourceLabel}构建分支:${item.source.branch}\x1b[0m`);
383
448
  }
384
- let context = inside(sourceDir, item.context || ".");
449
+ const buildStrategy = item.buildStrategy || "artifact";
450
+ const componentReleaseContext = item.source
451
+ ? { mode: "standalone", contextRoot: sourceDir, projectRelativeDir: "." }
452
+ : releaseContext;
453
+ let context = buildStrategy === "source"
454
+ ? componentReleaseContext.contextRoot
455
+ : inside(sourceDir, item.context || ".");
385
456
  let dockerfile = inside(sourceDir, item.dockerfile || "Dockerfile");
457
+ let workspaceRevision;
458
+ if (buildStrategy === "source" && componentReleaseContext.mode === "monorepo") {
459
+ const workspaceChanges = capture("git", ["-C", context, "status", "--porcelain", "--untracked-files=all"]);
460
+ if (workspaceChanges) {
461
+ throw new Error(`${item.name} 的 monorepo 构建上下文存在未提交改动`);
462
+ }
463
+ workspaceRevision = capture("git", ["-C", context, "rev-parse", "HEAD"]).toLowerCase();
464
+ if (!/^[a-f0-9]{40}$/.test(workspaceRevision)) {
465
+ throw new Error(`${item.name} 无法解析合法的 monorepo revision`);
466
+ }
467
+ const prepared = (dependencies.prepareMinimalMonorepoContext || prepareMinimalMonorepoContext)({
468
+ workspaceRoot: componentReleaseContext.contextRoot,
469
+ projectDir: sourceDir,
470
+ io,
471
+ });
472
+ tempRoot = prepared.contextRoot;
473
+ context = prepared.contextRoot;
474
+ dockerfile = inside(context, `${prepared.projectRelativeDir}/${item.dockerfile || "Dockerfile"}`);
475
+ log(`最小上下文: ${prepared.projectRelativeDir} + packages + 根锁文件`);
476
+ }
386
477
  for (const file of item.requiredFiles || []) {
387
478
  if (!io.existsSync(inside(sourceDir, file))) throw new Error(`缺少必需构建产物: ${file}`);
388
479
  }
@@ -406,11 +497,19 @@ async function runTargetRelease(options = {}, dependencies = {}) {
406
497
  const buildOptions = ["buildx", "build", "--load", "--file", dockerfile];
407
498
  if (item.platform) buildOptions.push("--platform", item.platform);
408
499
  if (item.target) buildOptions.push("--target", item.target);
409
- for (const [key, value] of Object.entries(item.buildArgs || {})) {
500
+ const buildArgs = {
501
+ ...(item.buildArgs || {}),
502
+ ...(buildStrategy === "source" ? {
503
+ BUILD_MODE: componentReleaseContext.mode,
504
+ PROJECT_DIR: componentReleaseContext.projectRelativeDir,
505
+ } : {}),
506
+ };
507
+ for (const [key, value] of Object.entries(buildArgs)) {
410
508
  buildOptions.push("--build-arg", `${key}=${value}`);
411
509
  }
412
510
  run("docker", [...buildOptions,
413
511
  "--label", `org.opencontainers.image.revision=${commit}`, "--label", `org.opencontainers.image.version=${commit}`,
512
+ ...(workspaceRevision ? ["--label", `com.infly.workspace.revision=${workspaceRevision}`] : []),
414
513
  "--label", `com.infly.platform=${target}`, "--tag", image,
415
514
  ...(latestImage ? ["--tag", latestImage] : []), context], { cwd: projectDir });
416
515
  if (capture("docker", ["image", "inspect", "--format", '{{ index .Config.Labels "org.opencontainers.image.revision" }}', image]) !== commit) {
@@ -474,5 +573,5 @@ async function runTargetRelease(options = {}, dependencies = {}) {
474
573
  return { target, results };
475
574
  }
476
575
 
477
- module.exports = { compareVersions, parseReleaseArgs, runReleasePreparation, runTargetRelease,
478
- validateReleaseProfile, windowsExecutable };
576
+ module.exports = { buildExecutableSpawn, compareVersions, detectReleaseContext, detectReleaseMode, normalizePreBuildCommand,
577
+ parseReleaseArgs, runReleasePreparation, runTargetRelease, validateReleaseProfile, windowsExecutable };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infly/libs",
3
- "version": "2.2.14",
3
+ "version": "2.2.16",
4
4
  "description": "不受前端框架限制的独立工具库",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",