@dongnanyang/deploy-cli 0.10.1 → 0.11.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
@@ -18,7 +18,7 @@ async function runEntry(argv = process.argv.slice(2)) {
18
18
  await import("./tui/main.js");
19
19
  break;
20
20
  case "cli": {
21
- const cli = await import("./cli-CR04-WjM.js");
21
+ const cli = await import("./cli-D0f7LcnK.js");
22
22
  process.exitCode = await cli.main(argv);
23
23
  break;
24
24
  }
@@ -1,223 +1,9 @@
1
- import { _ as certbotProbeCommand, a as generateCompose, b as execFailureMessage, c as loadProject, d as removeProject, g as acmeProbeCommand, h as ACME_BIN, m as PROJECT_LABEL, o as hasComposeMarker, p as COMPOSE_SERVICE_LABEL, r as addProject, s as listProjects, t as COMPOSE_MARKER, v as createNginx, x as run, y as resolveNginxPaths } from "./project-BzJoAv1l.js";
1
+ import { _ as certbotProbeCommand, a as generateCompose, b as execFailureMessage, c as loadProject, d as removeProject, g as acmeProbeCommand, h as ACME_BIN, o as hasComposeMarker, r as addProject, s as listProjects, t as COMPOSE_MARKER, v as createNginx, x as run, y as resolveNginxPaths } from "./project-BzJoAv1l.js";
2
2
  import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-xUl8Oa3T.js";
3
+ import { a as logsArgs, i as createDocker, n as findProjectContainers, r as httpProbe, t as checkProjectHealth } from "./health-CZL7Ghs8.js";
3
4
  import { accessSync, constants, existsSync, readFileSync, writeFileSync } from "node:fs";
4
5
  import { dirname, join, resolve } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
6
- //#region src/core/docker.ts
7
- /** docker 调用默认超时(F5:docker daemon 挂起不得永久挂死 CLI),与流水线 600s 长步档同口径;--follow 流式豁免 */
8
- const DOCKER_TIMEOUT_MS = 6e5;
9
- /** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
10
- function logsArgs(idOrName, o) {
11
- const args = ["logs"];
12
- if (o?.tail !== void 0) args.push("--tail", String(o.tail));
13
- if (o?.follow) args.push("--follow");
14
- args.push(idOrName);
15
- return args;
16
- }
17
- /** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 onLine(M2-T2 #3:stream 标签透传,不再丢弃) */
18
- function adaptOnLine(onLine) {
19
- return onLine ? (line, stream) => onLine(line, stream) : void 0;
20
- }
21
- /** docker ps 的 Labels 字段 → 标签表(M2-T3):模板渲染为逗号分隔 "k=v" 串,个别版本输出对象;空/缺失 → undefined */
22
- function parseLabels(raw) {
23
- const out = {};
24
- if (typeof raw === "string") for (const pair of raw.split(",")) {
25
- const eq = pair.indexOf("=");
26
- if (eq <= 0) continue;
27
- out[pair.slice(0, eq)] = pair.slice(eq + 1);
28
- }
29
- else if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) for (const [key, value] of Object.entries(raw)) out[key] = String(value);
30
- return Object.keys(out).length > 0 ? out : void 0;
31
- }
32
- /** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
33
- function parseContainerLine(line) {
34
- let raw;
35
- try {
36
- raw = JSON.parse(line);
37
- } catch (error) {
38
- const reason = error instanceof Error ? error.message : String(error);
39
- throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
40
- }
41
- return {
42
- id: String(raw.ID ?? raw.Id ?? ""),
43
- name: String(raw.Names ?? ""),
44
- image: String(raw.Image ?? ""),
45
- state: String(raw.State ?? ""),
46
- status: String(raw.Status ?? ""),
47
- ports: String(raw.Ports ?? ""),
48
- labels: parseLabels(raw.Labels)
49
- };
50
- }
51
- /** 以 shell-out 方式实现的 docker 操作集合 */
52
- function createDocker(runner = run) {
53
- /** F5 防挂起:docker 调用默认挂 DOCKER_TIMEOUT_MS;调用方显式 timeoutMs 优先 */
54
- const withTimeout = (cmd, args, o = {}) => runner(cmd, args, {
55
- ...o,
56
- timeoutMs: o.timeoutMs ?? 6e5
57
- });
58
- return {
59
- async listContainers(o) {
60
- const args = ["ps"];
61
- if (o?.all) args.push("-a");
62
- if (o?.name) args.push("--filter", `name=${o.name}`);
63
- args.push("--format", "{{json .}}");
64
- const result = await withTimeout("docker", args);
65
- if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
66
- return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
67
- },
68
- async logs(idOrName, o) {
69
- return await runner("docker", logsArgs(idOrName, o), {
70
- onLine: adaptOnLine(o?.onLine),
71
- ...o?.follow ? {} : { timeoutMs: DOCKER_TIMEOUT_MS }
72
- });
73
- },
74
- async composeUp(cwd, composeFile, o) {
75
- const args = [
76
- "compose",
77
- "-f",
78
- composeFile,
79
- "up",
80
- "-d"
81
- ];
82
- if (o?.build) args.push("--build");
83
- return await withTimeout("docker", args, {
84
- cwd,
85
- onLine: adaptOnLine(o?.onLine)
86
- });
87
- },
88
- async composeDown(cwd, composeFile, o) {
89
- return await withTimeout("docker", [
90
- "compose",
91
- "-f",
92
- composeFile,
93
- "down"
94
- ], {
95
- cwd,
96
- onLine: adaptOnLine(o?.onLine)
97
- });
98
- },
99
- async composeBuild(cwd, composeFile, o) {
100
- return await withTimeout("docker", [
101
- "compose",
102
- "-f",
103
- composeFile,
104
- "build"
105
- ], {
106
- cwd,
107
- onLine: adaptOnLine(o?.onLine)
108
- });
109
- },
110
- async restart(idOrName) {
111
- return await withTimeout("docker", ["restart", idOrName]);
112
- },
113
- async stop(idOrName) {
114
- return await withTimeout("docker", ["stop", idOrName]);
115
- },
116
- async remove(idOrName, o) {
117
- const args = ["rm"];
118
- if (o?.force) args.push("--force");
119
- args.push(idOrName);
120
- return await withTimeout("docker", args);
121
- }
122
- };
123
- }
124
- //#endregion
125
- //#region src/core/health.ts
126
- /** 把 fetch 失败原因(含 cause / AggregateError 链)摊平成含关键码的单行摘要 */
127
- function describeFetchError(error, timeoutMs) {
128
- const name = error?.name;
129
- if (name === "TimeoutError" || name === "AbortError") return `timeout: 健康探测超时(${timeoutMs}ms)`;
130
- const parts = [];
131
- const seen = /* @__PURE__ */ new Set();
132
- let current = error;
133
- while (current instanceof Error && !seen.has(current)) {
134
- seen.add(current);
135
- const code = current.code;
136
- parts.push(code !== void 0 ? `${current.message}(${code})` : current.message);
137
- const aggregate = current;
138
- current = current.cause ?? (Array.isArray(aggregate.errors) ? aggregate.errors[0] : void 0);
139
- }
140
- return parts.join(": ") || String(error);
141
- }
142
- /** HTTP 健康探测(global fetch,默认 5s 超时):2xx → ok;非 2xx/连接拒绝/超时 → ok:false 附 status 或 error */
143
- async function httpProbe(url, timeoutMs = 5e3) {
144
- try {
145
- const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
146
- if (res.ok) return {
147
- ok: true,
148
- status: res.status
149
- };
150
- return {
151
- ok: false,
152
- status: res.status,
153
- error: `HTTP ${res.status}`
154
- };
155
- } catch (error) {
156
- return {
157
- ok: false,
158
- error: describeFetchError(error, timeoutMs)
159
- };
160
- }
161
- }
162
- /**
163
- * 容器归属判定(M2-T3 归属 label 化):
164
- * 1. **label 优先**——容器带 `deploy-cli.project` 归属 label 时只认 label(generateCompose 生成的容器都带),
165
- * 同名段碰撞根治(`happy-app-1` 段匹配会撞上项目 `app`,label 指名 `happy-app` 后不再误配);
166
- * 2. **无 label 回退**精确名后过滤(历史兼容):docker `--filter name=` 是子串匹配(`app` 会误伤 `myapp`/`application`),
167
- * 这里要求项目名以完整连字符分段连续出现在容器名中(兼容 compose 的 `<前缀>-<服务名>-<序号>` 命名)。
168
- * 末段 `-<数字>` 是 compose 副本号而非名字成分,先剥掉再匹配——否则 `...-test-2`(test 的 2 号副本)
169
- * 会误配名为 `test-2` 的项目;恰以项目名命名的容器(container_name)走全等判定不受剥离影响。
170
- */
171
- function containerBelongsToProject(containerName, projectName, labels) {
172
- if (projectName === "") return false;
173
- const owned = labels?.[PROJECT_LABEL];
174
- if (owned) return owned === projectName;
175
- if (containerName === projectName) return true;
176
- const segments = containerName.replace(/-\d+$/, "").split("-");
177
- const want = projectName.split("-");
178
- for (let i = 0; i + want.length <= segments.length; i++) if (want.every((w, j) => segments[i + j] === w)) return true;
179
- return false;
180
- }
181
- /**
182
- * 项目容器集合:docker name 过滤(子串)+ label 优先归属过滤(无 label 回退精确名后过滤)。
183
- * all 语义可选(M2-T2 #14,与 ps --all 口径一致):缺省 true=含已停止容器(status/deploy 现口径不变),
184
- * false=只查运行中(ps 不带 --all 的口径)。
185
- * services 过滤(R14/F10):非空时只留 `com.docker.compose.service` 命中声明服务的容器(缺省/空=全部)。
186
- */
187
- async function findProjectContainers(docker, projectName, opts = {}) {
188
- const listOpts = { name: projectName };
189
- if (opts.all ?? true) listOpts.all = true;
190
- const all = await docker.listContainers(listOpts);
191
- const wanted = opts.services ?? [];
192
- return all.filter((c) => {
193
- if (!containerBelongsToProject(c.name, projectName, c.labels)) return false;
194
- if (wanted.length === 0) return true;
195
- const service = c.labels?.[COMPOSE_SERVICE_LABEL];
196
- return service !== void 0 && wanted.includes(service);
197
- });
198
- }
199
- /** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
200
- async function probeNginxSite(slug, api) {
201
- try {
202
- return (await api.listSites()).includes(slug);
203
- } catch {
204
- return;
205
- }
206
- }
207
- /** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位;nginx 判定可注入(M2-T2 #11 测试接缝,缺省 createNginx) */
208
- async function checkProjectHealth(project, opts) {
209
- const runner = opts.runner ?? run;
210
- const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name, { services: project.services });
211
- const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
212
- const nginxPresent = await probeNginxSite(project.name, opts.nginx ?? createNginx(runner));
213
- return {
214
- name: project.name,
215
- containers,
216
- http,
217
- nginxPresent
218
- };
219
- }
220
- //#endregion
221
7
  //#region src/core/deploy.ts
