@dongnanyang/deploy-cli 0.8.0 → 0.9.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.
@@ -0,0 +1,714 @@
1
+ import { n as loadConfig, r as saveConfig } from "./config-xUl8Oa3T.js";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
3
+ import { homedir } from "os";
4
+ import { resolve } from "path";
5
+ import { parse, stringify } from "yaml";
6
+ import { existsSync as existsSync$1, lstatSync, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
7
+ import { join as join$1 } from "node:path";
8
+ import { execFileSync, spawn } from "node:child_process";
9
+ //#region src/core/exec.ts
10
+ /**
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 匹配集补齐)。
14
+ */
15
+ function stderrSummary(stderr) {
16
+ const lines = stderr.trim().split("\n").filter((line) => line.trim() !== "");
17
+ const errors = lines.filter((line) => /error|fatal|failed|emerg|alert|crit/i.test(line));
18
+ return (errors.length > 0 ? errors.slice(-3) : lines.slice(-3)).join(" ");
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
+ }
28
+ /** 仅 spawn 失败(ENOENT)与超时抛出 */
29
+ var ExecError = class extends Error {
30
+ result;
31
+ constructor(message, result) {
32
+ super(message);
33
+ this.name = "ExecError";
34
+ this.result = result;
35
+ }
36
+ };
37
+ /** 超时 SIGTERM 后等待子进程退出的宽限时长,超过则 SIGKILL */
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
+ }
72
+ /** 按 \n 切行缓冲,结束时补发无结尾换行的残行 */
73
+ function createLineBuffer(stream, onLine) {
74
+ let buffer = "";
75
+ let text = "";
76
+ /** 回调抛异常跳过该次调用即可,不得影响数据捕获与后续行回调 */
77
+ const emit = (line) => {
78
+ try {
79
+ onLine?.(line, stream);
80
+ } catch {}
81
+ };
82
+ return {
83
+ push(chunk) {
84
+ text += chunk;
85
+ buffer += chunk;
86
+ let index = buffer.indexOf("\n");
87
+ while (index !== -1) {
88
+ const line = buffer.slice(0, index);
89
+ buffer = buffer.slice(index + 1);
90
+ emit(line);
91
+ index = buffer.indexOf("\n");
92
+ }
93
+ },
94
+ /** flush 残行并返回累计全文 */
95
+ flush() {
96
+ if (buffer.length > 0) {
97
+ emit(buffer);
98
+ buffer = "";
99
+ }
100
+ return text;
101
+ }
102
+ };
103
+ }
104
+ /** 执行命令并捕获退出码与输出 */
105
+ async function run(cmd, args, opts = {}) {
106
+ const cmdLine = [cmd, ...args].join(" ");
107
+ return new Promise((resolve, reject) => {
108
+ const child = spawn(cmd, args, {
109
+ cwd: opts.cwd,
110
+ env: opts.env,
111
+ stdio: [
112
+ "ignore",
113
+ "pipe",
114
+ "pipe"
115
+ ]
116
+ });
117
+ const out = createLineBuffer("stdout", opts.onLine);
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
+ };
128
+ let settled = false;
129
+ let timedOut = false;
130
+ let timeoutNote = "";
131
+ let killTimer;
132
+ const timeoutTimer = opts.timeoutMs ? setTimeout(() => {
133
+ timedOut = true;
134
+ timeoutNote = `timeout: ${cmdLine}\n`;
135
+ killTree("SIGTERM");
136
+ killTimer = setTimeout(() => killTree("SIGKILL"), KILL_GRACE_MS);
137
+ }, opts.timeoutMs) : void 0;
138
+ child.stdout?.setEncoding("utf-8");
139
+ child.stderr?.setEncoding("utf-8");
140
+ child.stdout?.on("data", (chunk) => out.push(chunk));
141
+ child.stderr?.on("data", (chunk) => err.push(chunk));
142
+ child.on("error", (error) => {
143
+ if (settled) return;
144
+ settled = true;
145
+ clearTimeout(timeoutTimer);
146
+ clearTimeout(killTimer);
147
+ const message = `spawn 失败: ${cmdLine}: ${error.message}`;
148
+ reject(new ExecError(message, {
149
+ code: 127,
150
+ stdout: out.flush(),
151
+ stderr: `${message}\n`
152
+ }));
153
+ });
154
+ child.on("close", (code) => {
155
+ if (settled) return;
156
+ settled = true;
157
+ clearTimeout(timeoutTimer);
158
+ clearTimeout(killTimer);
159
+ const stderr = err.flush();
160
+ const result = {
161
+ code: code ?? (timedOut ? 124 : 1),
162
+ stdout: out.flush(),
163
+ stderr: stderr + timeoutNote
164
+ };
165
+ if (timedOut) {
166
+ const summary = stderrSummary(stderr);
167
+ reject(new ExecError(`timeout: ${cmdLine}${summary ? `: ${summary}` : ""}`, result));
168
+ return;
169
+ }
170
+ resolve(result);
171
+ });
172
+ });
173
+ }
174
+ //#endregion
175
+ //#region src/core/nginx.ts
176
+ /** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
177
+ const CONF_PREFIX = "deploy-cli-";
178
+ const CONF_SUFFIX = ".conf";
179
+ /** slug 合法形状(M2-T2 #6 收紧):小写字母数字与连字符、不得连字符开头;项目 name 同用作 slug(F4 前移校验共用) */
180
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
181
+ /** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
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])?)*$/;
183
+ const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
184
+ const UPSTREAM_RE = /^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):([0-9]{1,5})$/;
185
+ const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
186
+ const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
187
+ const DEFAULT_CONF_D = "/etc/nginx/conf.d";
188
+ /** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
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
+ }
206
+ /** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
207
+ const ACME_RENEW_SKIP = 2;
208
+ /** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
209
+ function pathExists(path) {
210
+ try {
211
+ lstatSync(path);
212
+ return true;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+ /** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
218
+ function validateSlug(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);
224
+ }
225
+ function validateSpec(spec) {
226
+ validateSlug(spec.slug);
227
+ if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
228
+ if (!DOMAIN_RE.test(spec.serverName)) throw new Error(`NginxSiteSpec.serverName 非法: ${JSON.stringify(spec.serverName)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止 conf 元字符与空白)`);
229
+ if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
230
+ if (spec.root !== void 0 && spec.root !== "") validateAbsPath("root", spec.root);
231
+ if (spec.upstream !== void 0 && spec.upstream !== "") {
232
+ const match = spec.upstream.match(UPSTREAM_RE);
233
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) throw new Error(`NginxSiteSpec.upstream 非法: ${JSON.stringify(spec.upstream)},须为 host:port(端口 1-65535;禁止 conf 元字符与空白)`);
234
+ }
235
+ if (spec.ssl === "custom" && (!spec.certPath || !spec.keyPath)) throw new Error("ssl:custom 需要 certPath 与 keyPath");
236
+ if (spec.certPath) validateAbsPath("certPath", spec.certPath);
237
+ if (spec.keyPath) validateAbsPath("keyPath", spec.keyPath);
238
+ }
239
+ function validateAbsPath(field, value) {
240
+ if (!ABS_PATH_RE.test(value)) throw new Error(`NginxSiteSpec.${field} 非法: ${JSON.stringify(value)},须为绝对路径且不含 conf 元字符与空白`);
241
+ }
242
+ /** 失败信息:统一走 core/exec 文案模板(M2-T2 #2 壳统一,R12 与 docker.ts 同口径),可附提示,包裹为 ExecError 附完整结果 */
243
+ function execFailure(cmd, args, result, note) {
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 });
262
+ }
263
+ /**
264
+ * 路径探测:sites-available 与 sites-enabled 同时存在 → sites 模式(软链);否则 conf.d 模式(无软链)。
265
+ * 仅凭 sites-available 存在不足以走 sites 模式:无 sites-enabled 时(nginx.conf 直接 include sites-available/*)
266
+ * 软链无处落地,且 .bak/.new 会被 `include ...*` 通配吸入,破坏回滚与删除的生效性。
267
+ */
268
+ function resolveNginxPaths(exists = existsSync$1) {
269
+ if (exists(DEFAULT_SITES_AVAILABLE) && exists(DEFAULT_SITES_ENABLED)) return {
270
+ sitesAvailable: DEFAULT_SITES_AVAILABLE,
271
+ sitesEnabled: DEFAULT_SITES_ENABLED
272
+ };
273
+ return { sitesAvailable: DEFAULT_CONF_D };
274
+ }
275
+ /** 渲染 server 块;withSsl 时要求 certPath/keyPath(acme 需先 requestCert 取得) */
276
+ function renderBlock(spec, withSsl) {
277
+ validateSpec(spec);
278
+ if (withSsl && (!spec.certPath || !spec.keyPath)) throw new Error(`ssl:${spec.ssl} 需要 certPath 与 keyPath(acme 需先 requestCert 取得)`);
279
+ const lines = [];
280
+ lines.push(`# ${CONF_PREFIX}${spec.slug}${CONF_SUFFIX} — 由 deploy-cli 管理,请勿手动修改`);
281
+ lines.push("server {");
282
+ lines.push(" listen 80;");
283
+ if (withSsl) lines.push(" listen 443 ssl;");
284
+ lines.push(` server_name ${spec.serverName};`);
285
+ lines.push("");
286
+ if (withSsl) {
287
+ lines.push(` ssl_certificate ${spec.certPath};`);
288
+ lines.push(` ssl_certificate_key ${spec.keyPath};`);
289
+ lines.push("");
290
+ }
291
+ if (spec.root) {
292
+ lines.push(` root ${spec.root};`);
293
+ lines.push("");
294
+ lines.push(" location / {");
295
+ lines.push(" try_files $uri $uri/ =404;");
296
+ lines.push(" }");
297
+ } else {
298
+ lines.push(" location / {");
299
+ lines.push(` proxy_pass http://${spec.upstream};`);
300
+ lines.push(" proxy_set_header Host $host;");
301
+ lines.push(" proxy_set_header X-Real-IP $remote_addr;");
302
+ lines.push(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;");
303
+ lines.push(" proxy_set_header X-Forwarded-Proto $scheme;");
304
+ lines.push(" }");
305
+ }
306
+ lines.push("}");
307
+ return lines.join("\n") + "\n";
308
+ }
309
+ function createNginx(runner = run, paths) {
310
+ const resolved = paths ?? resolveNginxPaths();
311
+ const sitesAvailable = resolved.sitesAvailable;
312
+ const sitesEnabled = resolved.sitesEnabled;
313
+ const confName = (slug) => `${CONF_PREFIX}${slug}${CONF_SUFFIX}`;
314
+ const tmpName = (slug) => `.${confName(slug)}.new`;
315
+ const bakName = (slug) => `.${confName(slug)}.bak`;
316
+ /**
317
+ * 写盘/回滚流程:新内容写隐藏 .conf.new → 旧 conf 备份隐藏 .bak → .new 原子改名 → 建 sites-enabled 软链 → nginx -t;
318
+ * 失败:恢复 .bak(或删新文件)、移除本次新建的软链、抛 ExecError;成功:nginx -s reload、清 .bak。
319
+ * 写盘段(写 .new/改名/软链)与 nginx -t 同一回滚口径(M2-T2 #8):段内任一 fs 操作失败即整体恢复再抛出。
320
+ */
321
+ async function writeSite(slug, content) {
322
+ const conf = join$1(sitesAvailable, confName(slug));
323
+ const tmp = join$1(sitesAvailable, tmpName(slug));
324
+ const bak = join$1(sitesAvailable, bakName(slug));
325
+ const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
326
+ const existed = pathExists(conf);
327
+ const linkCreated = link ? !pathExists(link) : false;
328
+ /** 统一回滚:恢复/清除 conf、软链、.new 临时文件(R13:逐项守护,单项失败记 stderr 继续,回滚不抛) */
329
+ const rollback = () => {
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
+ ]);
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
+ }
361
+ let test;
362
+ try {
363
+ test = await runner("nginx", ["-t"]);
364
+ } catch (error) {
365
+ rollback();
366
+ throw error;
367
+ }
368
+ if (test.code !== 0) {
369
+ rollback();
370
+ throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
371
+ }
372
+ const reloadNote = existed ? `nginx reload 失败,保留备份 ${bak} 供人工恢复` : `nginx reload 失败(新建站点无备份可回退),conf 已写入 ${conf},可手工 nginx -s reload 重试或删除该 conf`;
373
+ let reload;
374
+ try {
375
+ reload = await runner("nginx", ["-s", "reload"]);
376
+ } catch (error) {
377
+ throw wrapReloadFailure(error, reloadNote);
378
+ }
379
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, reloadNote);
380
+ if (existed) unlinkSync(bak);
381
+ }
382
+ async function requestCert(domain) {
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) {
386
+ const args = [
387
+ "--issue",
388
+ "--nginx",
389
+ "-d",
390
+ domain
391
+ ];
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 = [{
395
+ certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
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
404
+ };
405
+ throw new Error(`acme.sh 签发完成但未找到证书文件(已探测 ${candidates.map((c) => c.certPath).join(" 与 ")}),请检查 acme.sh 安装证书目录`);
406
+ }
407
+ const certbot = certbotProbeCommand();
408
+ if ((await runner(certbot.cmd, certbot.args)).code === 0) {
409
+ const args = [
410
+ "--nginx",
411
+ "-d",
412
+ domain,
413
+ "--non-interactive",
414
+ "--agree-tos",
415
+ "--register-unsafely-without-email"
416
+ ];
417
+ const result = await runner("certbot", args);
418
+ if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
419
+ return {
420
+ tool: "certbot",
421
+ certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
422
+ keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
423
+ };
424
+ }
425
+ throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
426
+ }
427
+ return {
428
+ async applySite(spec) {
429
+ validateSpec(spec);
430
+ if (spec.ssl === "acme") {
431
+ await writeSite(spec.slug, renderBlock(spec, false));
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
+ }
440
+ await writeSite(spec.slug, renderBlock({
441
+ ...spec,
442
+ certPath: cert.certPath,
443
+ keyPath: cert.keyPath
444
+ }, true));
445
+ return;
446
+ }
447
+ await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
448
+ },
449
+ async removeSite(slug) {
450
+ validateSlug(slug);
451
+ const conf = join$1(sitesAvailable, confName(slug));
452
+ if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
453
+ const bak = join$1(sitesAvailable, bakName(slug));
454
+ const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
455
+ const hadLink = link ? pathExists(link) : false;
456
+ /**
457
+ * 与 applySite 同等回滚对等(R2)+ 写盘段同款收口(R13):逐项守护(单项失败记 stderr 继续恢复其余项),
458
+ * 回滚自身绝不抛错;软链仅在缺失时重建(unlink 失败的半删场景下软链仍在,不得 EEXIST 二次伤害)。
459
+ */
460
+ const rollback = () => {
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
+ }]);
470
+ };
471
+ try {
472
+ renameSync(conf, bak);
473
+ if (link && hadLink) unlinkSync(link);
474
+ } catch (error) {
475
+ rollback();
476
+ throw error;
477
+ }
478
+ let test;
479
+ try {
480
+ test = await runner("nginx", ["-t"]);
481
+ } catch (error) {
482
+ rollback();
483
+ throw error;
484
+ }
485
+ if (test.code !== 0) {
486
+ rollback();
487
+ throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
488
+ }
489
+ const reloadNote = `nginx reload 失败,保留备份 ${bak} 供人工恢复`;
490
+ let reload;
491
+ try {
492
+ reload = await runner("nginx", ["-s", "reload"]);
493
+ } catch (error) {
494
+ throw wrapReloadFailure(error, reloadNote);
495
+ }
496
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, reloadNote);
497
+ unlinkSync(bak);
498
+ },
499
+ async listSites() {
500
+ 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();
501
+ },
502
+ requestCert
503
+ };
504
+ }
505
+ //#endregion
506
+ //#region src/core/types.ts
507
+ /** 容器归属 label 键(M2-T3):generateCompose 写入 compose 服务级 labels,归属判定优先匹配,无 label 回退精确名后过滤 */
508
+ const PROJECT_LABEL = "deploy-cli.project";
509
+ /** compose 自动标注的服务名 label(R14/F10):deploy.yaml `services` 过滤口径,缺省/空=全部 */
510
+ const COMPOSE_SERVICE_LABEL = "com.docker.compose.service";
511
+ //#endregion
512
+ //#region src/core/project.ts
513
+ const VALID_TYPES = [
514
+ "compose",
515
+ "image",
516
+ "static"
517
+ ];
518
+ const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
519
+ const VALID_SSL = [
520
+ "none",
521
+ "acme",
522
+ "custom"
523
+ ];
524
+ const VALID_UPDATE = ["git-pull", "none"];
525
+ /** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
526
+ var ProjectConfigError = class extends Error {
527
+ field;
528
+ constructor(message, field) {
529
+ super(message);
530
+ this.name = "ProjectConfigError";
531
+ this.field = field;
532
+ }
533
+ };
534
+ /** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
535
+ function loadProject(dir) {
536
+ const yamlPath = resolve(dir, "deploy.yaml");
537
+ let raw;
538
+ try {
539
+ raw = readFileSync(yamlPath, "utf-8");
540
+ } catch (error) {
541
+ const reason = error instanceof Error ? error.message : String(error);
542
+ if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
543
+ throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
544
+ }
545
+ let parsed;
546
+ try {
547
+ parsed = parse(raw);
548
+ } catch (error) {
549
+ throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
550
+ }
551
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
552
+ return validate(parsed);
553
+ }
554
+ /** 校验并规范化 deploy.yaml 模型:name(含 slug 形状)→ type 合法性 → 类型必填字段 → nginx.domain 非空 → deploy 段值域 */
555
+ function validate(raw) {
556
+ const name = raw.name;
557
+ if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
558
+ if (!isValidSlug(name)) throw new ProjectConfigError(`name 非法: ${JSON.stringify(name)},仅允许小写字母、数字与连字符且以字母数字开头(name 将用作 nginx 站点 slug)`, "name");
559
+ const type = raw.type;
560
+ if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
561
+ if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
562
+ if (type === "image" && (typeof raw.image !== "string" || raw.image.trim() === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
563
+ if (type === "static" && (typeof raw.root !== "string" || raw.root.trim() === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
564
+ if (raw.services !== void 0 && raw.services !== null) {
565
+ if (!Array.isArray(raw.services) || raw.services.some((s) => typeof s !== "string" || s.trim() === "")) throw new ProjectConfigError("services 应为字符串数组(参与部署/状态面板的服务名,如 [web])", "services");
566
+ }
567
+ if (raw.nginx !== void 0 && raw.nginx !== null) {
568
+ const nginx = raw.nginx;
569
+ if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
570
+ const n = nginx;
571
+ if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
572
+ if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
573
+ }
574
+ if (raw.deploy !== void 0 && raw.deploy !== null) {
575
+ const deploy = raw.deploy;
576
+ if (typeof deploy !== "object" || Array.isArray(deploy)) throw new ProjectConfigError("deploy 应为对象", "deploy");
577
+ const dp = deploy;
578
+ if (dp.update !== void 0 && dp.update !== null) {
579
+ if (typeof dp.update !== "string" || !VALID_UPDATE.includes(dp.update)) throw new ProjectConfigError(`deploy.update 非法: ${JSON.stringify(dp.update)},合法值: git-pull | none(不设=不自动更新)`, "deploy.update");
580
+ }
581
+ if (dp.build !== void 0 && dp.build !== null && typeof dp.build !== "string") throw new ProjectConfigError("deploy.build 应为字符串(构建命令)", "deploy.build");
582
+ for (const hook of ["pre", "post"]) {
583
+ const hooks = dp[hook];
584
+ if (hooks !== void 0 && hooks !== null && (!Array.isArray(hooks) || hooks.some((c) => typeof c !== "string"))) throw new ProjectConfigError(`deploy.${hook} 应为字符串数组(命令列表)`, `deploy.${hook}`);
585
+ }
586
+ }
587
+ const d = raw;
588
+ if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
589
+ return d;
590
+ }
591
+ /** 校验后写出 <dir>/deploy.yaml */
592
+ function saveProject(dir, d) {
593
+ const normalized = validate({ ...d });
594
+ const out = {};
595
+ for (const [key, value] of Object.entries(normalized)) if (value !== void 0) out[key] = value;
596
+ writeFileSync(resolve(dir, "deploy.yaml"), stringify(out), "utf-8");
597
+ }
598
+ /** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
599
+ function listProjects(cfg) {
600
+ return cfg.projects.map((project) => {
601
+ try {
602
+ return {
603
+ name: project.name,
604
+ path: project.path,
605
+ config: loadProject(project.path)
606
+ };
607
+ } catch (error) {
608
+ return {
609
+ name: project.name,
610
+ path: project.path,
611
+ config: null,
612
+ error: error instanceof Error ? error.message : String(error)
613
+ };
614
+ }
615
+ });
616
+ }
617
+ /** 注册冲突预检(addProject/createManagedProject 共用):同名或同路径均拒,文案口径与 addProject 一致 */
618
+ function assertRegistrable(cfg, name, normalizedPath) {
619
+ const byName = cfg.projects.find((p) => p.name === name);
620
+ if (byName) throw new Error(`项目已注册: ${name}(${byName.path}),请先 remove 再 add`);
621
+ const byPath = cfg.projects.find((p) => resolve(p.path) === normalizedPath);
622
+ if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${normalizedPath}`);
623
+ }
624
+ /** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig);dir 在核心层 resolve 归一(M2-T2 #9) */
625
+ function addProject(cfg, dir) {
626
+ const normalized = resolve(dir);
627
+ const config = loadProject(normalized);
628
+ assertRegistrable(cfg, config.name, normalized);
629
+ const entry = {
630
+ name: config.name,
631
+ path: normalized,
632
+ deployDir: "deploy"
633
+ };
634
+ return {
635
+ ...cfg,
636
+ projects: [...cfg.projects, entry]
637
+ };
638
+ }
639
+ /** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
640
+ function removeProject(cfg, name) {
641
+ const projects = cfg.projects.filter((p) => p.name !== name);
642
+ if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
643
+ return {
644
+ ...cfg,
645
+ projects
646
+ };
647
+ }
648
+ /** image 型生成的 docker-compose.yml 标记头(护栏 marker):既有同名文件无此头则拒绝覆盖(终审 M1:防绑架项目文件) */
649
+ const COMPOSE_MARKER = "# generated by deploy-cli — do not edit";
650
+ /** marker 判定扫描窗口(A2):不再死盯首行——运维头注释把 marker 挤到前几行仍认;窗口外不认 */
651
+ const MARKER_SCAN_LINES = 10;
652
+ /** 既有文件内容是否带 COMPOSE_MARKER 头(前 10 行内任一行,M2-T2 A2:不再信任首行) */
653
+ function hasComposeMarker(content) {
654
+ return content.split("\n").slice(0, MARKER_SCAN_LINES).some((line) => line.trim() === COMPOSE_MARKER);
655
+ }
656
+ /** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment),首行带 COMPOSE_MARKER 标记头 */
657
+ function generateCompose(d) {
658
+ if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
659
+ if (typeof d.image !== "string" || d.image.trim() === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
660
+ const service = { image: d.image };
661
+ service.labels = { [PROJECT_LABEL]: d.name };
662
+ if (d.ports && d.ports.length > 0) service.ports = d.ports;
663
+ if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
664
+ if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
665
+ return `${COMPOSE_MARKER}\n${stringify({ services: { [d.name]: service } })}`;
666
+ }
667
+ /** 托管项目名形状(与 nginx SLUG_RE 同一正则:小写字母数字与连字符、字母数字开头) */
668
+ const MANAGED_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
669
+ /** 托管根目录 ~/.deploy-cli/projects(spec 反目标「绑架项目文件」:image/static 无源码项目的唯一可写落点) */
670
+ function managedRoot() {
671
+ return resolve(homedir(), ".deploy-cli", "projects");
672
+ }
673
+ /** 托管项目目录 <managedRoot>/<name>;name 先过形状校验(防路径穿越/大写/空白非法名) */
674
+ function managedDir(name) {
675
+ if (!MANAGED_NAME_RE.test(name)) throw new ProjectConfigError(`name 非法: ${JSON.stringify(name)},仅允许小写字母、数字与连字符且以字母数字开头(托管目录名)`, "name");
676
+ return resolve(managedRoot(), name);
677
+ }
678
+ /**
679
+ * 一键建托管项目(M2-T3,Task 6 创建向导的 API):校验 → 托管目录落 deploy.yaml(image 型加生成 compose,含 COMPOSE_MARKER+归属 label)→ 自动注册进 config.json。
680
+ * 护栏:非法输入/注册冲突零落盘;既有 deploy.yaml 与无 marker 头 compose 一律拒绝覆盖(防绑架项目文件);文件绝不写 cwd。
681
+ */
682
+ function createManagedProject(input) {
683
+ const dir = managedDir(input.name);
684
+ const raw = {
685
+ name: input.name,
686
+ type: input.type
687
+ };
688
+ if (input.services !== void 0) raw.services = input.services;
689
+ if (input.type === "image") {
690
+ raw.image = input.image;
691
+ raw.ports = input.ports;
692
+ raw.volumes = input.volumes;
693
+ raw.env = input.env;
694
+ }
695
+ if (input.type === "static") raw.root = input.root;
696
+ if (input.nginx !== void 0) raw.nginx = input.nginx;
697
+ const config = validate(raw);
698
+ const yamlPath = resolve(dir, "deploy.yaml");
699
+ const composePath = resolve(dir, DEFAULT_COMPOSE_FILE);
700
+ const composeText = config.type === "image" ? generateCompose(config) : void 0;
701
+ if (existsSync(yamlPath)) throw new ProjectConfigError(`托管目录已有 deploy.yaml,拒绝覆盖: ${yamlPath}`, "name");
702
+ if (composeText !== void 0 && existsSync(composePath) && !hasComposeMarker(readFileSync(composePath, "utf-8"))) throw new ProjectConfigError(`托管目录已有非 deploy-cli 生成的 ${DEFAULT_COMPOSE_FILE}(缺 marker 头 "${COMPOSE_MARKER}"),拒绝覆盖: ${composePath}`);
703
+ assertRegistrable(loadConfig(), config.name, dir);
704
+ mkdirSync(dir, { recursive: true });
705
+ saveProject(dir, config);
706
+ if (composeText !== void 0) writeFileSync(composePath, composeText, "utf-8");
707
+ saveConfig(addProject(loadConfig(), dir));
708
+ return {
709
+ dir,
710
+ config
711
+ };
712
+ }
713
+ //#endregion
714
+ export { certbotProbeCommand as _, generateCompose as a, execFailureMessage as b, loadProject as c, removeProject as d, saveProject as f, acmeProbeCommand as g, ACME_BIN as h, createManagedProject as i, managedDir as l, PROJECT_LABEL as m, ProjectConfigError as n, hasComposeMarker as o, COMPOSE_SERVICE_LABEL as p, addProject as r, listProjects as s, COMPOSE_MARKER as t, managedRoot as u, createNginx as v, run as x, resolveNginxPaths as y };