@dongnanyang/deploy-cli 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,127 @@
1
1
  import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-CVqFEtQB.js";
2
2
  import { readFileSync } from "fs";
3
3
  import { resolve } from "path";
4
+ import { parse, stringify } from "yaml";
4
5
  import { accessSync, constants, existsSync as existsSync$1, lstatSync, 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";
5
7
  import { spawn } from "node:child_process";
6
- import { parse } from "yaml";
7
- import { join as join$1 } from "node:path";
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
+ /** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
21
+ var ProjectConfigError = class extends Error {
22
+ field;
23
+ constructor(message, field) {
24
+ super(message);
25
+ this.name = "ProjectConfigError";
26
+ this.field = field;
27
+ }
28
+ };
29
+ /** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
30
+ function loadProject(dir) {
31
+ const yamlPath = resolve(dir, "deploy.yaml");
32
+ let raw;
33
+ try {
34
+ raw = readFileSync(yamlPath, "utf-8");
35
+ } catch (error) {
36
+ const reason = error instanceof Error ? error.message : String(error);
37
+ if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
38
+ throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
39
+ }
40
+ let parsed;
41
+ try {
42
+ parsed = parse(raw);
43
+ } catch (error) {
44
+ throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
45
+ }
46
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
47
+ return validate(parsed);
48
+ }
49
+ /** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 */
50
+ function validate(raw) {
51
+ const name = raw.name;
52
+ if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
53
+ const type = raw.type;
54
+ if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
55
+ if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
56
+ if (type === "image" && (typeof raw.image !== "string" || raw.image === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
57
+ if (type === "static" && (typeof raw.root !== "string" || raw.root === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
58
+ if (raw.nginx !== void 0 && raw.nginx !== null) {
59
+ const nginx = raw.nginx;
60
+ if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
61
+ const n = nginx;
62
+ if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
63
+ if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
64
+ }
65
+ const d = raw;
66
+ if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
67
+ return d;
68
+ }
69
+ /** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
70
+ function listProjects(cfg) {
71
+ return cfg.projects.map((project) => {
72
+ try {
73
+ return {
74
+ name: project.name,
75
+ path: project.path,
76
+ config: loadProject(project.path)
77
+ };
78
+ } catch (error) {
79
+ return {
80
+ name: project.name,
81
+ path: project.path,
82
+ config: null,
83
+ error: error instanceof Error ? error.message : String(error)
84
+ };
85
+ }
86
+ });
87
+ }
88
+ /** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig) */
89
+ function addProject(cfg, dir) {
90
+ const config = loadProject(dir);
91
+ const byName = cfg.projects.find((p) => p.name === config.name);
92
+ if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
93
+ const byPath = cfg.projects.find((p) => p.path === dir);
94
+ if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${dir}`);
95
+ const entry = {
96
+ name: config.name,
97
+ path: dir,
98
+ deployDir: "deploy"
99
+ };
100
+ return {
101
+ ...cfg,
102
+ projects: [...cfg.projects, entry]
103
+ };
104
+ }
105
+ /** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
106
+ function removeProject(cfg, name) {
107
+ const projects = cfg.projects.filter((p) => p.name !== name);
108
+ if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
109
+ return {
110
+ ...cfg,
111
+ projects
112
+ };
113
+ }
114
+ /** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment) */
115
+ function generateCompose(d) {
116
+ if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
117
+ if (typeof d.image !== "string" || d.image === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
118
+ const service = { image: d.image };
119
+ if (d.ports && d.ports.length > 0) service.ports = d.ports;
120
+ if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
121
+ if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
122
+ return stringify({ services: { [d.name]: service } });
123
+ }
124
+ //#endregion
8
125
  //#region src/core/exec.ts
9
126
  /** 仅 spawn 失败(ENOENT)与超时抛出 */
10
127
  var ExecError = class extends Error {
@@ -109,70 +226,6 @@ async function run(cmd, args, opts = {}) {
109
226
  });
110
227
  }
111
228
  //#endregion
112
- //#region src/cli/commands/doctor.ts
113
- const SITES_AVAILABLE = "/etc/nginx/sites-available";
114
- const MIN_NODE_MAJOR = 20;
115
- /** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
116
- const PROBE_TIMEOUT_MS = 1e4;
117
- async function probe(runner, cmd, args) {
118
- try {
119
- const result = await runner(cmd, args, { timeoutMs: PROBE_TIMEOUT_MS });
120
- const detail = (result.code === 0 ? result.stdout || result.stderr : result.stderr || result.stdout).trim().split("\n")[0] ?? "";
121
- return {
122
- ok: result.code === 0,
123
- detail
124
- };
125
- } catch (error) {
126
- return {
127
- ok: false,
128
- detail: error instanceof Error ? error.message : String(error)
129
- };
130
- }
131
- }
132
- function defaultCanWrite(path) {
133
- try {
134
- accessSync(path, constants.W_OK);
135
- return true;
136
- } catch {
137
- return false;
138
- }
139
- }
140
- /** 环境自检:返回退出码(存在失败项 1,否则 0;警告不影响退出码) */
141
- async function doctor(options = {}) {
142
- const runner = options.runner ?? run;
143
- const log = options.log ?? ((line) => console.log(line));
144
- const canWrite = options.canWrite ?? defaultCanWrite;
145
- let failed = false;
146
- const pass = (line) => log(`[✓] ${line}`);
147
- const fail = (line) => {
148
- failed = true;
149
- log(`[✗] ${line}`);
150
- };
151
- const warn = (line) => log(`[警告] ${line}`);
152
- log("deploy-cli doctor 环境自检");
153
- if (Number(process.versions.node.split(".")[0]) >= MIN_NODE_MAJOR) pass(`Node.js v${process.versions.node}`);
154
- else fail(`Node.js v${process.versions.node} 过低,需要 >= ${MIN_NODE_MAJOR}`);
155
- const dockerVersion = await probe(runner, "docker", ["--version"]);
156
- if (!dockerVersion.ok) fail(`docker 不可用(docker --version 失败): ${dockerVersion.detail}`);
157
- else {
158
- pass(`docker 可用(${dockerVersion.detail})`);
159
- const dockerInfo = await probe(runner, "docker", ["info"]);
160
- if (dockerInfo.ok) pass("docker daemon 运行中");
161
- else fail(`docker daemon 未运行(docker info 失败): ${dockerInfo.detail}`);
162
- }
163
- const nginx = await probe(runner, "nginx", ["-v"]);
164
- if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
165
- else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
166
- if (canWrite(SITES_AVAILABLE)) pass(`${SITES_AVAILABLE} 可写`);
167
- else fail(`${SITES_AVAILABLE} 不可写`);
168
- const acme = await probe(runner, "acme.sh", ["--version"]);
169
- const certbot = await probe(runner, "certbot", ["--version"]);
170
- const certTools = [acme.ok && "acme.sh", certbot.ok && "certbot"].filter(Boolean).join(" / ");
171
- if (certTools) pass(`证书工具可用(${certTools})`);
172
- else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
173
- return failed ? 1 : 0;
174
- }
175
- //#endregion
176
229
  //#region src/core/docker.ts
177
230
  /** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
178
231
  function logsArgs(idOrName, o) {
@@ -275,223 +328,44 @@ function createDocker(runner = run) {
275
328
  };
276
329
  }
277
330
  //#endregion
278
- //#region src/cli/commands/logs.ts
279
- const USAGE$4 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
280
-
281
- 选项:
282
- --tail <行数> 只显示最后 N 行(默认全部)
283
- --follow 持续跟随日志输出(Ctrl-C 退出)
284
-
285
- 示例:
286
- deploy-cli logs deploy-cli-test-echo --tail 5
287
- deploy-cli logs my-app --follow`;
288
- /** 查看容器日志,逐行输出到 stdout;返回退出码 */
289
- async function logs(args, options = {}) {
290
- const log = options.log ?? ((line) => console.log(line));
291
- const error = options.error ?? ((line) => console.error(line));
292
- let tail;
293
- let follow = false;
294
- const positionals = [];
295
- for (let i = 0; i < args.length; i++) {
296
- const arg = args[i];
297
- if (arg === "-h" || arg === "--help") {
298
- log(USAGE$4);
299
- return 0;
300
- }
301
- if (arg === "--tail") {
302
- const value = args[++i];
303
- const parsed = Number(value);
304
- if (value === void 0 || value === "" || !Number.isInteger(parsed) || parsed < 0) {
305
- error(`--tail 需要非负整数参数: ${value ?? ""}`);
306
- error(USAGE$4);
307
- return 1;
308
- }
309
- tail = parsed;
310
- continue;
311
- }
312
- if (arg === "--follow") {
313
- follow = true;
314
- continue;
315
- }
316
- if (arg.startsWith("-")) {
317
- error(`未知参数: ${arg}`);
318
- error(USAGE$4);
319
- return 1;
320
- }
321
- positionals.push(arg);
331
+ //#region src/core/nginx.ts
332
+ /** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
333
+ const CONF_PREFIX = "deploy-cli-";
334
+ const CONF_SUFFIX = ".conf";
335
+ const SLUG_RE = /^[a-z0-9-]+$/;
336
+ /** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
337
+ 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])?)*$/;
338
+ const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
339
+ const UPSTREAM_RE = /^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):([0-9]{1,5})$/;
340
+ const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
341
+ const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
342
+ const DEFAULT_CONF_D = "/etc/nginx/conf.d";
343
+ /** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
344
+ const ACME_HOME = "/root/.acme.sh";
345
+ /** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
346
+ const ACME_RENEW_SKIP = 2;
347
+ /** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
348
+ function pathExists(path) {
349
+ try {
350
+ lstatSync(path);
351
+ return true;
352
+ } catch {
353
+ return false;
322
354
  }
323
- if (positionals.length !== 1) {
324
- error(positionals.length === 0 ? "缺少容器名参数" : `只支持一个容器名参数: ${positionals.join(" ")}`);
325
- error(USAGE$4);
326
- return 1;
327
- }
328
- const name = positionals[0];
329
- const docker = options.docker ?? createDocker();
330
- const logOpts = {
331
- tail,
332
- follow
333
- };
334
- try {
335
- const result = await docker.logs(name, {
336
- ...logOpts,
337
- onLine: (line) => log(line)
338
- });
339
- if (result.code !== 0) {
340
- error(execFailureMessage("docker", logsArgs(name, logOpts), result));
341
- return 1;
342
- }
343
- return 0;
344
- } catch (err) {
345
- error(err instanceof Error ? err.message : String(err));
346
- return 1;
347
- }
348
- }
349
- //#endregion
350
- //#region src/core/project.ts
351
- const VALID_TYPES = [
352
- "compose",
353
- "image",
354
- "static"
355
- ];
356
- const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
357
- const VALID_SSL = [
358
- "none",
359
- "acme",
360
- "custom"
361
- ];
362
- /** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
363
- var ProjectConfigError = class extends Error {
364
- field;
365
- constructor(message, field) {
366
- super(message);
367
- this.name = "ProjectConfigError";
368
- this.field = field;
369
- }
370
- };
371
- /** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
372
- function loadProject(dir) {
373
- const yamlPath = resolve(dir, "deploy.yaml");
374
- let raw;
375
- try {
376
- raw = readFileSync(yamlPath, "utf-8");
377
- } catch (error) {
378
- const reason = error instanceof Error ? error.message : String(error);
379
- if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
380
- throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
381
- }
382
- let parsed;
383
- try {
384
- parsed = parse(raw);
385
- } catch (error) {
386
- throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
387
- }
388
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
389
- return validate(parsed);
390
- }
391
- /** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 */
392
- function validate(raw) {
393
- const name = raw.name;
394
- if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
395
- const type = raw.type;
396
- if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
397
- if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
398
- if (type === "image" && (typeof raw.image !== "string" || raw.image === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
399
- if (type === "static" && (typeof raw.root !== "string" || raw.root === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
400
- if (raw.nginx !== void 0 && raw.nginx !== null) {
401
- const nginx = raw.nginx;
402
- if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
403
- const n = nginx;
404
- if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
405
- if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
406
- }
407
- const d = raw;
408
- if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
409
- return d;
410
- }
411
- /** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
412
- function listProjects(cfg) {
413
- return cfg.projects.map((project) => {
414
- try {
415
- return {
416
- name: project.name,
417
- path: project.path,
418
- config: loadProject(project.path)
419
- };
420
- } catch (error) {
421
- return {
422
- name: project.name,
423
- path: project.path,
424
- config: null,
425
- error: error instanceof Error ? error.message : String(error)
426
- };
427
- }
428
- });
429
- }
430
- /** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig) */
431
- function addProject(cfg, dir) {
432
- const config = loadProject(dir);
433
- const byName = cfg.projects.find((p) => p.name === config.name);
434
- if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
435
- const byPath = cfg.projects.find((p) => p.path === dir);
436
- if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${dir}`);
437
- const entry = {
438
- name: config.name,
439
- path: dir,
440
- deployDir: "deploy"
441
- };
442
- return {
443
- ...cfg,
444
- projects: [...cfg.projects, entry]
445
- };
446
- }
447
- /** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
448
- function removeProject(cfg, name) {
449
- const projects = cfg.projects.filter((p) => p.name !== name);
450
- if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
451
- return {
452
- ...cfg,
453
- projects
454
- };
455
- }
456
- //#endregion
457
- //#region src/core/nginx.ts
458
- /** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
459
- const CONF_PREFIX = "deploy-cli-";
460
- const CONF_SUFFIX = ".conf";
461
- const SLUG_RE = /^[a-z0-9-]+$/;
462
- /** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
463
- 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])?)*$/;
464
- const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
465
- const UPSTREAM_RE = /^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):([0-9]{1,5})$/;
466
- const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
467
- const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
468
- const DEFAULT_CONF_D = "/etc/nginx/conf.d";
469
- /** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
470
- const ACME_HOME = "/root/.acme.sh";
471
- /** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
472
- const ACME_RENEW_SKIP = 2;
473
- /** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
474
- function pathExists(path) {
475
- try {
476
- lstatSync(path);
477
- return true;
478
- } catch {
479
- return false;
480
- }
481
- }
482
- /** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
483
- function validateSlug(slug) {
484
- if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符(禁止路径字符与大写)`);
485
- }
486
- function validateSpec(spec) {
487
- validateSlug(spec.slug);
488
- if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
489
- if (!DOMAIN_RE.test(spec.serverName)) throw new Error(`NginxSiteSpec.serverName 非法: ${JSON.stringify(spec.serverName)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止 conf 元字符与空白)`);
490
- if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
491
- if (spec.root !== void 0 && spec.root !== "") validateAbsPath("root", spec.root);
492
- if (spec.upstream !== void 0 && spec.upstream !== "") {
493
- const match = spec.upstream.match(UPSTREAM_RE);
494
- if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) throw new Error(`NginxSiteSpec.upstream 非法: ${JSON.stringify(spec.upstream)},须为 host:port(端口 1-65535;禁止 conf 元字符与空白)`);
355
+ }
356
+ /** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
357
+ function validateSlug(slug) {
358
+ if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符(禁止路径字符与大写)`);
359
+ }
360
+ function validateSpec(spec) {
361
+ validateSlug(spec.slug);
362
+ if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
363
+ if (!DOMAIN_RE.test(spec.serverName)) throw new Error(`NginxSiteSpec.serverName 非法: ${JSON.stringify(spec.serverName)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止 conf 元字符与空白)`);
364
+ if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
365
+ if (spec.root !== void 0 && spec.root !== "") validateAbsPath("root", spec.root);
366
+ if (spec.upstream !== void 0 && spec.upstream !== "") {
367
+ const match = spec.upstream.match(UPSTREAM_RE);
368
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) throw new Error(`NginxSiteSpec.upstream 非法: ${JSON.stringify(spec.upstream)},须为 host:port(端口 1-65535;禁止 conf 元字符与空白)`);
495
369
  }
496
370
  if (spec.ssl === "custom" && (!spec.certPath || !spec.keyPath)) throw new Error("ssl:custom 需要 certPath 与 keyPath");
497
371
  if (spec.certPath) validateAbsPath("certPath", spec.certPath);
@@ -589,108 +463,544 @@ function createNginx(runner = run, paths) {
589
463
  rollback();
590
464
  throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
591
465
  }
592
- let reload;
593
- try {
594
- reload = await runner("nginx", ["-s", "reload"]);
595
- } catch (error) {
596
- throw error;
466
+ let reload;
467
+ try {
468
+ reload = await runner("nginx", ["-s", "reload"]);
469
+ } catch (error) {
470
+ throw error;
471
+ }
472
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
473
+ if (existed) unlinkSync(bak);
474
+ }
475
+ async function requestCert(domain) {
476
+ const acmeBin = `${ACME_HOME}/acme.sh`;
477
+ if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
478
+ const args = [
479
+ "--issue",
480
+ "--nginx",
481
+ "-d",
482
+ domain
483
+ ];
484
+ const result = await runner(acmeBin, args);
485
+ if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
486
+ return {
487
+ tool: "acme.sh",
488
+ certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
489
+ keyPath: `${ACME_HOME}/${domain}/${domain}.key`
490
+ };
491
+ }
492
+ if ((await runner("sh", ["-c", "command -v certbot"])).code === 0) {
493
+ const args = [
494
+ "--nginx",
495
+ "-d",
496
+ domain,
497
+ "--non-interactive",
498
+ "--agree-tos",
499
+ "--register-unsafely-without-email"
500
+ ];
501
+ const result = await runner("certbot", args);
502
+ if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
503
+ return {
504
+ tool: "certbot",
505
+ certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
506
+ keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
507
+ };
508
+ }
509
+ throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
510
+ }
511
+ return {
512
+ async applySite(spec) {
513
+ validateSpec(spec);
514
+ if (spec.ssl === "acme") {
515
+ await writeSite(spec.slug, renderBlock(spec, false));
516
+ const cert = await requestCert(spec.serverName);
517
+ await writeSite(spec.slug, renderBlock({
518
+ ...spec,
519
+ certPath: cert.certPath,
520
+ keyPath: cert.keyPath
521
+ }, true));
522
+ return;
523
+ }
524
+ await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
525
+ },
526
+ async removeSite(slug) {
527
+ validateSlug(slug);
528
+ const conf = join$1(sitesAvailable, confName(slug));
529
+ if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
530
+ const bak = join$1(sitesAvailable, bakName(slug));
531
+ const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
532
+ const hadLink = link ? pathExists(link) : false;
533
+ renameSync(conf, bak);
534
+ if (link && hadLink) unlinkSync(link);
535
+ const rollback = () => {
536
+ renameSync(bak, conf);
537
+ if (link && hadLink) symlinkSync(conf, link);
538
+ };
539
+ let test;
540
+ try {
541
+ test = await runner("nginx", ["-t"]);
542
+ } catch (error) {
543
+ rollback();
544
+ throw error;
545
+ }
546
+ if (test.code !== 0) {
547
+ rollback();
548
+ throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
549
+ }
550
+ let reload;
551
+ try {
552
+ reload = await runner("nginx", ["-s", "reload"]);
553
+ } catch (error) {
554
+ throw error;
555
+ }
556
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
557
+ unlinkSync(bak);
558
+ },
559
+ async listSites() {
560
+ return readdirSync$1(sitesAvailable).filter((name) => name.startsWith(CONF_PREFIX) && name.endsWith(CONF_SUFFIX)).map((name) => name.slice(11, -5)).filter((slug) => SLUG_RE.test(slug)).sort();
561
+ },
562
+ requestCert
563
+ };
564
+ }
565
+ //#endregion
566
+ //#region src/core/health.ts
567
+ /** 把 fetch 失败原因(含 cause / AggregateError 链)摊平成含关键码的单行摘要 */
568
+ function describeFetchError(error, timeoutMs) {
569
+ const name = error?.name;
570
+ if (name === "TimeoutError" || name === "AbortError") return `timeout: 健康探测超时(${timeoutMs}ms)`;
571
+ const parts = [];
572
+ const seen = /* @__PURE__ */ new Set();
573
+ let current = error;
574
+ while (current instanceof Error && !seen.has(current)) {
575
+ seen.add(current);
576
+ const code = current.code;
577
+ parts.push(code !== void 0 ? `${current.message}(${code})` : current.message);
578
+ const aggregate = current;
579
+ current = current.cause ?? (Array.isArray(aggregate.errors) ? aggregate.errors[0] : void 0);
580
+ }
581
+ return parts.join(": ") || String(error);
582
+ }
583
+ /** HTTP 健康探测(global fetch,默认 5s 超时):2xx → ok;非 2xx/连接拒绝/超时 → ok:false 附 status 或 error */
584
+ async function httpProbe(url, timeoutMs = 5e3) {
585
+ try {
586
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
587
+ if (res.ok) return {
588
+ ok: true,
589
+ status: res.status
590
+ };
591
+ return {
592
+ ok: false,
593
+ status: res.status,
594
+ error: `HTTP ${res.status}`
595
+ };
596
+ } catch (error) {
597
+ return {
598
+ ok: false,
599
+ error: describeFetchError(error, timeoutMs)
600
+ };
601
+ }
602
+ }
603
+ /**
604
+ * 容器归属判定(精确名后过滤):docker `--filter name=` 是子串匹配(`app` 会误伤 `myapp`/`application`),
605
+ * 这里要求项目名以完整连字符分段连续出现在容器名中(兼容 compose 的 `<前缀>-<服务名>-<序号>` 命名)。
606
+ * 末段 `-<数字>` 是 compose 副本号而非名字成分,先剥掉再匹配——否则 `...-test-2`(test 的 2 号副本)
607
+ * 会误配名为 `test-2` 的项目;恰以项目名命名的容器(container_name)走全等判定不受剥离影响。
608
+ */
609
+ function containerBelongsToProject(containerName, projectName) {
610
+ if (projectName === "") return false;
611
+ if (containerName === projectName) return true;
612
+ const segments = containerName.replace(/-\d+$/, "").split("-");
613
+ const want = projectName.split("-");
614
+ for (let i = 0; i + want.length <= segments.length; i++) if (want.every((w, j) => segments[i + j] === w)) return true;
615
+ return false;
616
+ }
617
+ /** 项目容器集合:docker name 过滤(子串)+ 精确名后过滤,含已停止容器 */
618
+ async function findProjectContainers(docker, projectName) {
619
+ return (await docker.listContainers({
620
+ all: true,
621
+ name: projectName
622
+ })).filter((c) => containerBelongsToProject(c.name, projectName));
623
+ }
624
+ /** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
625
+ async function probeNginxSite(slug, runner) {
626
+ try {
627
+ return (await createNginx(runner).listSites()).includes(slug);
628
+ } catch {
629
+ return;
630
+ }
631
+ }
632
+ /** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位 */
633
+ async function checkProjectHealth(project, opts) {
634
+ const runner = opts.runner ?? run;
635
+ const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name);
636
+ const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
637
+ const nginxPresent = await probeNginxSite(project.name, runner);
638
+ return {
639
+ name: project.name,
640
+ containers,
641
+ http,
642
+ nginxPresent
643
+ };
644
+ }
645
+ //#endregion
646
+ //#region src/core/deploy.ts
647
+ /** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
648
+ function buildSpec(d, noSsl) {
649
+ if (!d.nginx) throw new Error(`项目 ${d.name} 未配置 nginx(deploy.yaml 缺 nginx 段)`);
650
+ const ssl = noSsl ? "none" : d.nginx.ssl;
651
+ if (ssl === "custom") throw new Error("ssl:custom 需要 certPath/keyPath,deploy.yaml 暂不支持;请改用 ssl:acme 或 ssl:none");
652
+ const spec = {
653
+ slug: d.name,
654
+ serverName: d.nginx.domain,
655
+ ssl
656
+ };
657
+ if (d.type === "static") spec.root = d.root;
658
+ else {
659
+ if (!d.nginx.upstream) throw new Error(`项目 ${d.name} 为 ${d.type} 型,缺少 nginx.upstream(代理目标,如 127.0.0.1:3000)`);
660
+ spec.upstream = d.nginx.upstream;
661
+ }
662
+ return spec;
663
+ }
664
+ /** 非零退出码 → 抛失败信息(命令原文 + stderr 摘要,可附提示) */
665
+ function expectOk(result, cmd, args, hint) {
666
+ if (result.code !== 0) throw new Error(`${execFailureMessage(cmd, args, result)}${hint ? `;${hint}` : ""}`);
667
+ }
668
+ /**
669
+ * 部署流水线(失败即停):update(git pull) → pre → build → up → nginx → health → post(R10 上线后钩子)。
670
+ * 步骤跳过口径:update 仅 deploy.update==='git-pull' 时执行(缺省/none 跳过);pre/post 无钩子跳过;
671
+ * static 型跳过 build/up(自定义 build 也不跑);image 型无自定义 build 跳过 build(compose 文件在 up 步才生成);
672
+ * nginx 在 applyNginx!==false 且有 nginx 配置时执行;health 在有 healthUrl 或非 static 型时执行。
673
+ * 某步失败(含 Runner reject:spawn 失败/超时)→ 该步 fail 事件 + 后续步骤绝不执行。
674
+ */
675
+ async function runDeploy(project, opts) {
676
+ const runner = opts.runner ?? run;
677
+ const docker = opts.docker ?? createDocker(runner);
678
+ const emit = opts.onEvent;
679
+ /** 包裹单步:start → fn → ok;fn 抛错 → fail 事件 + 停(返回结果由调用方 return) */
680
+ async function step(name, startLine, fn) {
681
+ emit({
682
+ step: name,
683
+ status: "start",
684
+ line: startLine
685
+ });
686
+ try {
687
+ await fn();
688
+ } catch (error) {
689
+ const line = error instanceof Error ? error.message : String(error);
690
+ emit({
691
+ step: name,
692
+ status: "fail",
693
+ line
694
+ });
695
+ return {
696
+ ok: false,
697
+ failedStep: name
698
+ };
699
+ }
700
+ emit({
701
+ step: name,
702
+ status: "ok"
703
+ });
704
+ }
705
+ const gitArgs = [
706
+ "-C",
707
+ opts.cwd,
708
+ "pull"
709
+ ];
710
+ if (project.deploy?.update === "git-pull") {
711
+ const stopped = await step("update", `git ${gitArgs.join(" ")}`, async () => {
712
+ expectOk(await runner("git", gitArgs), "git", gitArgs, "非 git 目录或拉取失败;如无需自动更新请改 deploy.update: none");
713
+ });
714
+ if (stopped) return stopped;
715
+ }
716
+ const pre = project.deploy?.pre ?? [];
717
+ if (pre.length > 0) {
718
+ const stopped = await step("pre", void 0, async () => {
719
+ for (const cmd of pre) expectOk(await runner("bash", ["-c", cmd]), "bash", ["-c", cmd]);
720
+ });
721
+ if (stopped) return stopped;
722
+ }
723
+ const composeFile = project.composeFile ?? "docker-compose.yml";
724
+ const customBuild = project.deploy?.build;
725
+ if (project.type !== "static" && (customBuild !== void 0 || project.type === "compose")) {
726
+ const stopped = await step("build", customBuild ?? `docker compose -f ${composeFile} build`, async () => {
727
+ if (customBuild !== void 0) expectOk(await runner("bash", ["-c", customBuild]), "bash", ["-c", customBuild]);
728
+ else expectOk(await docker.composeBuild(opts.cwd, composeFile), "docker", [
729
+ "compose",
730
+ "-f",
731
+ composeFile,
732
+ "build"
733
+ ]);
734
+ });
735
+ if (stopped) return stopped;
736
+ }
737
+ if (project.type !== "static") {
738
+ const upFile = project.type === "image" ? "docker-compose.yml" : composeFile;
739
+ const stopped = await step("up", `docker compose -f ${upFile} up -d`, async () => {
740
+ if (project.type === "image") writeFileSync$1(resolve$1(opts.cwd, upFile), generateCompose(project), "utf-8");
741
+ expectOk(await docker.composeUp(opts.cwd, upFile), "docker", [
742
+ "compose",
743
+ "-f",
744
+ upFile,
745
+ "up",
746
+ "-d"
747
+ ]);
748
+ });
749
+ if (stopped) return stopped;
750
+ }
751
+ if ((opts.applyNginx ?? true) && project.nginx) {
752
+ const stopped = await step("nginx", void 0, async () => {
753
+ await (opts.nginx ?? createNginx(runner)).applySite(buildSpec(project, false));
754
+ });
755
+ if (stopped) return stopped;
756
+ }
757
+ if (project.healthUrl !== void 0 || project.type !== "static") {
758
+ const stopped = await step("health", project.healthUrl, async () => {
759
+ if (project.healthUrl) {
760
+ const probe = await httpProbe(project.healthUrl);
761
+ if (!probe.ok) throw new Error(`健康探测失败: ${project.healthUrl}: ${probe.error ?? `HTTP ${probe.status}`}`);
762
+ }
763
+ if (project.type !== "static") {
764
+ if (!(await findProjectContainers(docker, project.name)).some((c) => c.state === "running")) throw new Error(`无运行中容器: ${project.name}(docker ps 未见 running 状态容器)`);
765
+ }
766
+ });
767
+ if (stopped) return stopped;
768
+ }
769
+ const post = project.deploy?.post ?? [];
770
+ if (post.length > 0) {
771
+ const stopped = await step("post", void 0, async () => {
772
+ for (const cmd of post) expectOk(await runner("bash", ["-c", cmd]), "bash", ["-c", cmd]);
773
+ });
774
+ if (stopped) return stopped;
775
+ }
776
+ return { ok: true };
777
+ }
778
+ //#endregion
779
+ //#region src/cli/commands/deploy.ts
780
+ const USAGE$6 = `用法: deploy-cli deploy <project> [--yes] [--no-nginx]
781
+
782
+ 选项:
783
+ --yes 非交互环境(无 TTY)下确认执行部署
784
+ --no-nginx 跳过 nginx 站点配置步骤
785
+
786
+ 流水线: update(git pull) → pre 钩子 → build → up → nginx → health → post 钩子(失败即停)
787
+
788
+ 示例:
789
+ deploy-cli deploy my-app
790
+ deploy-cli deploy my-app --yes
791
+ deploy-cli deploy my-app --yes --no-nginx`;
792
+ /** 流水线事件 → 输出行:start=命令原文/开始、ok=✓、fail=✗+失败信息 */
793
+ function formatEvent(e) {
794
+ if (e.status === "ok") return `[${e.step}] ✓`;
795
+ if (e.status === "fail") return `[${e.step}] ✗ ${e.line ?? ""}`;
796
+ return `[${e.step}] ${e.line ?? "开始"}`;
797
+ }
798
+ /** 部署流水线命令:deploy <project> [--yes] [--no-nginx];返回退出码 */
799
+ async function deploy(args, options = {}) {
800
+ const log = options.log ?? ((line) => console.log(line));
801
+ const error = options.error ?? ((line) => console.error(line));
802
+ const load = options.load ?? loadConfig;
803
+ let yes = false;
804
+ let noNginx = false;
805
+ const positional = [];
806
+ for (const arg of args) {
807
+ if (arg === "-h" || arg === "--help") {
808
+ log(USAGE$6);
809
+ return 0;
810
+ }
811
+ if (arg === "--yes") {
812
+ yes = true;
813
+ continue;
814
+ }
815
+ if (arg === "--no-nginx") {
816
+ noNginx = true;
817
+ continue;
818
+ }
819
+ if (arg.startsWith("-")) {
820
+ error(`未知参数: ${arg}`);
821
+ error(USAGE$6);
822
+ return 1;
823
+ }
824
+ positional.push(arg);
825
+ }
826
+ const name = positional[0];
827
+ if (name === void 0 || positional.length > 1) {
828
+ error("deploy 需要且仅需要一个 <project> 参数");
829
+ error(USAGE$6);
830
+ return 1;
831
+ }
832
+ if (!(options.isTTY ?? Boolean(process.stdin.isTTY)) && !yes) {
833
+ error("非交互环境(无 TTY)下部署必须显式确认:请加 --yes(deploy-cli deploy <project> --yes)");
834
+ return 1;
835
+ }
836
+ try {
837
+ const row = listProjects(load()).find((r) => r.name === name);
838
+ if (!row) {
839
+ error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
840
+ return 1;
841
+ }
842
+ if (!row.config) {
843
+ error(`项目配置不可用: ${name}: ${row.error ?? ""}`);
844
+ return 1;
845
+ }
846
+ const result = await runDeploy(row.config, {
847
+ cwd: expandPath(row.path),
848
+ onEvent: (e) => log(formatEvent(e)),
849
+ applyNginx: !noNginx,
850
+ runner: options.runner,
851
+ docker: options.docker,
852
+ nginx: options.nginx
853
+ });
854
+ if (!result.ok) {
855
+ error(`部署失败: ${name}(步骤: ${result.failedStep})`);
856
+ return 1;
857
+ }
858
+ log(`部署完成: ${name}`);
859
+ return 0;
860
+ } catch (err) {
861
+ error(err instanceof Error ? err.message : String(err));
862
+ return 1;
863
+ }
864
+ }
865
+ //#endregion
866
+ //#region src/cli/commands/doctor.ts
867
+ const SITES_AVAILABLE = "/etc/nginx/sites-available";
868
+ const MIN_NODE_MAJOR = 20;
869
+ /** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
870
+ const PROBE_TIMEOUT_MS = 1e4;
871
+ async function probe(runner, cmd, args) {
872
+ try {
873
+ const result = await runner(cmd, args, { timeoutMs: PROBE_TIMEOUT_MS });
874
+ const detail = (result.code === 0 ? result.stdout || result.stderr : result.stderr || result.stdout).trim().split("\n")[0] ?? "";
875
+ return {
876
+ ok: result.code === 0,
877
+ detail
878
+ };
879
+ } catch (error) {
880
+ return {
881
+ ok: false,
882
+ detail: error instanceof Error ? error.message : String(error)
883
+ };
884
+ }
885
+ }
886
+ function defaultCanWrite(path) {
887
+ try {
888
+ accessSync(path, constants.W_OK);
889
+ return true;
890
+ } catch {
891
+ return false;
892
+ }
893
+ }
894
+ /** 环境自检:返回退出码(存在失败项 1,否则 0;警告不影响退出码) */
895
+ async function doctor(options = {}) {
896
+ const runner = options.runner ?? run;
897
+ const log = options.log ?? ((line) => console.log(line));
898
+ const canWrite = options.canWrite ?? defaultCanWrite;
899
+ let failed = false;
900
+ const pass = (line) => log(`[✓] ${line}`);
901
+ const fail = (line) => {
902
+ failed = true;
903
+ log(`[✗] ${line}`);
904
+ };
905
+ const warn = (line) => log(`[警告] ${line}`);
906
+ log("deploy-cli doctor 环境自检");
907
+ if (Number(process.versions.node.split(".")[0]) >= MIN_NODE_MAJOR) pass(`Node.js v${process.versions.node}`);
908
+ else fail(`Node.js v${process.versions.node} 过低,需要 >= ${MIN_NODE_MAJOR}`);
909
+ const dockerVersion = await probe(runner, "docker", ["--version"]);
910
+ if (!dockerVersion.ok) fail(`docker 不可用(docker --version 失败): ${dockerVersion.detail}`);
911
+ else {
912
+ pass(`docker 可用(${dockerVersion.detail})`);
913
+ const dockerInfo = await probe(runner, "docker", ["info"]);
914
+ if (dockerInfo.ok) pass("docker daemon 运行中");
915
+ else fail(`docker daemon 未运行(docker info 失败): ${dockerInfo.detail}`);
916
+ }
917
+ const nginx = await probe(runner, "nginx", ["-v"]);
918
+ if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
919
+ else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
920
+ if (canWrite(SITES_AVAILABLE)) pass(`${SITES_AVAILABLE} 可写`);
921
+ else fail(`${SITES_AVAILABLE} 不可写`);
922
+ const acme = await probe(runner, "acme.sh", ["--version"]);
923
+ const certbot = await probe(runner, "certbot", ["--version"]);
924
+ const certTools = [acme.ok && "acme.sh", certbot.ok && "certbot"].filter(Boolean).join(" / ");
925
+ if (certTools) pass(`证书工具可用(${certTools})`);
926
+ else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
927
+ return failed ? 1 : 0;
928
+ }
929
+ //#endregion
930
+ //#region src/cli/commands/logs.ts
931
+ const USAGE$5 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
932
+
933
+ 选项:
934
+ --tail <行数> 只显示最后 N 行(默认全部)
935
+ --follow 持续跟随日志输出(Ctrl-C 退出)
936
+
937
+ 示例:
938
+ deploy-cli logs deploy-cli-test-echo --tail 5
939
+ deploy-cli logs my-app --follow`;
940
+ /** 查看容器日志,逐行输出到 stdout;返回退出码 */
941
+ async function logs(args, options = {}) {
942
+ const log = options.log ?? ((line) => console.log(line));
943
+ const error = options.error ?? ((line) => console.error(line));
944
+ let tail;
945
+ let follow = false;
946
+ const positionals = [];
947
+ for (let i = 0; i < args.length; i++) {
948
+ const arg = args[i];
949
+ if (arg === "-h" || arg === "--help") {
950
+ log(USAGE$5);
951
+ return 0;
952
+ }
953
+ if (arg === "--tail") {
954
+ const value = args[++i];
955
+ const parsed = Number(value);
956
+ if (value === void 0 || value === "" || !Number.isInteger(parsed) || parsed < 0) {
957
+ error(`--tail 需要非负整数参数: ${value ?? ""}`);
958
+ error(USAGE$5);
959
+ return 1;
960
+ }
961
+ tail = parsed;
962
+ continue;
597
963
  }
598
- if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
599
- if (existed) unlinkSync(bak);
600
- }
601
- async function requestCert(domain) {
602
- const acmeBin = `${ACME_HOME}/acme.sh`;
603
- if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
604
- const args = [
605
- "--issue",
606
- "--nginx",
607
- "-d",
608
- domain
609
- ];
610
- const result = await runner(acmeBin, args);
611
- if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
612
- return {
613
- tool: "acme.sh",
614
- certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
615
- keyPath: `${ACME_HOME}/${domain}/${domain}.key`
616
- };
964
+ if (arg === "--follow") {
965
+ follow = true;
966
+ continue;
617
967
  }
618
- if ((await runner("sh", ["-c", "command -v certbot"])).code === 0) {
619
- const args = [
620
- "--nginx",
621
- "-d",
622
- domain,
623
- "--non-interactive",
624
- "--agree-tos",
625
- "--register-unsafely-without-email"
626
- ];
627
- const result = await runner("certbot", args);
628
- if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
629
- return {
630
- tool: "certbot",
631
- certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
632
- keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
633
- };
968
+ if (arg.startsWith("-")) {
969
+ error(`未知参数: ${arg}`);
970
+ error(USAGE$5);
971
+ return 1;
634
972
  }
635
- throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
973
+ positionals.push(arg);
636
974
  }
637
- return {
638
- async applySite(spec) {
639
- validateSpec(spec);
640
- if (spec.ssl === "acme") {
641
- await writeSite(spec.slug, renderBlock(spec, false));
642
- const cert = await requestCert(spec.serverName);
643
- await writeSite(spec.slug, renderBlock({
644
- ...spec,
645
- certPath: cert.certPath,
646
- keyPath: cert.keyPath
647
- }, true));
648
- return;
649
- }
650
- await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
651
- },
652
- async removeSite(slug) {
653
- validateSlug(slug);
654
- const conf = join$1(sitesAvailable, confName(slug));
655
- if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
656
- const bak = join$1(sitesAvailable, bakName(slug));
657
- const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
658
- const hadLink = link ? pathExists(link) : false;
659
- renameSync(conf, bak);
660
- if (link && hadLink) unlinkSync(link);
661
- const rollback = () => {
662
- renameSync(bak, conf);
663
- if (link && hadLink) symlinkSync(conf, link);
664
- };
665
- let test;
666
- try {
667
- test = await runner("nginx", ["-t"]);
668
- } catch (error) {
669
- rollback();
670
- throw error;
671
- }
672
- if (test.code !== 0) {
673
- rollback();
674
- throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
675
- }
676
- let reload;
677
- try {
678
- reload = await runner("nginx", ["-s", "reload"]);
679
- } catch (error) {
680
- throw error;
681
- }
682
- if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
683
- unlinkSync(bak);
684
- },
685
- async listSites() {
686
- return readdirSync$1(sitesAvailable).filter((name) => name.startsWith(CONF_PREFIX) && name.endsWith(CONF_SUFFIX)).map((name) => name.slice(11, -5)).filter((slug) => SLUG_RE.test(slug)).sort();
687
- },
688
- requestCert
975
+ if (positionals.length !== 1) {
976
+ error(positionals.length === 0 ? "缺少容器名参数" : `只支持一个容器名参数: ${positionals.join(" ")}`);
977
+ error(USAGE$5);
978
+ return 1;
979
+ }
980
+ const name = positionals[0];
981
+ const docker = options.docker ?? createDocker();
982
+ const logOpts = {
983
+ tail,
984
+ follow
689
985
  };
986
+ try {
987
+ const result = await docker.logs(name, {
988
+ ...logOpts,
989
+ onLine: (line) => log(line)
990
+ });
991
+ if (result.code !== 0) {
992
+ error(execFailureMessage("docker", logsArgs(name, logOpts), result));
993
+ return 1;
994
+ }
995
+ return 0;
996
+ } catch (err) {
997
+ error(err instanceof Error ? err.message : String(err));
998
+ return 1;
999
+ }
690
1000
  }
691
1001
  //#endregion
692
1002
  //#region src/cli/commands/nginx.ts
693
- const USAGE$3 = `用法: deploy-cli nginx <apply|remove|list> [参数]
1003
+ const USAGE$4 = `用法: deploy-cli nginx <apply|remove|list> [参数]
694
1004
 
695
1005
  子命令:
696
1006
  apply <project> [--no-ssl] 按 deploy.yaml 的 nginx 配置写入站点 conf 并启用
@@ -702,23 +1012,6 @@ const USAGE$3 = `用法: deploy-cli nginx <apply|remove|list> [参数]
702
1012
  deploy-cli nginx apply my-app --no-ssl
703
1013
  deploy-cli nginx remove my-app
704
1014
  deploy-cli nginx list`;
705
- /** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
706
- function buildSpec(d, noSsl) {
707
- if (!d.nginx) throw new Error(`项目 ${d.name} 未配置 nginx(deploy.yaml 缺 nginx 段)`);
708
- const ssl = noSsl ? "none" : d.nginx.ssl;
709
- if (ssl === "custom") throw new Error("ssl:custom 需要 certPath/keyPath,deploy.yaml 暂不支持;请改用 ssl:acme 或 ssl:none");
710
- const spec = {
711
- slug: d.name,
712
- serverName: d.nginx.domain,
713
- ssl
714
- };
715
- if (d.type === "static") spec.root = d.root;
716
- else {
717
- if (!d.nginx.upstream) throw new Error(`项目 ${d.name} 为 ${d.type} 型,缺少 nginx.upstream(代理目标,如 127.0.0.1:3000)`);
718
- spec.upstream = d.nginx.upstream;
719
- }
720
- return spec;
721
- }
722
1015
  /** nginx 站点管理:apply / remove / list;返回退出码 */
723
1016
  async function nginx(args, options = {}) {
724
1017
  const log = options.log ?? ((line) => console.log(line));
@@ -727,12 +1020,12 @@ async function nginx(args, options = {}) {
727
1020
  const api = options.api ?? createNginx();
728
1021
  const [sub, ...rest] = args;
729
1022
  if (sub === "-h" || sub === "--help") {
730
- log(USAGE$3);
1023
+ log(USAGE$4);
731
1024
  return 0;
732
1025
  }
733
1026
  if (sub === void 0) {
734
1027
  error("缺少子命令");
735
- error(USAGE$3);
1028
+ error(USAGE$4);
736
1029
  return 1;
737
1030
  }
738
1031
  try {
@@ -741,14 +1034,14 @@ async function nginx(args, options = {}) {
741
1034
  const unknown = rest.filter((a) => a.startsWith("-") && a !== "--no-ssl");
742
1035
  if (unknown.length > 0) {
743
1036
  error(`未知参数: ${unknown.join(" ")}`);
744
- error(USAGE$3);
1037
+ error(USAGE$4);
745
1038
  return 1;
746
1039
  }
747
1040
  const positional = rest.filter((a) => !a.startsWith("-"));
748
1041
  const name = positional[0];
749
1042
  if (name === void 0 || positional.length > 1) {
750
1043
  error("apply 需要且仅需要一个 <project> 参数");
751
- error(USAGE$3);
1044
+ error(USAGE$4);
752
1045
  return 1;
753
1046
  }
754
1047
  const noSsl = rest.includes("--no-ssl");
@@ -770,7 +1063,7 @@ async function nginx(args, options = {}) {
770
1063
  const name = rest[0];
771
1064
  if (name === void 0 || rest.length > 1) {
772
1065
  error("remove 需要且仅需要一个 <project> 参数");
773
- error(USAGE$3);
1066
+ error(USAGE$4);
774
1067
  return 1;
775
1068
  }
776
1069
  await api.removeSite(name);
@@ -780,7 +1073,7 @@ async function nginx(args, options = {}) {
780
1073
  case "list": {
781
1074
  if (rest.length > 0) {
782
1075
  error(`未知参数: ${rest.join(" ")}`);
783
- error(USAGE$3);
1076
+ error(USAGE$4);
784
1077
  return 1;
785
1078
  }
786
1079
  const sites = await api.listSites();
@@ -790,7 +1083,7 @@ async function nginx(args, options = {}) {
790
1083
  }
791
1084
  default:
792
1085
  error(`未知子命令: ${sub}`);
793
- error(USAGE$3);
1086
+ error(USAGE$4);
794
1087
  return 1;
795
1088
  }
796
1089
  } catch (err) {
@@ -800,7 +1093,7 @@ async function nginx(args, options = {}) {
800
1093
  }
801
1094
  //#endregion
802
1095
  //#region src/cli/commands/project.ts
803
- const USAGE$2 = `用法: deploy-cli project <list|add|remove> [参数]
1096
+ const USAGE$3 = `用法: deploy-cli project <list|add|remove> [参数]
804
1097
 
805
1098
  子命令:
806
1099
  list 列出已注册项目(NAME/PATH/TYPE/ERROR)
@@ -819,12 +1112,12 @@ async function project(args, options = {}) {
819
1112
  const save = options.save ?? saveConfig;
820
1113
  const [sub, ...rest] = args;
821
1114
  if (sub === "-h" || sub === "--help") {
822
- log(USAGE$2);
1115
+ log(USAGE$3);
823
1116
  return 0;
824
1117
  }
825
1118
  if (sub === void 0) {
826
1119
  error("缺少子命令");
827
- error(USAGE$2);
1120
+ error(USAGE$3);
828
1121
  return 1;
829
1122
  }
830
1123
  try {
@@ -832,7 +1125,7 @@ async function project(args, options = {}) {
832
1125
  case "list": {
833
1126
  if (rest.length > 0) {
834
1127
  error(`未知参数: ${rest.join(" ")}`);
835
- error(USAGE$2);
1128
+ error(USAGE$3);
836
1129
  return 1;
837
1130
  }
838
1131
  const rows = listProjects(load());
@@ -844,7 +1137,7 @@ async function project(args, options = {}) {
844
1137
  const raw = rest[0];
845
1138
  if (raw === void 0 || rest.length > 1) {
846
1139
  error("add 需要且仅需要一个 <path> 参数");
847
- error(USAGE$2);
1140
+ error(USAGE$3);
848
1141
  return 1;
849
1142
  }
850
1143
  const dir = expandPath(raw);
@@ -858,7 +1151,7 @@ async function project(args, options = {}) {
858
1151
  const name = rest[0];
859
1152
  if (name === void 0 || rest.length > 1) {
860
1153
  error("remove 需要且仅需要一个 <name> 参数");
861
- error(USAGE$2);
1154
+ error(USAGE$3);
862
1155
  return 1;
863
1156
  }
864
1157
  save(removeProject(load(), name));
@@ -867,7 +1160,7 @@ async function project(args, options = {}) {
867
1160
  }
868
1161
  default:
869
1162
  error(`未知子命令: ${sub}`);
870
- error(USAGE$2);
1163
+ error(USAGE$3);
871
1164
  return 1;
872
1165
  }
873
1166
  } catch (err) {
@@ -877,7 +1170,7 @@ async function project(args, options = {}) {
877
1170
  }
878
1171
  //#endregion
879
1172
  //#region src/cli/commands/ps.ts
880
- const USAGE$1 = `用法: deploy-cli ps [--all] [--project <项目名>]
1173
+ const USAGE$2 = `用法: deploy-cli ps [--all] [--project <项目名>]
881
1174
 
882
1175
  选项:
883
1176
  --all 含已停止的容器
@@ -896,7 +1189,7 @@ async function ps(args, options = {}) {
896
1189
  for (let i = 0; i < args.length; i++) {
897
1190
  const arg = args[i];
898
1191
  if (arg === "-h" || arg === "--help") {
899
- log(USAGE$1);
1192
+ log(USAGE$2);
900
1193
  return 0;
901
1194
  }
902
1195
  if (arg === "--all") {
@@ -907,14 +1200,14 @@ async function ps(args, options = {}) {
907
1200
  const value = args[++i];
908
1201
  if (value === void 0 || value === "") {
909
1202
  error("缺少 --project 的项目名参数");
910
- error(USAGE$1);
1203
+ error(USAGE$2);
911
1204
  return 1;
912
1205
  }
913
1206
  projectName = value;
914
1207
  continue;
915
1208
  }
916
1209
  error(`未知参数: ${arg}`);
917
- error(USAGE$1);
1210
+ error(USAGE$2);
918
1211
  return 1;
919
1212
  }
920
1213
  const docker = options.docker ?? createDocker();
@@ -941,6 +1234,79 @@ async function ps(args, options = {}) {
941
1234
  }
942
1235
  }
943
1236
  //#endregion
1237
+ //#region src/cli/commands/status.ts
1238
+ const USAGE$1 = `用法: deploy-cli status [project]
1239
+
1240
+ 聚合项目健康状态(容器 / HTTP 探测 / nginx conf):
1241
+ CONTAINERS 运行中/总数 容器(含已停止)
1242
+ HTTP healthUrl 探测结果(2xx=状态码,失败=FAIL,未配置=-)
1243
+ NGINX deploy-cli 站点 conf 在位(✓ 在 / ✗ 不在 / - 未知)
1244
+
1245
+ 示例:
1246
+ deploy-cli status
1247
+ deploy-cli status my-app`;
1248
+ /** ProjectHealth → 表格行(CONTAINERS/HTTP/NGINX 三列) */
1249
+ function formatRow(health) {
1250
+ const total = health.containers.length;
1251
+ const running = health.containers.filter((c) => c.state === "running").length;
1252
+ const containers = total === 0 ? "无容器" : `${running}/${total} running`;
1253
+ const http = health.http === void 0 ? "-" : health.http.ok ? String(health.http.status) : "FAIL";
1254
+ const nginx = health.nginxPresent === void 0 ? "-" : health.nginxPresent ? "✓" : "✗";
1255
+ return `${health.name}\t${containers}\t${http}\t${nginx}`;
1256
+ }
1257
+ /** 状态聚合命令:status [project];返回退出码 */
1258
+ async function status(args, options = {}) {
1259
+ const log = options.log ?? ((line) => console.log(line));
1260
+ const error = options.error ?? ((line) => console.error(line));
1261
+ const load = options.load ?? loadConfig;
1262
+ const positional = [];
1263
+ for (const arg of args) {
1264
+ if (arg === "-h" || arg === "--help") {
1265
+ log(USAGE$1);
1266
+ return 0;
1267
+ }
1268
+ if (arg.startsWith("-")) {
1269
+ error(`未知参数: ${arg}`);
1270
+ error(USAGE$1);
1271
+ return 1;
1272
+ }
1273
+ positional.push(arg);
1274
+ }
1275
+ if (positional.length > 1) {
1276
+ error("status 至多接受一个 [project] 参数");
1277
+ error(USAGE$1);
1278
+ return 1;
1279
+ }
1280
+ try {
1281
+ let rows;
1282
+ if (positional.length === 1) {
1283
+ const name = positional[0];
1284
+ const row = listProjects(load()).find((r) => r.name === name);
1285
+ if (!row) {
1286
+ error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
1287
+ return 1;
1288
+ }
1289
+ rows = [row];
1290
+ } else rows = listProjects(load());
1291
+ log("NAME CONTAINERS HTTP NGINX");
1292
+ for (const row of rows) {
1293
+ if (!row.config) {
1294
+ error(`项目配置不可用: ${row.name}: ${row.error ?? ""}`);
1295
+ log(`${row.name}\t配置不可用\t-\t-`);
1296
+ continue;
1297
+ }
1298
+ log(formatRow(await checkProjectHealth(row.config, {
1299
+ docker: options.docker,
1300
+ runner: options.runner
1301
+ })));
1302
+ }
1303
+ return 0;
1304
+ } catch (err) {
1305
+ error(err instanceof Error ? err.message : String(err));
1306
+ return 1;
1307
+ }
1308
+ }
1309
+ //#endregion
944
1310
  //#region src/cli/index.ts
945
1311
  const USAGE = `用法:
946
1312
  deploy-cli 启动交互式 TUI
@@ -949,7 +1315,9 @@ const USAGE = `用法:
949
1315
  deploy-cli ps 列出容器(--help 看示例)
950
1316
  deploy-cli logs 查看容器日志(--help 看示例)
951
1317
  deploy-cli project 项目注册表:list / add / remove(--help 看示例)
952
- deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)`;
1318
+ deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)
1319
+ deploy-cli deploy 执行部署流水线(--help 看示例)
1320
+ deploy-cli status 项目健康状态聚合(--help 看示例)`;
953
1321
  /** CLI 子命令分发,返回退出码 */
954
1322
  async function main(argv) {
955
1323
  const [command] = argv;
@@ -959,6 +1327,8 @@ async function main(argv) {
959
1327
  case "logs": return await logs(argv.slice(1));
960
1328
  case "project": return await project(argv.slice(1));
961
1329
  case "nginx": return await nginx(argv.slice(1));
1330
+ case "deploy": return await deploy(argv.slice(1));
1331
+ case "status": return await status(argv.slice(1));
962
1332
  case "help":
963
1333
  case "--help":
964
1334
  case "-h":