@dongnanyang/deploy-cli 0.7.0 → 0.8.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/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  const argv = process.argv.slice(2);
3
3
  if (argv.length === 0 || argv[0] === "tui") await import("./main.js");
4
4
  else {
5
- const cli = await import("./cli-Dl4SYt_0.js");
5
+ const cli = await import("./cli-BcnQXZsp.js");
6
6
  process.exitCode = await cli.main(argv);
7
7
  }
8
8
  //#endregion
@@ -1,157 +1,30 @@
1
- import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-CVqFEtQB.js";
1
+ import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-DuBKPLi2.js";
2
2
  import { readFileSync } from "fs";
3
3
  import { resolve } from "path";
4
- import { parse, stringify } from "yaml";
5
4
  import { accessSync, constants, existsSync as existsSync$1, lstatSync, readFileSync as readFileSync$1, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
6
- import { join as join$1, resolve as resolve$1 } from "node:path";
7
- import { spawn } from "node:child_process";
8
- //#region src/core/project.ts
9
- const VALID_TYPES = [
10
- "compose",
11
- "image",
12
- "static"
13
- ];
14
- const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
15
- const VALID_SSL = [
16
- "none",
17
- "acme",
18
- "custom"
19
- ];
20
- const VALID_UPDATE = ["git-pull", "none"];
21
- /** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
22
- var ProjectConfigError = class extends Error {
23
- field;
24
- constructor(message, field) {
25
- super(message);
26
- this.name = "ProjectConfigError";
27
- this.field = field;
28
- }
29
- };
30
- /** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
31
- function loadProject(dir) {
32
- const yamlPath = resolve(dir, "deploy.yaml");
33
- let raw;
34
- try {
35
- raw = readFileSync(yamlPath, "utf-8");
36
- } catch (error) {
37
- const reason = error instanceof Error ? error.message : String(error);
38
- if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
39
- throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
40
- }
41
- let parsed;
42
- try {
43
- parsed = parse(raw);
44
- } catch (error) {
45
- throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
46
- }
47
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
48
- return validate(parsed);
49
- }
50
- /** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 → deploy 段值域 */
51
- function validate(raw) {
52
- const name = raw.name;
53
- if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
54
- const type = raw.type;
55
- if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
56
- if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
57
- if (type === "image" && (typeof raw.image !== "string" || raw.image.trim() === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
58
- if (type === "static" && (typeof raw.root !== "string" || raw.root.trim() === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
59
- if (raw.nginx !== void 0 && raw.nginx !== null) {
60
- const nginx = raw.nginx;
61
- if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
62
- const n = nginx;
63
- if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
64
- if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
65
- }
66
- if (raw.deploy !== void 0 && raw.deploy !== null) {
67
- const deploy = raw.deploy;
68
- if (typeof deploy !== "object" || Array.isArray(deploy)) throw new ProjectConfigError("deploy 应为对象", "deploy");
69
- const dp = deploy;
70
- if (dp.update !== void 0 && dp.update !== null) {
71
- if (typeof dp.update !== "string" || !VALID_UPDATE.includes(dp.update)) throw new ProjectConfigError(`deploy.update 非法: ${JSON.stringify(dp.update)},合法值: git-pull | none(不设=不自动更新)`, "deploy.update");
72
- }
73
- if (dp.build !== void 0 && dp.build !== null && typeof dp.build !== "string") throw new ProjectConfigError("deploy.build 应为字符串(构建命令)", "deploy.build");
74
- for (const hook of ["pre", "post"]) {
75
- const hooks = dp[hook];
76
- if (hooks !== void 0 && hooks !== null && (!Array.isArray(hooks) || hooks.some((c) => typeof c !== "string"))) throw new ProjectConfigError(`deploy.${hook} 应为字符串数组(命令列表)`, `deploy.${hook}`);
77
- }
78
- }
79
- const d = raw;
80
- if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
81
- return d;
82
- }
83
- /** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
84
- function listProjects(cfg) {
85
- return cfg.projects.map((project) => {
86
- try {
87
- return {
88
- name: project.name,
89
- path: project.path,
90
- config: loadProject(project.path)
91
- };
92
- } catch (error) {
93
- return {
94
- name: project.name,
95
- path: project.path,
96
- config: null,
97
- error: error instanceof Error ? error.message : String(error)
98
- };
99
- }
100
- });
101
- }
102
- /** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig) */
103
- function addProject(cfg, dir) {
104
- const config = loadProject(dir);
105
- const byName = cfg.projects.find((p) => p.name === config.name);
106
- if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
107
- const byPath = cfg.projects.find((p) => p.path === dir);
108
- if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${dir}`);
109
- const entry = {
110
- name: config.name,
111
- path: dir,
112
- deployDir: "deploy"
113
- };
114
- return {
115
- ...cfg,
116
- projects: [...cfg.projects, entry]
117
- };
118
- }
119
- /** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
120
- function removeProject(cfg, name) {
121
- const projects = cfg.projects.filter((p) => p.name !== name);
122
- if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
123
- return {
124
- ...cfg,
125
- projects
126
- };
127
- }
128
- /** image 型生成的 docker-compose.yml 标记头(护栏 marker):既有同名文件无此头则拒绝覆盖(终审 M1:防绑架项目文件) */
129
- const COMPOSE_MARKER = "# generated by deploy-cli — do not edit";
130
- /** 既有文件内容是否带 COMPOSE_MARKER 头(首行) */
131
- function hasComposeMarker(content) {
132
- return content.split("\n", 1)[0]?.trim() === COMPOSE_MARKER;
133
- }
134
- /** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment),首行带 COMPOSE_MARKER 标记头 */
135
- function generateCompose(d) {
136
- if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
137
- if (typeof d.image !== "string" || d.image.trim() === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
138
- const service = { image: d.image };
139
- if (d.ports && d.ports.length > 0) service.ports = d.ports;
140
- if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
141
- if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
142
- return `${COMPOSE_MARKER}\n${stringify({ services: { [d.name]: service } })}`;
143
- }
144
- //#endregion
5
+ import { dirname as dirname$1, join as join$1, resolve as resolve$1 } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { parse, stringify } from "yaml";
8
+ import { execFileSync, spawn } from "node:child_process";
145
9
  //#region src/core/exec.ts
146
10
  /**
147
- * stderr 摘要(失败信息用):优先命中 /error|fatal|failed/i 的行(至多尾 3 条),无命中取尾部 3 行。
148
- * docker compose / nginx 等工具把进度打在 stderr 前部,取前部会挤掉真错误行(M1-T5 评审修复,R12 同缺陷同修)。
11
+ * stderr 摘要(失败信息用):优先命中 /error|fatal|failed|emerg|alert|crit/i 的行(至多尾 3 条),无命中取尾部 3 行。
12
+ * docker compose / nginx 等工具把进度打在 stderr 前部,取前部会挤掉真错误行(M1-T5 评审修复,R12 同缺陷同修);
13
+ * nginx 的 [emerg]/[alert]/[crit] 级别行同为错误行(M2-T2 #1 匹配集补齐)。
149
14
  */
150
15
  function stderrSummary(stderr) {
151
16
  const lines = stderr.trim().split("\n").filter((line) => line.trim() !== "");
152
- const errors = lines.filter((line) => /error|fatal|failed/i.test(line));
17
+ const errors = lines.filter((line) => /error|fatal|failed|emerg|alert|crit/i.test(line));
153
18
  return (errors.length > 0 ? errors.slice(-3) : lines.slice(-3)).join(" ");
154
19
  }
20
+ /**
21
+ * 失败信息统一文案模板(M2-T2 #2 壳统一):命令原文 + exit 码 + stderr 摘要(无输出时注明)。
22
+ * docker.ts(execFailureMessage 复用/再导出)与 nginx.ts(execFailure 包裹 ExecError)共用本模板,R12 同口径。
23
+ */
24
+ function execFailureMessage(cmd, args, result) {
25
+ const summary = stderrSummary(result.stderr);
26
+ return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
27
+ }
155
28
  /** 仅 spawn 失败(ENOENT)与超时抛出 */
156
29
  var ExecError = class extends Error {
157
30
  result;
@@ -163,6 +36,39 @@ var ExecError = class extends Error {
163
36
  };
164
37
  /** 超时 SIGTERM 后等待子进程退出的宽限时长,超过则 SIGKILL */
165
38
  const KILL_GRACE_MS = 3e3;
39
+ /** pid 的全部后代进程(ps pid/ppid 祖先链);ps 不可用时退化为空数组(只杀直接子进程,F8 尽力而为) */
40
+ function descendantPids(pid) {
41
+ let table;
42
+ try {
43
+ table = execFileSync("ps", ["-axo", "pid=,ppid="], { encoding: "utf-8" });
44
+ } catch {
45
+ return [];
46
+ }
47
+ const childrenOf = /* @__PURE__ */ new Map();
48
+ for (const line of table.split("\n")) {
49
+ const [p, pp] = line.trim().split(/\s+/);
50
+ const child = Number(p);
51
+ const parent = Number(pp);
52
+ if (!Number.isInteger(child) || !Number.isInteger(parent)) continue;
53
+ const list = childrenOf.get(parent);
54
+ if (list) list.push(child);
55
+ else childrenOf.set(parent, [child]);
56
+ }
57
+ const out = [];
58
+ const seen = /* @__PURE__ */ new Set([pid]);
59
+ const queue = [pid];
60
+ while (queue.length > 0) {
61
+ const current = queue.pop();
62
+ if (current === void 0) break;
63
+ for (const child of childrenOf.get(current) ?? []) {
64
+ if (seen.has(child)) continue;
65
+ seen.add(child);
66
+ out.push(child);
67
+ queue.push(child);
68
+ }
69
+ }
70
+ return out;
71
+ }
166
72
  /** 按 \n 切行缓冲,结束时补发无结尾换行的残行 */
167
73
  function createLineBuffer(stream, onLine) {
168
74
  let buffer = "";
@@ -210,6 +116,15 @@ async function run(cmd, args, opts = {}) {
210
116
  });
211
117
  const out = createLineBuffer("stdout", opts.onLine);
212
118
  const err = createLineBuffer("stderr", opts.onLine);
119
+ /** 超时终止整个进程树(F8):bash -c 钩子/构建的孙进程随子进程一并 SIGTERM/SIGKILL,避免孤儿继续跑 */
120
+ const killTree = (signal) => {
121
+ if (child.pid !== void 0) for (const pid of descendantPids(child.pid)) try {
122
+ process.kill(pid, signal);
123
+ } catch {}
124
+ try {
125
+ child.kill(signal);
126
+ } catch {}
127
+ };
213
128
  let settled = false;
214
129
  let timedOut = false;
215
130
  let timeoutNote = "";
@@ -217,8 +132,8 @@ async function run(cmd, args, opts = {}) {
217
132
  const timeoutTimer = opts.timeoutMs ? setTimeout(() => {
218
133
  timedOut = true;
219
134
  timeoutNote = `timeout: ${cmdLine}\n`;
220
- child.kill("SIGTERM");
221
- killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
135
+ killTree("SIGTERM");
136
+ killTimer = setTimeout(() => killTree("SIGKILL"), KILL_GRACE_MS);
222
137
  }, opts.timeoutMs) : void 0;
223
138
  child.stdout?.setEncoding("utf-8");
224
139
  child.stderr?.setEncoding("utf-8");
@@ -257,113 +172,12 @@ async function run(cmd, args, opts = {}) {
257
172
  });
258
173
  }
259
174
  //#endregion
260
- //#region src/core/docker.ts
261
- /** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
262
- function logsArgs(idOrName, o) {
263
- const args = ["logs"];
264
- if (o?.tail !== void 0) args.push("--tail", String(o.tail));
265
- if (o?.follow) args.push("--follow");
266
- args.push(idOrName);
267
- return args;
268
- }
269
- /** 失败信息:命令原文 + exit 码 + stderr 摘要(stderrSummary:优先错误行、否则尾部——docker compose 等工具把进度打在 stderr 前部) */
270
- function execFailureMessage(cmd, args, result) {
271
- const summary = stderrSummary(result.stderr);
272
- return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
273
- }
274
- /** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 (l) => void */
275
- function adaptOnLine(onLine) {
276
- return onLine ? (line) => onLine(line) : void 0;
277
- }
278
- /** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
279
- function parseContainerLine(line) {
280
- let raw;
281
- try {
282
- raw = JSON.parse(line);
283
- } catch (error) {
284
- const reason = error instanceof Error ? error.message : String(error);
285
- throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
286
- }
287
- return {
288
- id: String(raw.ID ?? raw.Id ?? ""),
289
- name: String(raw.Names ?? ""),
290
- image: String(raw.Image ?? ""),
291
- state: String(raw.State ?? ""),
292
- status: String(raw.Status ?? ""),
293
- ports: String(raw.Ports ?? "")
294
- };
295
- }
296
- /** 以 shell-out 方式实现的 docker 操作集合 */
297
- function createDocker(runner = run) {
298
- return {
299
- async listContainers(o) {
300
- const args = ["ps"];
301
- if (o?.all) args.push("-a");
302
- if (o?.name) args.push("--filter", `name=${o.name}`);
303
- args.push("--format", "{{json .}}");
304
- const result = await runner("docker", args);
305
- if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
306
- return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
307
- },
308
- async logs(idOrName, o) {
309
- return await runner("docker", logsArgs(idOrName, o), { onLine: adaptOnLine(o?.onLine) });
310
- },
311
- async composeUp(cwd, composeFile, o) {
312
- const args = [
313
- "compose",
314
- "-f",
315
- composeFile,
316
- "up",
317
- "-d"
318
- ];
319
- if (o?.build) args.push("--build");
320
- return await runner("docker", args, {
321
- cwd,
322
- onLine: adaptOnLine(o?.onLine)
323
- });
324
- },
325
- async composeDown(cwd, composeFile, o) {
326
- return await runner("docker", [
327
- "compose",
328
- "-f",
329
- composeFile,
330
- "down"
331
- ], {
332
- cwd,
333
- onLine: adaptOnLine(o?.onLine)
334
- });
335
- },
336
- async composeBuild(cwd, composeFile, o) {
337
- return await runner("docker", [
338
- "compose",
339
- "-f",
340
- composeFile,
341
- "build"
342
- ], {
343
- cwd,
344
- onLine: adaptOnLine(o?.onLine)
345
- });
346
- },
347
- async restart(idOrName) {
348
- return await runner("docker", ["restart", idOrName]);
349
- },
350
- async stop(idOrName) {
351
- return await runner("docker", ["stop", idOrName]);
352
- },
353
- async remove(idOrName, o) {
354
- const args = ["rm"];
355
- if (o?.force) args.push("--force");
356
- args.push(idOrName);
357
- return await runner("docker", args);
358
- }
359
- };
360
- }
361
- //#endregion
362
175
  //#region src/core/nginx.ts
363
176
  /** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
364
177
  const CONF_PREFIX = "deploy-cli-";
365
178
  const CONF_SUFFIX = ".conf";
366
- const SLUG_RE = /^[a-z0-9-]+$/;
179
+ /** slug 合法形状(M2-T2 #6 收紧):小写字母数字与连字符、不得连字符开头;项目 name 同用作 slug(F4 前移校验共用) */
180
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
367
181
  /** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
368
182
  const DOMAIN_RE = /^(\*\.)?[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
369
183
  const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
@@ -373,6 +187,22 @@ const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
373
187
  const DEFAULT_CONF_D = "/etc/nginx/conf.d";
374
188
  /** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
375
189
  const ACME_HOME = "/root/.acme.sh";
190
+ /** acme.sh 实际二进制路径(R6 约定);doctor 与 requestCert 共用同一路径探测(F1 对齐) */
191
+ const ACME_BIN = `${ACME_HOME}/acme.sh`;
192
+ /** acme.sh 在场探测命令(F1:doctor 与 requestCert 共用,勿各自另写探测) */
193
+ function acmeProbeCommand() {
194
+ return {
195
+ cmd: "sh",
196
+ args: ["-c", `test -x ${ACME_BIN}`]
197
+ };
198
+ }
199
+ /** certbot 在场探测命令(F1:doctor 与 requestCert 共用) */
200
+ function certbotProbeCommand() {
201
+ return {
202
+ cmd: "sh",
203
+ args: ["-c", "command -v certbot"]
204
+ };
205
+ }
376
206
  /** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
377
207
  const ACME_RENEW_SKIP = 2;
378
208
  /** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
@@ -386,7 +216,11 @@ function pathExists(path) {
386
216
  }
387
217
  /** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
388
218
  function validateSlug(slug) {
389
- if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符(禁止路径字符与大写)`);
219
+ if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符且以字母数字开头(禁止路径字符与大写)`);
220
+ }
221
+ /** slug 合法判定(F4:项目 name 用作 conf slug,loadProject 以同一正则前移校验,防部署到 nginx 步才被拒) */
222
+ function isValidSlug(slug) {
223
+ return SLUG_RE.test(slug);
390
224
  }
391
225
  function validateSpec(spec) {
392
226
  validateSlug(spec.slug);
@@ -405,10 +239,26 @@ function validateSpec(spec) {
405
239
  function validateAbsPath(field, value) {
406
240
  if (!ABS_PATH_RE.test(value)) throw new Error(`NginxSiteSpec.${field} 非法: ${JSON.stringify(value)},须为绝对路径且不含 conf 元字符与空白`);
407
241
  }
408
- /** 失败信息:命令原文 + exit 码 + stderr 摘要(stderrSummary:优先错误行、否则尾部,R12 与 docker.ts 同口径;包裹为 ExecError,附完整结果) */
242
+ /** 失败信息:统一走 core/exec 文案模板(M2-T2 #2 壳统一,R12 与 docker.ts 同口径),可附提示,包裹为 ExecError 附完整结果 */
409
243
  function execFailure(cmd, args, result, note) {
410
- const summary = stderrSummary(result.stderr);
411
- return new ExecError(`${note ? `${note}: ` : ""}命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`, result);
244
+ return new ExecError(`${note ? `${note}: ` : ""}${execFailureMessage(cmd, args, result)}`, result);
245
+ }
246
+ /**
247
+ * 回滚单项守护(R13):逐项执行,单项失败记 stderr 继续恢复其余项;回滚自身绝不抛错——
248
+ * 不得让回滚异常掩盖 nginx -t / 写盘段的原始错误。
249
+ */
250
+ function guardedRestore(items) {
251
+ for (const item of items) try {
252
+ item.fn();
253
+ } catch (error) {
254
+ console.error(`[nginx] 回滚 ${item.what} 失败: ${error instanceof Error ? error.message : String(error)}`);
255
+ }
256
+ }
257
+ /** reload 失败统一包装(R13 Minor 4):reject 通道与 code!==0 同 F6 条件化文案;ExecError 保留 result 透传 */
258
+ function wrapReloadFailure(error, note) {
259
+ const reason = error instanceof Error ? error.message : String(error);
260
+ if (error instanceof ExecError) return new ExecError(`${note}: ${reason}`, error.result);
261
+ return new Error(`${note}: ${reason}`, { cause: error });
412
262
  }
413
263
  /**
414
264
  * 路径探测:sites-available 与 sites-enabled 同时存在 → sites 模式(软链);否则 conf.d 模式(无软链)。
@@ -466,23 +316,48 @@ function createNginx(runner = run, paths) {
466
316
  /**
467
317
  * 写盘/回滚流程:新内容写隐藏 .conf.new → 旧 conf 备份隐藏 .bak → .new 原子改名 → 建 sites-enabled 软链 → nginx -t;
468
318
  * 失败:恢复 .bak(或删新文件)、移除本次新建的软链、抛 ExecError;成功:nginx -s reload、清 .bak。
319
+ * 写盘段(写 .new/改名/软链)与 nginx -t 同一回滚口径(M2-T2 #8):段内任一 fs 操作失败即整体恢复再抛出。
469
320
  */
470
321
  async function writeSite(slug, content) {
471
322
  const conf = join$1(sitesAvailable, confName(slug));
472
323
  const tmp = join$1(sitesAvailable, tmpName(slug));
473
324
  const bak = join$1(sitesAvailable, bakName(slug));
474
- writeFileSync$1(tmp, content, "utf-8");
475
- const existed = pathExists(conf);
476
- if (existed) renameSync(conf, bak);
477
- renameSync(tmp, conf);
478
325
  const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
326
+ const existed = pathExists(conf);
479
327
  const linkCreated = link ? !pathExists(link) : false;
480
- if (link && linkCreated) symlinkSync(conf, link);
328
+ /** 统一回滚:恢复/清除 conf、软链、.new 临时文件(R13:逐项守护,单项失败记 stderr 继续,回滚不抛) */
481
329
  const rollback = () => {
482
- if (existed) renameSync(bak, conf);
483
- else unlinkSync(conf);
484
- if (link && linkCreated) unlinkSync(link);
330
+ guardedRestore([
331
+ {
332
+ what: "站点 conf",
333
+ fn: () => {
334
+ if (existed) renameSync(bak, conf);
335
+ else if (pathExists(conf)) unlinkSync(conf);
336
+ }
337
+ },
338
+ {
339
+ what: "软链",
340
+ fn: () => {
341
+ if (link && linkCreated && pathExists(link)) unlinkSync(link);
342
+ }
343
+ },
344
+ {
345
+ what: "临时文件",
346
+ fn: () => {
347
+ if (pathExists(tmp)) unlinkSync(tmp);
348
+ }
349
+ }
350
+ ]);
485
351
  };
352
+ try {
353
+ writeFileSync$1(tmp, content, "utf-8");
354
+ if (existed) renameSync(conf, bak);
355
+ renameSync(tmp, conf);
356
+ if (link && linkCreated) symlinkSync(conf, link);
357
+ } catch (error) {
358
+ rollback();
359
+ throw error;
360
+ }
486
361
  let test;
487
362
  try {
488
363
  test = await runner("nginx", ["-t"]);
@@ -494,33 +369,43 @@ function createNginx(runner = run, paths) {
494
369
  rollback();
495
370
  throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
496
371
  }
372
+ const reloadNote = existed ? `nginx reload 失败,保留备份 ${bak} 供人工恢复` : `nginx reload 失败(新建站点无备份可回退),conf 已写入 ${conf},可手工 nginx -s reload 重试或删除该 conf`;
497
373
  let reload;
498
374
  try {
499
375
  reload = await runner("nginx", ["-s", "reload"]);
500
376
  } catch (error) {
501
- throw error;
377
+ throw wrapReloadFailure(error, reloadNote);
502
378
  }
503
- if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
379
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, reloadNote);
504
380
  if (existed) unlinkSync(bak);
505
381
  }
506
382
  async function requestCert(domain) {
507
- const acmeBin = `${ACME_HOME}/acme.sh`;
508
- if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
383
+ if (!DOMAIN_RE.test(domain)) throw new Error(`requestCert domain 非法: ${JSON.stringify(domain)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止元字符与空白)`);
384
+ const acme = acmeProbeCommand();
385
+ if ((await runner(acme.cmd, acme.args)).code === 0) {
509
386
  const args = [
510
387
  "--issue",
511
388
  "--nginx",
512
389
  "-d",
513
390
  domain
514
391
  ];
515
- const result = await runner(acmeBin, args);
516
- if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
517
- return {
518
- tool: "acme.sh",
392
+ const result = await runner(ACME_BIN, args);
393
+ if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(ACME_BIN, args, result, `acme.sh 签发失败: ${domain}`);
394
+ const candidates = [{
519
395
  certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
520
396
  keyPath: `${ACME_HOME}/${domain}/${domain}.key`
397
+ }, {
398
+ certPath: `${ACME_HOME}/${domain}_ecc/fullchain.cer`,
399
+ keyPath: `${ACME_HOME}/${domain}_ecc/${domain}.key`
400
+ }];
401
+ for (const candidate of candidates) if ((await runner("sh", ["-c", `test -f "${candidate.certPath}"`])).code === 0) return {
402
+ tool: "acme.sh",
403
+ ...candidate
521
404
  };
405
+ throw new Error(`acme.sh 签发完成但未找到证书文件(已探测 ${candidates.map((c) => c.certPath).join(" 与 ")}),请检查 acme.sh 安装证书目录`);
522
406
  }
523
- if ((await runner("sh", ["-c", "command -v certbot"])).code === 0) {
407
+ const certbot = certbotProbeCommand();
408
+ if ((await runner(certbot.cmd, certbot.args)).code === 0) {
524
409
  const args = [
525
410
  "--nginx",
526
411
  "-d",
@@ -544,7 +429,14 @@ function createNginx(runner = run, paths) {
544
429
  validateSpec(spec);
545
430
  if (spec.ssl === "acme") {
546
431
  await writeSite(spec.slug, renderBlock(spec, false));
547
- const cert = await requestCert(spec.serverName);
432
+ let cert;
433
+ try {
434
+ cert = await requestCert(spec.serverName);
435
+ } catch (error) {
436
+ const message = `${error instanceof Error ? error.message : String(error)};注意:HTTP 块已上线(deploy-cli-${spec.slug}.conf 已生效,站点当前仅 HTTP)`;
437
+ if (error instanceof ExecError) throw new ExecError(message, error.result);
438
+ throw new Error(message, { cause: error });
439
+ }
548
440
  await writeSite(spec.slug, renderBlock({
549
441
  ...spec,
550
442
  certPath: cert.certPath,
@@ -561,12 +453,28 @@ function createNginx(runner = run, paths) {
561
453
  const bak = join$1(sitesAvailable, bakName(slug));
562
454
  const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
563
455
  const hadLink = link ? pathExists(link) : false;
564
- renameSync(conf, bak);
565
- if (link && hadLink) unlinkSync(link);
456
+ /**
457
+ * 与 applySite 同等回滚对等(R2)+ 写盘段同款收口(R13):逐项守护(单项失败记 stderr 继续恢复其余项),
458
+ * 回滚自身绝不抛错;软链仅在缺失时重建(unlink 失败的半删场景下软链仍在,不得 EEXIST 二次伤害)。
459
+ */
566
460
  const rollback = () => {
567
- renameSync(bak, conf);
568
- if (link && hadLink) symlinkSync(conf, link);
461
+ guardedRestore([{
462
+ what: "站点 conf",
463
+ fn: () => renameSync(bak, conf)
464
+ }, {
465
+ what: "软链",
466
+ fn: () => {
467
+ if (link && hadLink && !pathExists(link)) symlinkSync(conf, link);
468
+ }
469
+ }]);
569
470
  };
471
+ try {
472
+ renameSync(conf, bak);
473
+ if (link && hadLink) unlinkSync(link);
474
+ } catch (error) {
475
+ rollback();
476
+ throw error;
477
+ }
570
478
  let test;
571
479
  try {
572
480
  test = await runner("nginx", ["-t"]);
@@ -578,13 +486,14 @@ function createNginx(runner = run, paths) {
578
486
  rollback();
579
487
  throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
580
488
  }
489
+ const reloadNote = `nginx reload 失败,保留备份 ${bak} 供人工恢复`;
581
490
  let reload;
582
491
  try {
583
492
  reload = await runner("nginx", ["-s", "reload"]);
584
493
  } catch (error) {
585
- throw error;
494
+ throw wrapReloadFailure(error, reloadNote);
586
495
  }
587
- if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
496
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, reloadNote);
588
497
  unlinkSync(bak);
589
498
  },
590
499
  async listSites() {
@@ -594,6 +503,254 @@ function createNginx(runner = run, paths) {
594
503
  };
595
504
  }
596
505
  //#endregion
506
+ //#region src/core/project.ts
507
+ const VALID_TYPES = [
508
+ "compose",
509
+ "image",
510
+ "static"
511
+ ];
512
+ const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
513
+ const VALID_SSL = [
514
+ "none",
515
+ "acme",
516
+ "custom"
517
+ ];
518
+ const VALID_UPDATE = ["git-pull", "none"];
519
+ /** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
520
+ var ProjectConfigError = class extends Error {
521
+ field;
522
+ constructor(message, field) {
523
+ super(message);
524
+ this.name = "ProjectConfigError";
525
+ this.field = field;
526
+ }
527
+ };
528
+ /** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
529
+ function loadProject(dir) {
530
+ const yamlPath = resolve(dir, "deploy.yaml");
531
+ let raw;
532
+ try {
533
+ raw = readFileSync(yamlPath, "utf-8");
534
+ } catch (error) {
535
+ const reason = error instanceof Error ? error.message : String(error);
536
+ if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
537
+ throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
538
+ }
539
+ let parsed;
540
+ try {
541
+ parsed = parse(raw);
542
+ } catch (error) {
543
+ throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
544
+ }
545
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
546
+ return validate(parsed);
547
+ }
548
+ /** 校验并规范化 deploy.yaml 模型:name(含 slug 形状)→ type 合法性 → 类型必填字段 → nginx.domain 非空 → deploy 段值域 */
549
+ function validate(raw) {
550
+ const name = raw.name;
551
+ if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
552
+ if (!isValidSlug(name)) throw new ProjectConfigError(`name 非法: ${JSON.stringify(name)},仅允许小写字母、数字与连字符且以字母数字开头(name 将用作 nginx 站点 slug)`, "name");
553
+ const type = raw.type;
554
+ if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
555
+ if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
556
+ if (type === "image" && (typeof raw.image !== "string" || raw.image.trim() === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
557
+ if (type === "static" && (typeof raw.root !== "string" || raw.root.trim() === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
558
+ if (raw.nginx !== void 0 && raw.nginx !== null) {
559
+ const nginx = raw.nginx;
560
+ if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
561
+ const n = nginx;
562
+ if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
563
+ if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
564
+ }
565
+ if (raw.deploy !== void 0 && raw.deploy !== null) {
566
+ const deploy = raw.deploy;
567
+ if (typeof deploy !== "object" || Array.isArray(deploy)) throw new ProjectConfigError("deploy 应为对象", "deploy");
568
+ const dp = deploy;
569
+ if (dp.update !== void 0 && dp.update !== null) {
570
+ if (typeof dp.update !== "string" || !VALID_UPDATE.includes(dp.update)) throw new ProjectConfigError(`deploy.update 非法: ${JSON.stringify(dp.update)},合法值: git-pull | none(不设=不自动更新)`, "deploy.update");
571
+ }
572
+ if (dp.build !== void 0 && dp.build !== null && typeof dp.build !== "string") throw new ProjectConfigError("deploy.build 应为字符串(构建命令)", "deploy.build");
573
+ for (const hook of ["pre", "post"]) {
574
+ const hooks = dp[hook];
575
+ if (hooks !== void 0 && hooks !== null && (!Array.isArray(hooks) || hooks.some((c) => typeof c !== "string"))) throw new ProjectConfigError(`deploy.${hook} 应为字符串数组(命令列表)`, `deploy.${hook}`);
576
+ }
577
+ }
578
+ const d = raw;
579
+ if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
580
+ return d;
581
+ }
582
+ /** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
583
+ function listProjects(cfg) {
584
+ return cfg.projects.map((project) => {
585
+ try {
586
+ return {
587
+ name: project.name,
588
+ path: project.path,
589
+ config: loadProject(project.path)
590
+ };
591
+ } catch (error) {
592
+ return {
593
+ name: project.name,
594
+ path: project.path,
595
+ config: null,
596
+ error: error instanceof Error ? error.message : String(error)
597
+ };
598
+ }
599
+ });
600
+ }
601
+ /** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig);dir 在核心层 resolve 归一(M2-T2 #9) */
602
+ function addProject(cfg, dir) {
603
+ const normalized = resolve(dir);
604
+ const config = loadProject(normalized);
605
+ const byName = cfg.projects.find((p) => p.name === config.name);
606
+ if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
607
+ const byPath = cfg.projects.find((p) => resolve(p.path) === normalized);
608
+ if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${normalized}`);
609
+ const entry = {
610
+ name: config.name,
611
+ path: normalized,
612
+ deployDir: "deploy"
613
+ };
614
+ return {
615
+ ...cfg,
616
+ projects: [...cfg.projects, entry]
617
+ };
618
+ }
619
+ /** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
620
+ function removeProject(cfg, name) {
621
+ const projects = cfg.projects.filter((p) => p.name !== name);
622
+ if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
623
+ return {
624
+ ...cfg,
625
+ projects
626
+ };
627
+ }
628
+ /** image 型生成的 docker-compose.yml 标记头(护栏 marker):既有同名文件无此头则拒绝覆盖(终审 M1:防绑架项目文件) */
629
+ const COMPOSE_MARKER = "# generated by deploy-cli — do not edit";
630
+ /** marker 判定扫描窗口(A2):不再死盯首行——运维头注释把 marker 挤到前几行仍认;窗口外不认 */
631
+ const MARKER_SCAN_LINES = 10;
632
+ /** 既有文件内容是否带 COMPOSE_MARKER 头(前 10 行内任一行,M2-T2 A2:不再信任首行) */
633
+ function hasComposeMarker(content) {
634
+ return content.split("\n").slice(0, MARKER_SCAN_LINES).some((line) => line.trim() === COMPOSE_MARKER);
635
+ }
636
+ /** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment),首行带 COMPOSE_MARKER 标记头 */
637
+ function generateCompose(d) {
638
+ if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
639
+ if (typeof d.image !== "string" || d.image.trim() === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
640
+ const service = { image: d.image };
641
+ if (d.ports && d.ports.length > 0) service.ports = d.ports;
642
+ if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
643
+ if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
644
+ return `${COMPOSE_MARKER}\n${stringify({ services: { [d.name]: service } })}`;
645
+ }
646
+ //#endregion
647
+ //#region src/core/docker.ts
648
+ /** docker 调用默认超时(F5:docker daemon 挂起不得永久挂死 CLI),与流水线 600s 长步档同口径;--follow 流式豁免 */
649
+ const DOCKER_TIMEOUT_MS = 6e5;
650
+ /** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
651
+ function logsArgs(idOrName, o) {
652
+ const args = ["logs"];
653
+ if (o?.tail !== void 0) args.push("--tail", String(o.tail));
654
+ if (o?.follow) args.push("--follow");
655
+ args.push(idOrName);
656
+ return args;
657
+ }
658
+ /** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 onLine(M2-T2 #3:stream 标签透传,不再丢弃) */
659
+ function adaptOnLine(onLine) {
660
+ return onLine ? (line, stream) => onLine(line, stream) : void 0;
661
+ }
662
+ /** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
663
+ function parseContainerLine(line) {
664
+ let raw;
665
+ try {
666
+ raw = JSON.parse(line);
667
+ } catch (error) {
668
+ const reason = error instanceof Error ? error.message : String(error);
669
+ throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
670
+ }
671
+ return {
672
+ id: String(raw.ID ?? raw.Id ?? ""),
673
+ name: String(raw.Names ?? ""),
674
+ image: String(raw.Image ?? ""),
675
+ state: String(raw.State ?? ""),
676
+ status: String(raw.Status ?? ""),
677
+ ports: String(raw.Ports ?? "")
678
+ };
679
+ }
680
+ /** 以 shell-out 方式实现的 docker 操作集合 */
681
+ function createDocker(runner = run) {
682
+ /** F5 防挂起:docker 调用默认挂 DOCKER_TIMEOUT_MS;调用方显式 timeoutMs 优先 */
683
+ const withTimeout = (cmd, args, o = {}) => runner(cmd, args, {
684
+ ...o,
685
+ timeoutMs: o.timeoutMs ?? 6e5
686
+ });
687
+ return {
688
+ async listContainers(o) {
689
+ const args = ["ps"];
690
+ if (o?.all) args.push("-a");
691
+ if (o?.name) args.push("--filter", `name=${o.name}`);
692
+ args.push("--format", "{{json .}}");
693
+ const result = await withTimeout("docker", args);
694
+ if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
695
+ return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
696
+ },
697
+ async logs(idOrName, o) {
698
+ return await runner("docker", logsArgs(idOrName, o), {
699
+ onLine: adaptOnLine(o?.onLine),
700
+ ...o?.follow ? {} : { timeoutMs: DOCKER_TIMEOUT_MS }
701
+ });
702
+ },
703
+ async composeUp(cwd, composeFile, o) {
704
+ const args = [
705
+ "compose",
706
+ "-f",
707
+ composeFile,
708
+ "up",
709
+ "-d"
710
+ ];
711
+ if (o?.build) args.push("--build");
712
+ return await withTimeout("docker", args, {
713
+ cwd,
714
+ onLine: adaptOnLine(o?.onLine)
715
+ });
716
+ },
717
+ async composeDown(cwd, composeFile, o) {
718
+ return await withTimeout("docker", [
719
+ "compose",
720
+ "-f",
721
+ composeFile,
722
+ "down"
723
+ ], {
724
+ cwd,
725
+ onLine: adaptOnLine(o?.onLine)
726
+ });
727
+ },
728
+ async composeBuild(cwd, composeFile, o) {
729
+ return await withTimeout("docker", [
730
+ "compose",
731
+ "-f",
732
+ composeFile,
733
+ "build"
734
+ ], {
735
+ cwd,
736
+ onLine: adaptOnLine(o?.onLine)
737
+ });
738
+ },
739
+ async restart(idOrName) {
740
+ return await withTimeout("docker", ["restart", idOrName]);
741
+ },
742
+ async stop(idOrName) {
743
+ return await withTimeout("docker", ["stop", idOrName]);
744
+ },
745
+ async remove(idOrName, o) {
746
+ const args = ["rm"];
747
+ if (o?.force) args.push("--force");
748
+ args.push(idOrName);
749
+ return await withTimeout("docker", args);
750
+ }
751
+ };
752
+ }
753
+ //#endregion
597
754
  //#region src/core/health.ts
598
755
  /** 把 fetch 失败原因(含 cause / AggregateError 链)摊平成含关键码的单行摘要 */
599
756
  function describeFetchError(error, timeoutMs) {
@@ -645,27 +802,30 @@ function containerBelongsToProject(containerName, projectName) {
645
802
  for (let i = 0; i + want.length <= segments.length; i++) if (want.every((w, j) => segments[i + j] === w)) return true;
646
803
  return false;
647
804
  }
648
- /** 项目容器集合:docker name 过滤(子串)+ 精确名后过滤,含已停止容器 */
649
- async function findProjectContainers(docker, projectName) {
650
- return (await docker.listContainers({
651
- all: true,
652
- name: projectName
653
- })).filter((c) => containerBelongsToProject(c.name, projectName));
805
+ /**
806
+ * 项目容器集合:docker name 过滤(子串)+ 精确名后过滤。
807
+ * all 语义可选(M2-T2 #14,与 ps --all 口径一致):缺省 true=含已停止容器(status/deploy 现口径不变),
808
+ * false=只查运行中(ps 不带 --all 的口径)。
809
+ */
810
+ async function findProjectContainers(docker, projectName, opts = {}) {
811
+ const listOpts = { name: projectName };
812
+ if (opts.all ?? true) listOpts.all = true;
813
+ return (await docker.listContainers(listOpts)).filter((c) => containerBelongsToProject(c.name, projectName));
654
814
  }
655
815
  /** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
656
- async function probeNginxSite(slug, runner) {
816
+ async function probeNginxSite(slug, api) {
657
817
  try {
658
- return (await createNginx(runner).listSites()).includes(slug);
818
+ return (await api.listSites()).includes(slug);
659
819
  } catch {
660
820
  return;
661
821
  }
662
822
  }
663
- /** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位 */
823
+ /** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位;nginx 判定可注入(M2-T2 #11 测试接缝,缺省 createNginx) */
664
824
  async function checkProjectHealth(project, opts) {
665
825
  const runner = opts.runner ?? run;
666
826
  const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name);
667
827
  const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
668
- const nginxPresent = await probeNginxSite(project.name, runner);
828
+ const nginxPresent = await probeNginxSite(project.name, opts.nginx ?? createNginx(runner));
669
829
  return {
670
830
  name: project.name,
671
831
  containers,
@@ -768,6 +928,11 @@ async function runDeploy(project, opts) {
768
928
  }
769
929
  const composeFile = project.composeFile ?? "docker-compose.yml";
770
930
  const customBuild = project.deploy?.build;
931
+ if (project.type === "static" && customBuild !== void 0) emit({
932
+ step: "build",
933
+ status: "warn",
934
+ line: "static 型项目不执行 build,deploy.build 已忽略;如需构建步骤请改用 deploy.pre 钩子"
935
+ });
771
936
  if (project.type !== "static" && (customBuild !== void 0 || project.type === "compose")) {
772
937
  const stopped = await step("build", customBuild ?? `docker compose -f ${composeFile} build`, async () => {
773
938
  if (customBuild !== void 0) expectOk(await runner("bash", ["-c", customBuild]), "bash", ["-c", customBuild]);
@@ -835,14 +1000,19 @@ const USAGE$6 = `用法: deploy-cli deploy <project> [--yes] [--no-nginx]
835
1000
 
836
1001
  流水线: update(git pull) → pre 钩子 → build → up → nginx → health → post 钩子(失败即停)
837
1002
 
1003
+ 说明:
1004
+ deploy 不支持 --no-ssl(nginx 步按 deploy.yaml 的 nginx.ssl 执行);如需 HTTP-only,请用 deploy-cli nginx apply <project> --no-ssl
1005
+ static 型不执行 build/up(deploy.build 会被忽略并提示);如需构建步骤请用 deploy.pre 钩子
1006
+
838
1007
  示例:
839
1008
  deploy-cli deploy my-app
840
1009
  deploy-cli deploy my-app --yes
841
1010
  deploy-cli deploy my-app --yes --no-nginx`;
842
- /** 流水线事件 → 输出行:start=命令原文/开始、ok=✓、fail=✗+失败信息 */
1011
+ /** 流水线事件 → 输出行:start=命令原文/开始、ok=✓、fail=✗+失败信息、warn=⚠+提示(M2-T2 #12) */
843
1012
  function formatEvent(e) {
844
1013
  if (e.status === "ok") return `[${e.step}] ✓`;
845
1014
  if (e.status === "fail") return `[${e.step}] ✗ ${e.line ?? ""}`;
1015
+ if (e.status === "warn") return `[${e.step}] ⚠ ${e.line ?? ""}`;
846
1016
  return `[${e.step}] ${e.line ?? "开始"}`;
847
1017
  }
848
1018
  /** 部署流水线命令:deploy <project> [--yes] [--no-nginx];返回退出码 */
@@ -914,7 +1084,6 @@ async function deploy(args, options = {}) {
914
1084
  }
915
1085
  //#endregion
916
1086
  //#region src/cli/commands/doctor.ts
917
- const SITES_AVAILABLE = "/etc/nginx/sites-available";
918
1087
  const MIN_NODE_MAJOR = 20;
919
1088
  /** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
920
1089
  const PROBE_TIMEOUT_MS = 1e4;
@@ -967,11 +1136,16 @@ async function doctor(options = {}) {
967
1136
  const nginx = await probe(runner, "nginx", ["-v"]);
968
1137
  if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
969
1138
  else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
970
- if (canWrite(SITES_AVAILABLE)) pass(`${SITES_AVAILABLE} 可写`);
971
- else fail(`${SITES_AVAILABLE} 不可写`);
972
- const acme = await probe(runner, "acme.sh", ["--version"]);
973
- const certbot = await probe(runner, "certbot", ["--version"]);
974
- const certTools = [acme.ok && "acme.sh", certbot.ok && "certbot"].filter(Boolean).join(" / ");
1139
+ const paths = resolveNginxPaths(options.exists ?? existsSync$1);
1140
+ if (canWrite(paths.sitesAvailable)) pass(`${paths.sitesAvailable} 可写`);
1141
+ else fail(`${paths.sitesAvailable} 不可写`);
1142
+ if (paths.sitesEnabled) if (canWrite(paths.sitesEnabled)) pass(`${paths.sitesEnabled} 可写`);
1143
+ else fail(`${paths.sitesEnabled} 不可写(sites-enabled 软链无法创建)`);
1144
+ const acmeCmd = acmeProbeCommand();
1145
+ const certbotCmd = certbotProbeCommand();
1146
+ const acme = await probe(runner, acmeCmd.cmd, acmeCmd.args);
1147
+ const certbot = await probe(runner, certbotCmd.cmd, certbotCmd.args);
1148
+ const certTools = [acme.ok && `acme.sh(${ACME_BIN})`, certbot.ok && "certbot"].filter(Boolean).join(" / ");
975
1149
  if (certTools) pass(`证书工具可用(${certTools})`);
976
1150
  else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
977
1151
  return failed ? 1 : 0;
@@ -1036,7 +1210,7 @@ async function logs(args, options = {}) {
1036
1210
  try {
1037
1211
  const result = await docker.logs(name, {
1038
1212
  ...logOpts,
1039
- onLine: (line) => log(line)
1213
+ onLine: (line, stream) => stream === "stderr" ? error(line) : log(line)
1040
1214
  });
1041
1215
  if (result.code !== 0) {
1042
1216
  error(execFailureMessage("docker", logsArgs(name, logOpts), result));
@@ -1078,6 +1252,10 @@ async function nginx(args, options = {}) {
1078
1252
  error(USAGE$4);
1079
1253
  return 1;
1080
1254
  }
1255
+ if (rest.includes("-h") || rest.includes("--help")) {
1256
+ log(USAGE$4);
1257
+ return 0;
1258
+ }
1081
1259
  try {
1082
1260
  switch (sub) {
1083
1261
  case "apply": {
@@ -1110,6 +1288,12 @@ async function nginx(args, options = {}) {
1110
1288
  return 0;
1111
1289
  }
1112
1290
  case "remove": {
1291
+ const dash = rest.filter((a) => a.startsWith("-"));
1292
+ if (dash.length > 0) {
1293
+ error(`未知参数: ${dash.join(" ")}`);
1294
+ error(USAGE$4);
1295
+ return 1;
1296
+ }
1113
1297
  const name = rest[0];
1114
1298
  if (name === void 0 || rest.length > 1) {
1115
1299
  error("remove 需要且仅需要一个 <project> 参数");
@@ -1170,6 +1354,10 @@ async function project(args, options = {}) {
1170
1354
  error(USAGE$3);
1171
1355
  return 1;
1172
1356
  }
1357
+ if (rest.includes("-h") || rest.includes("--help")) {
1358
+ log(USAGE$3);
1359
+ return 0;
1360
+ }
1173
1361
  try {
1174
1362
  switch (sub) {
1175
1363
  case "list": {
@@ -1180,7 +1368,10 @@ async function project(args, options = {}) {
1180
1368
  }
1181
1369
  const rows = listProjects(load());
1182
1370
  log("NAME PATH TYPE ERROR");
1183
- for (const row of rows) log(`${row.name}\t${row.path}\t${row.config?.type ?? "-"}\t${row.error ?? ""}`);
1371
+ for (const row of rows) {
1372
+ const errorText = (row.error ?? "").replace(/\s+/g, " ").trim();
1373
+ log(`${row.name}\t${row.path}\t${row.config?.type ?? "-"}\t${errorText}`);
1374
+ }
1184
1375
  return 0;
1185
1376
  }
1186
1377
  case "add": {
@@ -1198,6 +1389,12 @@ async function project(args, options = {}) {
1198
1389
  return 0;
1199
1390
  }
1200
1391
  case "remove": {
1392
+ const dash = rest.filter((a) => a.startsWith("-"));
1393
+ if (dash.length > 0) {
1394
+ error(`未知参数: ${dash.join(" ")}`);
1395
+ error(USAGE$3);
1396
+ return 1;
1397
+ }
1201
1398
  const name = rest[0];
1202
1399
  if (name === void 0 || rest.length > 1) {
1203
1400
  error("remove 需要且仅需要一个 <name> 参数");
@@ -1262,22 +1459,22 @@ async function ps(args, options = {}) {
1262
1459
  }
1263
1460
  const docker = options.docker ?? createDocker();
1264
1461
  try {
1265
- let nameFilter;
1266
1462
  if (projectName !== void 0) {
1267
1463
  const project = (options.projects ?? (() => loadConfig().projects))().find((p) => p.name === projectName);
1268
1464
  if (!project) {
1269
1465
  error(`未找到项目: ${projectName}(请检查 ~/.deploy-cli/config.json 的 projects 注册表)`);
1270
1466
  return 1;
1271
1467
  }
1272
- nameFilter = project.name;
1468
+ const rows = await findProjectContainers(docker, project.name, { all });
1469
+ log("NAME IMAGE STATE PORTS");
1470
+ for (const container of rows) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
1471
+ return 0;
1273
1472
  }
1274
1473
  const listOpts = {};
1275
1474
  if (all) listOpts.all = true;
1276
- if (nameFilter) listOpts.name = nameFilter;
1277
1475
  const containers = await docker.listContainers(listOpts);
1278
- const rows = projectName === void 0 ? containers : containers.filter((c) => containerBelongsToProject(c.name, projectName));
1279
1476
  log("NAME IMAGE STATE PORTS");
1280
- for (const container of rows) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
1477
+ for (const container of containers) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
1281
1478
  return 0;
1282
1479
  } catch (err) {
1283
1480
  error(err instanceof Error ? err.message : String(err));
@@ -1293,6 +1490,10 @@ const USAGE$1 = `用法: deploy-cli status [project]
1293
1490
  HTTP healthUrl 探测结果(2xx=状态码,失败=FAIL,未配置=-)
1294
1491
  NGINX deploy-cli 站点 conf 在位(✓ 在 / ✗ 不在 / - 未知)
1295
1492
 
1493
+ 退出码(契约):
1494
+ 0 命令成功(表格已输出)——退出码不反映健康,健康与否看表内 FAIL/✗ 行
1495
+ 1 命令失败(参数错误 / 项目未注册 / 注册表损坏);行级失败降级展示,不影响退出码
1496
+
1296
1497
  示例:
1297
1498
  deploy-cli status
1298
1499
  deploy-cli status my-app`;
@@ -1346,10 +1547,17 @@ async function status(args, options = {}) {
1346
1547
  log(`${row.name}\t配置不可用\t-\t-`);
1347
1548
  continue;
1348
1549
  }
1349
- log(formatRow(await checkProjectHealth(row.config, {
1350
- docker: options.docker,
1351
- runner: options.runner
1352
- })));
1550
+ try {
1551
+ log(formatRow(await checkProjectHealth(row.config, {
1552
+ docker: options.docker,
1553
+ runner: options.runner,
1554
+ nginx: options.nginx
1555
+ })));
1556
+ } catch (err) {
1557
+ const reason = err instanceof Error ? err.message : String(err);
1558
+ error(`项目健康检查失败: ${row.name}: ${reason}`);
1559
+ log(`${row.name}\t检查失败\t-\t-`);
1560
+ }
1353
1561
  }
1354
1562
  return 0;
1355
1563
  } catch (err) {
@@ -1368,7 +1576,24 @@ const USAGE = `用法:
1368
1576
  deploy-cli project 项目注册表:list / add / remove(--help 看示例)
1369
1577
  deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)
1370
1578
  deploy-cli deploy 执行部署流水线(--help 看示例)
1371
- deploy-cli status 项目健康状态聚合(--help 看示例)`;
1579
+ deploy-cli status 项目健康状态聚合(--help 看示例)
1580
+ deploy-cli --version 输出版本号(-V 同义)`;
1581
+ const PKG_NAME = "@dongnanyang/deploy-cli";
1582
+ /** 读取 package.json version(M2-T2 #13):自当前模块逐级向上找本包 package.json(构建产物 dist/ 与测试 src/ 均成立) */
1583
+ function readVersion() {
1584
+ let dir = dirname$1(fileURLToPath(import.meta.url));
1585
+ for (let i = 0; i < 6; i++) {
1586
+ const file = join$1(dir, "package.json");
1587
+ if (existsSync$1(file)) try {
1588
+ const pkg = JSON.parse(readFileSync$1(file, "utf-8"));
1589
+ if (pkg.name === PKG_NAME && typeof pkg.version === "string") return pkg.version;
1590
+ } catch {}
1591
+ const parent = dirname$1(dir);
1592
+ if (parent === dir) break;
1593
+ dir = parent;
1594
+ }
1595
+ return "unknown";
1596
+ }
1372
1597
  /** CLI 子命令分发,返回退出码 */
1373
1598
  async function main(argv) {
1374
1599
  const [command] = argv;
@@ -1380,6 +1605,10 @@ async function main(argv) {
1380
1605
  case "nginx": return await nginx(argv.slice(1));
1381
1606
  case "deploy": return await deploy(argv.slice(1));
1382
1607
  case "status": return await status(argv.slice(1));
1608
+ case "--version":
1609
+ case "-V":
1610
+ console.log(readVersion());
1611
+ return 0;
1383
1612
  case "help":
1384
1613
  case "--help":
1385
1614
  case "-h":
@@ -9,12 +9,13 @@ const DEFAULT_CONFIG = {
9
9
  tunnels: [],
10
10
  projects: []
11
11
  };
12
- /** 读取配置,不存在则创建默认配置;projects 缺 deployDir 时补默认值 'deploy' */
13
- function loadConfig() {
12
+ /** 读取配置,不存在则创建默认配置;projects 缺 deployDir 时补默认值 'deploy'。
13
+ * 首建提示走可注入 log sink(M2-T2 #4),缺省仍打 console.log。 */
14
+ function loadConfig(log = (line) => console.log(line)) {
14
15
  if (!existsSync(CONFIG_PATH)) {
15
16
  mkdirSync(CONFIG_DIR, { recursive: true });
16
17
  saveConfig(DEFAULT_CONFIG);
17
- console.log(`[config] 已创建默认配置: ${CONFIG_PATH}`);
18
+ log(`[config] 已创建默认配置: ${CONFIG_PATH}`);
18
19
  return {
19
20
  servers: [],
20
21
  tunnels: [],
package/dist/main.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-CVqFEtQB.js";
1
+ import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-DuBKPLi2.js";
2
2
  import { Box, Text, createApp, useApp, useInput } from "@vue-tui/runtime";
3
3
  import { Fragment, createBlock, createCommentVNode, createElementBlock, createTextVNode, createVNode, defineComponent, nextTick, onMounted, onUnmounted, openBlock, ref, renderList, shallowRef, toDisplayString, watch, withCtx } from "vue";
4
4
  import { ScrollBox } from "@vue-tui/components";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dongnanyang/deploy-cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Local CLI TUI for SSH tunnels & deploy scripts",
5
5
  "type": "module",
6
6
  "bin": {