@dongnanyang/deploy-cli 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  const argv = process.argv.slice(2);
3
3
  if (argv.length === 0 || argv[0] === "tui") await import("./main.js");
4
4
  else {
5
- const cli = await import("./cli-rULr9mal.js");
5
+ const cli = await import("./cli-DC-8dd-4.js");
6
6
  process.exitCode = await cli.main(argv);
7
7
  }
8
8
  //#endregion
@@ -1,9 +1,10 @@
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 { accessSync, constants } from "node:fs";
4
+ import { accessSync, constants, existsSync as existsSync$1, lstatSync, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
5
5
  import { spawn } from "node:child_process";
6
6
  import { parse } from "yaml";
7
+ import { join as join$1 } from "node:path";
7
8
  //#region src/core/exec.ts
8
9
  /** 仅 spawn 失败(ENOENT)与超时抛出 */
9
10
  var ExecError = class extends Error {
@@ -275,7 +276,7 @@ function createDocker(runner = run) {
275
276
  }
276
277
  //#endregion
277
278
  //#region src/cli/commands/logs.ts
278
- const USAGE$3 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
279
+ const USAGE$4 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
279
280
 
280
281
  选项:
281
282
  --tail <行数> 只显示最后 N 行(默认全部)
@@ -294,7 +295,7 @@ async function logs(args, options = {}) {
294
295
  for (let i = 0; i < args.length; i++) {
295
296
  const arg = args[i];
296
297
  if (arg === "-h" || arg === "--help") {
297
- log(USAGE$3);
298
+ log(USAGE$4);
298
299
  return 0;
299
300
  }
300
301
  if (arg === "--tail") {
@@ -302,7 +303,7 @@ async function logs(args, options = {}) {
302
303
  const parsed = Number(value);
303
304
  if (value === void 0 || value === "" || !Number.isInteger(parsed) || parsed < 0) {
304
305
  error(`--tail 需要非负整数参数: ${value ?? ""}`);
305
- error(USAGE$3);
306
+ error(USAGE$4);
306
307
  return 1;
307
308
  }
308
309
  tail = parsed;
@@ -314,14 +315,14 @@ async function logs(args, options = {}) {
314
315
  }
315
316
  if (arg.startsWith("-")) {
316
317
  error(`未知参数: ${arg}`);
317
- error(USAGE$3);
318
+ error(USAGE$4);
318
319
  return 1;
319
320
  }
320
321
  positionals.push(arg);
321
322
  }
322
323
  if (positionals.length !== 1) {
323
324
  error(positionals.length === 0 ? "缺少容器名参数" : `只支持一个容器名参数: ${positionals.join(" ")}`);
324
- error(USAGE$3);
325
+ error(USAGE$4);
325
326
  return 1;
326
327
  }
327
328
  const name = positionals[0];
@@ -453,6 +454,306 @@ function removeProject(cfg, name) {
453
454
  };
454
455
  }
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
+ const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
463
+ const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
464
+ const DEFAULT_CONF_D = "/etc/nginx/conf.d";
465
+ /** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
466
+ const ACME_HOME = "/root/.acme.sh";
467
+ /** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
468
+ const ACME_RENEW_SKIP = 2;
469
+ /** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
470
+ function pathExists(path) {
471
+ try {
472
+ lstatSync(path);
473
+ return true;
474
+ } catch {
475
+ return false;
476
+ }
477
+ }
478
+ /** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
479
+ function validateSlug(slug) {
480
+ if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符(禁止路径字符与大写)`);
481
+ }
482
+ function validateSpec(spec) {
483
+ validateSlug(spec.slug);
484
+ if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
485
+ if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
486
+ if (spec.ssl === "custom" && (!spec.certPath || !spec.keyPath)) throw new Error("ssl:custom 需要 certPath 与 keyPath");
487
+ }
488
+ /** 失败信息:命令原文 + exit 码 + stderr 摘要(包裹为 ExecError,附完整结果) */
489
+ function execFailure(cmd, args, result, note) {
490
+ const summary = result.stderr.trim().split("\n").filter((line) => line.trim() !== "").slice(0, 3).join(" ");
491
+ return new ExecError(`${note ? `${note}: ` : ""}命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`, result);
492
+ }
493
+ /**
494
+ * 路径探测:sites-available 与 sites-enabled 同时存在 → sites 模式(软链);否则 conf.d 模式(无软链)。
495
+ * 仅凭 sites-available 存在不足以走 sites 模式:无 sites-enabled 时(nginx.conf 直接 include sites-available/*)
496
+ * 软链无处落地,且 .bak/.new 会被 `include ...*` 通配吸入,破坏回滚与删除的生效性。
497
+ */
498
+ function resolveNginxPaths(exists = existsSync$1) {
499
+ if (exists(DEFAULT_SITES_AVAILABLE) && exists(DEFAULT_SITES_ENABLED)) return {
500
+ sitesAvailable: DEFAULT_SITES_AVAILABLE,
501
+ sitesEnabled: DEFAULT_SITES_ENABLED
502
+ };
503
+ return { sitesAvailable: DEFAULT_CONF_D };
504
+ }
505
+ /** 渲染 server 块;withSsl 时要求 certPath/keyPath(acme 需先 requestCert 取得) */
506
+ function renderBlock(spec, withSsl) {
507
+ validateSpec(spec);
508
+ if (withSsl && (!spec.certPath || !spec.keyPath)) throw new Error(`ssl:${spec.ssl} 需要 certPath 与 keyPath(acme 需先 requestCert 取得)`);
509
+ const lines = [];
510
+ lines.push(`# ${CONF_PREFIX}${spec.slug}${CONF_SUFFIX} — 由 deploy-cli 管理,请勿手动修改`);
511
+ lines.push("server {");
512
+ lines.push(" listen 80;");
513
+ if (withSsl) lines.push(" listen 443 ssl;");
514
+ lines.push(` server_name ${spec.serverName};`);
515
+ lines.push("");
516
+ if (withSsl) {
517
+ lines.push(` ssl_certificate ${spec.certPath};`);
518
+ lines.push(` ssl_certificate_key ${spec.keyPath};`);
519
+ lines.push("");
520
+ }
521
+ if (spec.root) {
522
+ lines.push(` root ${spec.root};`);
523
+ lines.push("");
524
+ lines.push(" location / {");
525
+ lines.push(" try_files $uri $uri/ =404;");
526
+ lines.push(" }");
527
+ } else {
528
+ lines.push(" location / {");
529
+ lines.push(` proxy_pass http://${spec.upstream};`);
530
+ lines.push(" proxy_set_header Host $host;");
531
+ lines.push(" proxy_set_header X-Real-IP $remote_addr;");
532
+ lines.push(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;");
533
+ lines.push(" proxy_set_header X-Forwarded-Proto $scheme;");
534
+ lines.push(" }");
535
+ }
536
+ lines.push("}");
537
+ return lines.join("\n") + "\n";
538
+ }
539
+ function createNginx(runner = run, paths) {
540
+ const resolved = paths ?? resolveNginxPaths();
541
+ const sitesAvailable = resolved.sitesAvailable;
542
+ const sitesEnabled = resolved.sitesEnabled;
543
+ const confName = (slug) => `${CONF_PREFIX}${slug}${CONF_SUFFIX}`;
544
+ /**
545
+ * 写盘/回滚流程:新内容写 .conf.new → 旧 conf 备份 .bak → .new 原子改名 → 建 sites-enabled 软链 → nginx -t;
546
+ * 失败:恢复 .bak(或删新文件)、移除本次新建的软链、抛 ExecError;成功:nginx -s reload、清 .bak。
547
+ */
548
+ async function writeSite(slug, content) {
549
+ const conf = join$1(sitesAvailable, confName(slug));
550
+ const tmp = `${conf}.new`;
551
+ const bak = `${conf}.bak`;
552
+ writeFileSync$1(tmp, content, "utf-8");
553
+ const existed = pathExists(conf);
554
+ if (existed) renameSync(conf, bak);
555
+ renameSync(tmp, conf);
556
+ const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
557
+ const linkCreated = link ? !pathExists(link) : false;
558
+ if (link && linkCreated) symlinkSync(conf, link);
559
+ const test = await runner("nginx", ["-t"]);
560
+ if (test.code !== 0) {
561
+ if (existed) renameSync(bak, conf);
562
+ else unlinkSync(conf);
563
+ if (link && linkCreated) unlinkSync(link);
564
+ throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
565
+ }
566
+ const reload = await runner("nginx", ["-s", "reload"]);
567
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
568
+ if (existed) unlinkSync(bak);
569
+ }
570
+ async function requestCert(domain) {
571
+ const acmeBin = `${ACME_HOME}/acme.sh`;
572
+ if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
573
+ const args = [
574
+ "--issue",
575
+ "--nginx",
576
+ "-d",
577
+ domain
578
+ ];
579
+ const result = await runner(acmeBin, args);
580
+ if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
581
+ return {
582
+ tool: "acme.sh",
583
+ certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
584
+ keyPath: `${ACME_HOME}/${domain}/${domain}.key`
585
+ };
586
+ }
587
+ if ((await runner("sh", ["-c", "command -v certbot"])).code === 0) {
588
+ const args = [
589
+ "--nginx",
590
+ "-d",
591
+ domain,
592
+ "--non-interactive",
593
+ "--agree-tos",
594
+ "--register-unsafely-without-email"
595
+ ];
596
+ const result = await runner("certbot", args);
597
+ if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
598
+ return {
599
+ tool: "certbot",
600
+ certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
601
+ keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
602
+ };
603
+ }
604
+ throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
605
+ }
606
+ return {
607
+ async applySite(spec) {
608
+ validateSpec(spec);
609
+ if (spec.ssl === "acme") {
610
+ await writeSite(spec.slug, renderBlock(spec, false));
611
+ const cert = await requestCert(spec.serverName);
612
+ await writeSite(spec.slug, renderBlock({
613
+ ...spec,
614
+ certPath: cert.certPath,
615
+ keyPath: cert.keyPath
616
+ }, true));
617
+ return;
618
+ }
619
+ await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
620
+ },
621
+ async removeSite(slug) {
622
+ validateSlug(slug);
623
+ const conf = join$1(sitesAvailable, confName(slug));
624
+ if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
625
+ const bak = `${conf}.bak`;
626
+ const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
627
+ const hadLink = link ? pathExists(link) : false;
628
+ renameSync(conf, bak);
629
+ if (link && hadLink) unlinkSync(link);
630
+ const test = await runner("nginx", ["-t"]);
631
+ if (test.code !== 0) {
632
+ renameSync(bak, conf);
633
+ if (link && hadLink) symlinkSync(conf, link);
634
+ throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
635
+ }
636
+ const reload = await runner("nginx", ["-s", "reload"]);
637
+ if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
638
+ unlinkSync(bak);
639
+ },
640
+ async listSites() {
641
+ 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();
642
+ },
643
+ requestCert
644
+ };
645
+ }
646
+ //#endregion
647
+ //#region src/cli/commands/nginx.ts
648
+ const USAGE$3 = `用法: deploy-cli nginx <apply|remove|list> [参数]
649
+
650
+ 子命令:
651
+ apply <project> [--no-ssl] 按 deploy.yaml 的 nginx 配置写入站点 conf 并启用
652
+ remove <project> 移除站点 conf 与软链
653
+ list 列出 deploy-cli 管理的站点
654
+
655
+ 示例:
656
+ deploy-cli nginx apply my-app
657
+ deploy-cli nginx apply my-app --no-ssl
658
+ deploy-cli nginx remove my-app
659
+ deploy-cli nginx list`;
660
+ /** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
661
+ function buildSpec(d, noSsl) {
662
+ if (!d.nginx) throw new Error(`项目 ${d.name} 未配置 nginx(deploy.yaml 缺 nginx 段)`);
663
+ const ssl = noSsl ? "none" : d.nginx.ssl;
664
+ if (ssl === "custom") throw new Error("ssl:custom 需要 certPath/keyPath,deploy.yaml 暂不支持;请改用 ssl:acme 或 ssl:none");
665
+ const spec = {
666
+ slug: d.name,
667
+ serverName: d.nginx.domain,
668
+ ssl
669
+ };
670
+ if (d.type === "static") spec.root = d.root;
671
+ else {
672
+ if (!d.nginx.upstream) throw new Error(`项目 ${d.name} 为 ${d.type} 型,缺少 nginx.upstream(代理目标,如 127.0.0.1:3000)`);
673
+ spec.upstream = d.nginx.upstream;
674
+ }
675
+ return spec;
676
+ }
677
+ /** nginx 站点管理:apply / remove / list;返回退出码 */
678
+ async function nginx(args, options = {}) {
679
+ const log = options.log ?? ((line) => console.log(line));
680
+ const error = options.error ?? ((line) => console.error(line));
681
+ const load = options.load ?? loadConfig;
682
+ const api = options.api ?? createNginx();
683
+ const [sub, ...rest] = args;
684
+ if (sub === "-h" || sub === "--help") {
685
+ log(USAGE$3);
686
+ return 0;
687
+ }
688
+ if (sub === void 0) {
689
+ error("缺少子命令");
690
+ error(USAGE$3);
691
+ return 1;
692
+ }
693
+ try {
694
+ switch (sub) {
695
+ case "apply": {
696
+ const unknown = rest.filter((a) => a.startsWith("-") && a !== "--no-ssl");
697
+ if (unknown.length > 0) {
698
+ error(`未知参数: ${unknown.join(" ")}`);
699
+ error(USAGE$3);
700
+ return 1;
701
+ }
702
+ const positional = rest.filter((a) => !a.startsWith("-"));
703
+ const name = positional[0];
704
+ if (name === void 0 || positional.length > 1) {
705
+ error("apply 需要且仅需要一个 <project> 参数");
706
+ error(USAGE$3);
707
+ return 1;
708
+ }
709
+ const noSsl = rest.includes("--no-ssl");
710
+ const row = listProjects(load()).find((r) => r.name === name);
711
+ if (!row) {
712
+ error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
713
+ return 1;
714
+ }
715
+ if (!row.config) {
716
+ error(`项目配置不可用: ${name}: ${row.error ?? ""}`);
717
+ return 1;
718
+ }
719
+ const spec = buildSpec(row.config, noSsl);
720
+ await api.applySite(spec);
721
+ log(`已应用站点: ${spec.slug}(deploy-cli-${spec.slug}.conf,server_name ${spec.serverName},ssl ${spec.ssl})`);
722
+ return 0;
723
+ }
724
+ case "remove": {
725
+ const name = rest[0];
726
+ if (name === void 0 || rest.length > 1) {
727
+ error("remove 需要且仅需要一个 <project> 参数");
728
+ error(USAGE$3);
729
+ return 1;
730
+ }
731
+ await api.removeSite(name);
732
+ log(`已移除站点配置: deploy-cli-${name}.conf`);
733
+ return 0;
734
+ }
735
+ case "list": {
736
+ if (rest.length > 0) {
737
+ error(`未知参数: ${rest.join(" ")}`);
738
+ error(USAGE$3);
739
+ return 1;
740
+ }
741
+ const sites = await api.listSites();
742
+ log("SLUG");
743
+ for (const slug of sites) log(slug);
744
+ return 0;
745
+ }
746
+ default:
747
+ error(`未知子命令: ${sub}`);
748
+ error(USAGE$3);
749
+ return 1;
750
+ }
751
+ } catch (err) {
752
+ error(err instanceof Error ? err.message : String(err));
753
+ return 1;
754
+ }
755
+ }
756
+ //#endregion
456
757
  //#region src/cli/commands/project.ts
457
758
  const USAGE$2 = `用法: deploy-cli project <list|add|remove> [参数]
458
759
 
@@ -602,7 +903,8 @@ const USAGE = `用法:
602
903
  deploy-cli doctor 环境自检
603
904
  deploy-cli ps 列出容器(--help 看示例)
604
905
  deploy-cli logs 查看容器日志(--help 看示例)
605
- deploy-cli project 项目注册表:list / add / remove(--help 看示例)`;
906
+ deploy-cli project 项目注册表:list / add / remove(--help 看示例)
907
+ deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)`;
606
908
  /** CLI 子命令分发,返回退出码 */
607
909
  async function main(argv) {
608
910
  const [command] = argv;
@@ -611,6 +913,7 @@ async function main(argv) {
611
913
  case "ps": return await ps(argv.slice(1));
612
914
  case "logs": return await logs(argv.slice(1));
613
915
  case "project": return await project(argv.slice(1));
916
+ case "nginx": return await nginx(argv.slice(1));
614
917
  case "help":
615
918
  case "--help":
616
919
  case "-h":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dongnanyang/deploy-cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Local CLI TUI for SSH tunnels & deploy scripts",
5
5
  "type": "module",
6
6
  "bin": {