222
8
  /** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
223
9
  function buildSpec(d, noSsl) {
@@ -0,0 +1,217 @@
1
+ import { b as execFailureMessage, m as PROJECT_LABEL, p as COMPOSE_SERVICE_LABEL, v as createNginx, x as run } from "./project-BzJoAv1l.js";
2
+ //#region src/core/docker.ts
3
+ /** docker 调用默认超时(F5:docker daemon 挂起不得永久挂死 CLI),与流水线 600s 长步档同口径;--follow 流式豁免 */
4
+ const DOCKER_TIMEOUT_MS = 6e5;
5
+ /** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
6
+ function logsArgs(idOrName, o) {
7
+ const args = ["logs"];
8
+ if (o?.tail !== void 0) args.push("--tail", String(o.tail));
9
+ if (o?.follow) args.push("--follow");
10
+ args.push(idOrName);
11
+ return args;
12
+ }
13
+ /** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 onLine(M2-T2 #3:stream 标签透传,不再丢弃) */
14
+ function adaptOnLine(onLine) {
15
+ return onLine ? (line, stream) => onLine(line, stream) : void 0;
16
+ }
17
+ /** docker ps 的 Labels 字段 → 标签表(M2-T3):模板渲染为逗号分隔 "k=v" 串,个别版本输出对象;空/缺失 → undefined */
18
+ function parseLabels(raw) {
19
+ const out = {};
20
+ if (typeof raw === "string") for (const pair of raw.split(",")) {
21
+ const eq = pair.indexOf("=");
22
+ if (eq <= 0) continue;
23
+ out[pair.slice(0, eq)] = pair.slice(eq + 1);
24
+ }
25
+ else if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) for (const [key, value] of Object.entries(raw)) out[key] = String(value);
26
+ return Object.keys(out).length > 0 ? out : void 0;
27
+ }
28
+ /** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
29
+ function parseContainerLine(line) {
30
+ let raw;
31
+ try {
32
+ raw = JSON.parse(line);
33
+ } catch (error) {
34
+ const reason = error instanceof Error ? error.message : String(error);
35
+ throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
36
+ }
37
+ return {
38
+ id: String(raw.ID ?? raw.Id ?? ""),
39
+ name: String(raw.Names ?? ""),
40
+ image: String(raw.Image ?? ""),
41
+ state: String(raw.State ?? ""),
42
+ status: String(raw.Status ?? ""),
43
+ ports: String(raw.Ports ?? ""),
44
+ labels: parseLabels(raw.Labels)
45
+ };
46
+ }
47
+ /** 以 shell-out 方式实现的 docker 操作集合 */
48
+ function createDocker(runner = run) {
49
+ /** F5 防挂起:docker 调用默认挂 DOCKER_TIMEOUT_MS;调用方显式 timeoutMs 优先 */
50
+ const withTimeout = (cmd, args, o = {}) => runner(cmd, args, {
51
+ ...o,
52
+ timeoutMs: o.timeoutMs ?? 6e5
53
+ });
54
+ return {
55
+ async listContainers(o) {
56
+ const args = ["ps"];
57
+ if (o?.all) args.push("-a");
58
+ if (o?.name) args.push("--filter", `name=${o.name}`);
59
+ args.push("--format", "{{json .}}");
60
+ const result = await withTimeout("docker", args);
61
+ if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
62
+ return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
63
+ },
64
+ async logs(idOrName, o) {
65
+ return await runner("docker", logsArgs(idOrName, o), {
66
+ onLine: adaptOnLine(o?.onLine),
67
+ ...o?.follow ? {} : { timeoutMs: DOCKER_TIMEOUT_MS }
68
+ });
69
+ },
70
+ async composeUp(cwd, composeFile, o) {
71
+ const args = [
72
+ "compose",
73
+ "-f",
74
+ composeFile,
75
+ "up",
76
+ "-d"
77
+ ];
78
+ if (o?.build) args.push("--build");
79
+ return await withTimeout("docker", args, {
80
+ cwd,
81
+ onLine: adaptOnLine(o?.onLine)
82
+ });
83
+ },
84
+ async composeDown(cwd, composeFile, o) {
85
+ return await withTimeout("docker", [
86
+ "compose",
87
+ "-f",
88
+ composeFile,
89
+ "down"
90
+ ], {
91
+ cwd,
92
+ onLine: adaptOnLine(o?.onLine)
93
+ });
94
+ },
95
+ async composeBuild(cwd, composeFile, o) {
96
+ return await withTimeout("docker", [
97
+ "compose",
98
+ "-f",
99
+ composeFile,
100
+ "build"
101
+ ], {
102
+ cwd,
103
+ onLine: adaptOnLine(o?.onLine)
104
+ });
105
+ },
106
+ async restart(idOrName) {
107
+ return await withTimeout("docker", ["restart", idOrName]);
108
+ },
109
+ async stop(idOrName) {
110
+ return await withTimeout("docker", ["stop", idOrName]);
111
+ },
112
+ async remove(idOrName, o) {
113
+ const args = ["rm"];
114
+ if (o?.force) args.push("--force");
115
+ args.push(idOrName);
116
+ return await withTimeout("docker", args);
117
+ }
118
+ };
119
+ }
120
+ //#endregion
121
+ //#region src/core/health.ts
122
+ /** 把 fetch 失败原因(含 cause / AggregateError 链)摊平成含关键码的单行摘要 */
123
+ function describeFetchError(error, timeoutMs) {
124
+ const name = error?.name;
125
+ if (name === "TimeoutError" || name === "AbortError") return `timeout: 健康探测超时(${timeoutMs}ms)`;
126
+ const parts = [];
127
+ const seen = /* @__PURE__ */ new Set();
128
+ let current = error;
129
+ while (current instanceof Error && !seen.has(current)) {
130
+ seen.add(current);
131
+ const code = current.code;
132
+ parts.push(code !== void 0 ? `${current.message}(${code})` : current.message);
133
+ const aggregate = current;
134
+ current = current.cause ?? (Array.isArray(aggregate.errors) ? aggregate.errors[0] : void 0);
135
+ }
136
+ return parts.join(": ") || String(error);
137
+ }
138
+ /** HTTP 健康探测(global fetch,默认 5s 超时):2xx → ok;非 2xx/连接拒绝/超时 → ok:false 附 status 或 error */
139
+ async function httpProbe(url, timeoutMs = 5e3) {
140
+ try {
141
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
142
+ if (res.ok) return {
143
+ ok: true,
144
+ status: res.status
145
+ };
146
+ return {
147
+ ok: false,
148
+ status: res.status,
149
+ error: `HTTP ${res.status}`
150
+ };
151
+ } catch (error) {
152
+ return {
153
+ ok: false,
154
+ error: describeFetchError(error, timeoutMs)
155
+ };
156
+ }
157
+ }
158
+ /**
159
+ * 容器归属判定(M2-T3 归属 label 化):
160
+ * 1. **label 优先**——容器带 `deploy-cli.project` 归属 label 时只认 label(generateCompose 生成的容器都带),
161
+ * 同名段碰撞根治(`happy-app-1` 段匹配会撞上项目 `app`,label 指名 `happy-app` 后不再误配);
162
+ * 2. **无 label 回退**精确名后过滤(历史兼容):docker `--filter name=` 是子串匹配(`app` 会误伤 `myapp`/`application`),
163
+ * 这里要求项目名以完整连字符分段连续出现在容器名中(兼容 compose 的 `<前缀>-<服务名>-<序号>` 命名)。
164
+ * 末段 `-<数字>` 是 compose 副本号而非名字成分,先剥掉再匹配——否则 `...-test-2`(test 的 2 号副本)
165
+ * 会误配名为 `test-2` 的项目;恰以项目名命名的容器(container_name)走全等判定不受剥离影响。
166
+ */
167
+ function containerBelongsToProject(containerName, projectName, labels) {
168
+ if (projectName === "") return false;
169
+ const owned = labels?.[PROJECT_LABEL];
170
+ if (owned) return owned === projectName;
171
+ if (containerName === projectName) return true;
172
+ const segments = containerName.replace(/-\d+$/, "").split("-");
173
+ const want = projectName.split("-");
174
+ for (let i = 0; i + want.length <= segments.length; i++) if (want.every((w, j) => segments[i + j] === w)) return true;
175
+ return false;
176
+ }
177
+ /**
178
+ * 项目容器集合:docker name 过滤(子串)+ label 优先归属过滤(无 label 回退精确名后过滤)。
179
+ * all 语义可选(M2-T2 #14,与 ps --all 口径一致):缺省 true=含已停止容器(status/deploy 现口径不变),
180
+ * false=只查运行中(ps 不带 --all 的口径)。
181
+ * services 过滤(R14/F10):非空时只留 `com.docker.compose.service` 命中声明服务的容器(缺省/空=全部)。
182
+ */
183
+ async function findProjectContainers(docker, projectName, opts = {}) {
184
+ const listOpts = { name: projectName };
185
+ if (opts.all ?? true) listOpts.all = true;
186
+ const all = await docker.listContainers(listOpts);
187
+ const wanted = opts.services ?? [];
188
+ return all.filter((c) => {
189
+ if (!containerBelongsToProject(c.name, projectName, c.labels)) return false;
190
+ if (wanted.length === 0) return true;
191
+ const service = c.labels?.[COMPOSE_SERVICE_LABEL];
192
+ return service !== void 0 && wanted.includes(service);
193
+ });
194
+ }
195
+ /** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
196
+ async function probeNginxSite(slug, api) {
197
+ try {
198
+ return (await api.listSites()).includes(slug);
199
+ } catch {
200
+ return;
201
+ }
202
+ }
203
+ /** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位;nginx 判定可注入(M2-T2 #11 测试接缝,缺省 createNginx) */
204
+ async function checkProjectHealth(project, opts) {
205
+ const runner = opts.runner ?? run;
206
+ const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name, { services: project.services });
207
+ const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
208
+ const nginxPresent = await probeNginxSite(project.name, opts.nginx ?? createNginx(runner));
209
+ return {
210
+ name: project.name,
211
+ containers,
212
+ http,
213
+ nginxPresent
214
+ };
215
+ }
216
+ //#endregion
217
+ export { logsArgs as a, createDocker as i, findProjectContainers as n, httpProbe as r, checkProjectHealth as t };