home-hosted 0.11.0 → 0.12.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.
Files changed (314) hide show
  1. package/README.md +273 -628
  2. package/dist/chunks/archive-DpCwA8Nf.js +339 -0
  3. package/dist/chunks/archive-DpCwA8Nf.js.map +1 -0
  4. package/dist/chunks/atomic-CEfCUfkQ.js +25 -0
  5. package/dist/chunks/atomic-CEfCUfkQ.js.map +1 -0
  6. package/dist/chunks/backup-CPrJVPJI.js +797 -0
  7. package/dist/chunks/backup-CPrJVPJI.js.map +1 -0
  8. package/dist/chunks/backups-Bd2SF2qd.js +4346 -0
  9. package/dist/chunks/backups-Bd2SF2qd.js.map +1 -0
  10. package/dist/chunks/config-text-DifCHhnz.js +50 -0
  11. package/dist/chunks/config-text-DifCHhnz.js.map +1 -0
  12. package/dist/chunks/contracts-ku5ypHXJ.js +2256 -0
  13. package/dist/chunks/contracts-ku5ypHXJ.js.map +1 -0
  14. package/dist/chunks/daemon-TwXk5vb8.js +215 -0
  15. package/dist/chunks/daemon-TwXk5vb8.js.map +1 -0
  16. package/dist/chunks/daemon-log-BVj8cDEo.js +241 -0
  17. package/dist/chunks/daemon-log-BVj8cDEo.js.map +1 -0
  18. package/dist/chunks/docker-CGv4Uv7w.js +436 -0
  19. package/dist/chunks/docker-CGv4Uv7w.js.map +1 -0
  20. package/dist/chunks/down-BlX5X3bm.js +378 -0
  21. package/dist/chunks/down-BlX5X3bm.js.map +1 -0
  22. package/dist/chunks/init-DdmqHVra.js +263 -0
  23. package/dist/chunks/init-DdmqHVra.js.map +1 -0
  24. package/dist/chunks/last-stop-BZ08Z89-.js +52 -0
  25. package/dist/chunks/last-stop-BZ08Z89-.js.map +1 -0
  26. package/dist/chunks/layout-D74TGUnr.js +24 -0
  27. package/dist/chunks/layout-D74TGUnr.js.map +1 -0
  28. package/dist/chunks/log-buffer-HnP0jKhZ.js +350 -0
  29. package/dist/chunks/log-buffer-HnP0jKhZ.js.map +1 -0
  30. package/dist/chunks/logger-B5U4GD3j.js +13 -0
  31. package/dist/chunks/logger-B5U4GD3j.js.map +1 -0
  32. package/dist/chunks/logs-gI_69Q1P.js +265 -0
  33. package/dist/chunks/logs-gI_69Q1P.js.map +1 -0
  34. package/dist/chunks/migrate-BTlsibvF.js +155 -0
  35. package/dist/chunks/migrate-BTlsibvF.js.map +1 -0
  36. package/dist/chunks/nanny-20aBXL1o.js +1069 -0
  37. package/dist/chunks/nanny-20aBXL1o.js.map +1 -0
  38. package/dist/chunks/nanny-CjnnrIpm.js +132 -0
  39. package/dist/chunks/nanny-CjnnrIpm.js.map +1 -0
  40. package/dist/chunks/nanny-DUaAfCV-.js +39 -0
  41. package/dist/chunks/nanny-DUaAfCV-.js.map +1 -0
  42. package/dist/chunks/nanny-sweep-Ca9kPAVi.js +104 -0
  43. package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +1 -0
  44. package/dist/chunks/nearest-6KgQEDUe.js +41 -0
  45. package/dist/chunks/nearest-6KgQEDUe.js.map +1 -0
  46. package/dist/chunks/parse-B9owE47G.js +383 -0
  47. package/dist/chunks/parse-B9owE47G.js.map +1 -0
  48. package/dist/chunks/paths-BT94q6-w.js +172 -0
  49. package/dist/chunks/paths-BT94q6-w.js.map +1 -0
  50. package/dist/chunks/port-B8WBTRMk.js +333 -0
  51. package/dist/chunks/port-B8WBTRMk.js.map +1 -0
  52. package/dist/chunks/restart-UZgeDukG.js +126 -0
  53. package/dist/chunks/restart-UZgeDukG.js.map +1 -0
  54. package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  55. package/dist/chunks/schema-o7Lgk0V1.js +102 -0
  56. package/dist/chunks/schema-o7Lgk0V1.js.map +1 -0
  57. package/dist/chunks/secrets-D7PdYh71.js +544 -0
  58. package/dist/chunks/secrets-D7PdYh71.js.map +1 -0
  59. package/dist/chunks/server-BuIeSsRu.js +169 -0
  60. package/dist/chunks/server-BuIeSsRu.js.map +1 -0
  61. package/dist/chunks/server-ids-DRuNLVCV.js +32 -0
  62. package/dist/chunks/server-ids-DRuNLVCV.js.map +1 -0
  63. package/dist/chunks/set-password-DegMumPh.js +43 -0
  64. package/dist/chunks/set-password-DegMumPh.js.map +1 -0
  65. package/dist/chunks/set-token-21d1FTDC.js +78 -0
  66. package/dist/chunks/set-token-21d1FTDC.js.map +1 -0
  67. package/dist/chunks/settings-BVSBnIwJ.js +332 -0
  68. package/dist/chunks/settings-BVSBnIwJ.js.map +1 -0
  69. package/dist/chunks/setup-temp-XiuAtiW2.js +150 -0
  70. package/dist/chunks/setup-temp-XiuAtiW2.js.map +1 -0
  71. package/dist/chunks/shape-DnTKzjQ2.js +24 -0
  72. package/dist/chunks/shape-DnTKzjQ2.js.map +1 -0
  73. package/dist/chunks/src-BL97vLVb.js +11153 -0
  74. package/dist/chunks/src-BL97vLVb.js.map +1 -0
  75. package/dist/chunks/status-EuWdRq8Q.js +119 -0
  76. package/dist/chunks/status-EuWdRq8Q.js.map +1 -0
  77. package/dist/chunks/ui-DbPuwddJ.js +323 -0
  78. package/dist/chunks/ui-DbPuwddJ.js.map +1 -0
  79. package/dist/chunks/ui-dir-CsU3uLNV.js +39 -0
  80. package/dist/chunks/ui-dir-CsU3uLNV.js.map +1 -0
  81. package/dist/chunks/ui-release-DKzVvlLd.js +312 -0
  82. package/dist/chunks/ui-release-DKzVvlLd.js.map +1 -0
  83. package/dist/chunks/ui-revert-BhqOAhmM.js +27 -0
  84. package/dist/chunks/ui-revert-BhqOAhmM.js.map +1 -0
  85. package/dist/chunks/ui-switch-CMoslPO2.js +150 -0
  86. package/dist/chunks/ui-switch-CMoslPO2.js.map +1 -0
  87. package/dist/chunks/ui-update-TTBBoDik.js +272 -0
  88. package/dist/chunks/ui-update-TTBBoDik.js.map +1 -0
  89. package/dist/chunks/up-C4H13hBw.js +196 -0
  90. package/dist/chunks/up-C4H13hBw.js.map +1 -0
  91. package/dist/chunks/usage-CSBgLRN5.js +85 -0
  92. package/dist/chunks/usage-CSBgLRN5.js.map +1 -0
  93. package/dist/chunks/workspaces-CAln2sQ7.js +221 -0
  94. package/dist/chunks/workspaces-CAln2sQ7.js.map +1 -0
  95. package/dist/chunks/wsl-temperature-BiCI4iK6.js +322 -0
  96. package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -0
  97. package/dist/cli.js +218 -25205
  98. package/dist/cli.js.map +1 -1
  99. package/dist/client.js +120 -0
  100. package/dist/client.js.map +1 -0
  101. package/dist/types/api/acme.d.ts +24 -0
  102. package/dist/types/api/auth/$.routes.d.ts +103 -0
  103. package/dist/types/api/backups.d.ts +179 -0
  104. package/dist/types/api/control.d.ts +469 -0
  105. package/dist/types/api/ddns.d.ts +432 -0
  106. package/dist/types/api/events.d.ts +21 -0
  107. package/dist/types/api/health.d.ts +27 -0
  108. package/dist/types/api/logs.d.ts +95 -0
  109. package/dist/types/api/metrics.d.ts +19 -0
  110. package/dist/types/api/notifications.d.ts +141 -0
  111. package/dist/types/api/proxy.d.ts +1128 -0
  112. package/dist/types/api/servers/$.routes.d.ts +1318 -0
  113. package/dist/types/api/settings.d.ts +642 -0
  114. package/dist/types/api/state.d.ts +492 -0
  115. package/dist/types/api/static.d.ts +11 -0
  116. package/dist/types/api/tls.d.ts +112 -0
  117. package/dist/types/api/workspaces/$.routes.d.ts +797 -0
  118. package/dist/types/api/wsl-temperature.d.ts +113 -0
  119. package/dist/types/app.d.ts +6080 -0
  120. package/dist/types/cli/args.d.ts +75 -0
  121. package/dist/types/cli/backup-offline.d.ts +23 -0
  122. package/dist/types/cli/backup.d.ts +79 -0
  123. package/dist/types/cli/down.d.ts +75 -0
  124. package/dist/types/cli/init.d.ts +60 -0
  125. package/dist/types/cli/io.d.ts +65 -0
  126. package/dist/types/cli/logs.d.ts +64 -0
  127. package/dist/types/cli/migrate.d.ts +33 -0
  128. package/dist/types/cli/nanny.d.ts +19 -0
  129. package/dist/types/cli/nearest.d.ts +10 -0
  130. package/dist/types/cli/restart.d.ts +42 -0
  131. package/dist/types/cli/server.d.ts +68 -0
  132. package/dist/types/cli/set-password.d.ts +14 -0
  133. package/dist/types/cli/set-token.d.ts +21 -0
  134. package/dist/types/cli/setup-temp.d.ts +65 -0
  135. package/dist/types/cli/status.d.ts +14 -0
  136. package/dist/types/cli/ui-revert.d.ts +3 -0
  137. package/dist/types/cli/ui-switch.d.ts +27 -0
  138. package/dist/types/cli/ui-update.d.ts +72 -0
  139. package/dist/types/cli/up.d.ts +90 -0
  140. package/dist/types/cli/usage.d.ts +23 -0
  141. package/dist/types/cli.d.ts +12 -0
  142. package/dist/types/client.d.ts +6284 -0
  143. package/dist/types/config/layout.d.ts +11 -0
  144. package/dist/types/config/migrations.d.ts +69 -0
  145. package/dist/types/config/parse.d.ts +54 -0
  146. package/dist/types/config/patch.d.ts +20 -0
  147. package/dist/types/config/schema.d.ts +318 -0
  148. package/dist/types/config/secret-parts.d.ts +48 -0
  149. package/dist/types/config/secrets.d.ts +206 -0
  150. package/dist/types/config/seed.d.ts +30 -0
  151. package/dist/types/config/server-ids.d.ts +14 -0
  152. package/dist/types/config/settings.d.ts +74 -0
  153. package/dist/types/config/store.d.ts +132 -0
  154. package/dist/types/config/workspaces.d.ts +96 -0
  155. package/dist/types/helpers/action-result.d.ts +46 -0
  156. package/dist/types/helpers/atomic.d.ts +9 -0
  157. package/dist/types/helpers/backoff.d.ts +7 -0
  158. package/dist/types/helpers/bind.d.ts +16 -0
  159. package/dist/types/helpers/config-text.d.ts +23 -0
  160. package/dist/types/helpers/cookies.d.ts +19 -0
  161. package/dist/types/helpers/copy-tree.d.ts +15 -0
  162. package/dist/types/helpers/daemon-log.d.ts +45 -0
  163. package/dist/types/helpers/daemon.d.ts +122 -0
  164. package/dist/types/helpers/deferred.d.ts +7 -0
  165. package/dist/types/helpers/env-file.d.ts +20 -0
  166. package/dist/types/helpers/error.d.ts +18 -0
  167. package/dist/types/helpers/factory.d.ts +6 -0
  168. package/dist/types/helpers/last-stop.d.ts +20 -0
  169. package/dist/types/helpers/logger.d.ts +7 -0
  170. package/dist/types/helpers/open.d.ts +2 -0
  171. package/dist/types/helpers/openapi.d.ts +46 -0
  172. package/dist/types/helpers/paths.d.ts +94 -0
  173. package/dist/types/helpers/restore-lock.d.ts +32 -0
  174. package/dist/types/helpers/runtime.d.ts +18 -0
  175. package/dist/types/helpers/secret-compare.d.ts +13 -0
  176. package/dist/types/helpers/shell.d.ts +19 -0
  177. package/dist/types/helpers/sse.d.ts +23 -0
  178. package/dist/types/helpers/template.d.ts +8 -0
  179. package/dist/types/helpers/ui-dir.d.ts +11 -0
  180. package/dist/types/helpers/validate.d.ts +7 -0
  181. package/dist/types/helpers/validator.d.ts +12 -0
  182. package/dist/types/helpers/version.d.ts +10 -0
  183. package/dist/types/helpers/workspace.d.ts +25 -0
  184. package/dist/types/index.d.ts +17 -0
  185. package/dist/types/middleware/auth.d.ts +37 -0
  186. package/dist/types/middleware/host.d.ts +29 -0
  187. package/dist/types/middleware/loopback.d.ts +18 -0
  188. package/dist/types/openapi-reference.d.ts +22 -0
  189. package/dist/types/openapi.d.ts +34 -0
  190. package/dist/types/providers/archive.d.ts +54 -0
  191. package/dist/types/providers/backup-hook.d.ts +34 -0
  192. package/dist/types/providers/ddns/cloudflare.d.ts +2 -0
  193. package/dist/types/providers/ddns/desec.d.ts +2 -0
  194. package/dist/types/providers/ddns/digitalocean.d.ts +2 -0
  195. package/dist/types/providers/ddns/duckdns.d.ts +2 -0
  196. package/dist/types/providers/ddns/dyndns2.d.ts +15 -0
  197. package/dist/types/providers/ddns/dynu.d.ts +2 -0
  198. package/dist/types/providers/ddns/freedns.d.ts +2 -0
  199. package/dist/types/providers/ddns/gandi.d.ts +2 -0
  200. package/dist/types/providers/ddns/godaddy.d.ts +2 -0
  201. package/dist/types/providers/ddns/henet.d.ts +3 -0
  202. package/dist/types/providers/ddns/index.d.ts +12 -0
  203. package/dist/types/providers/ddns/ip.d.ts +27 -0
  204. package/dist/types/providers/ddns/namecheap-api.d.ts +13 -0
  205. package/dist/types/providers/ddns/namecheap.d.ts +6 -0
  206. package/dist/types/providers/ddns/noip.d.ts +2 -0
  207. package/dist/types/providers/ddns/porkbun.d.ts +2 -0
  208. package/dist/types/providers/ddns/spaceship.d.ts +7 -0
  209. package/dist/types/providers/ddns/types.d.ts +98 -0
  210. package/dist/types/providers/ddns/zone.d.ts +11 -0
  211. package/dist/types/providers/docker.d.ts +117 -0
  212. package/dist/types/providers/entry-state.d.ts +15 -0
  213. package/dist/types/providers/health-check.d.ts +27 -0
  214. package/dist/types/providers/host.d.ts +147 -0
  215. package/dist/types/providers/identity.d.ts +54 -0
  216. package/dist/types/providers/log-tail.d.ts +29 -0
  217. package/dist/types/providers/nanny-sweep.d.ts +51 -0
  218. package/dist/types/providers/nanny.d.ts +94 -0
  219. package/dist/types/providers/port.d.ts +142 -0
  220. package/dist/types/providers/proc.d.ts +116 -0
  221. package/dist/types/providers/process.d.ts +61 -0
  222. package/dist/types/providers/proxy/caddy.d.ts +2 -0
  223. package/dist/types/providers/proxy/index.d.ts +7 -0
  224. package/dist/types/providers/proxy/types.d.ts +54 -0
  225. package/dist/types/providers/server-vars.d.ts +4 -0
  226. package/dist/types/providers/telegram.d.ts +32 -0
  227. package/dist/types/providers/ui-release.d.ts +113 -0
  228. package/dist/types/providers/webhook.d.ts +64 -0
  229. package/dist/types/providers/wsl-temperature.d.ts +69 -0
  230. package/dist/types/services/acme-challenge.d.ts +44 -0
  231. package/dist/types/services/auth.d.ts +145 -0
  232. package/dist/types/services/backups.d.ts +352 -0
  233. package/dist/types/services/config-watch.d.ts +40 -0
  234. package/dist/types/services/control-server.d.ts +58 -0
  235. package/dist/types/services/ddns.d.ts +67 -0
  236. package/dist/types/services/dependencies.d.ts +21 -0
  237. package/dist/types/services/events.d.ts +17 -0
  238. package/dist/types/services/exposure.d.ts +33 -0
  239. package/dist/types/services/history.d.ts +36 -0
  240. package/dist/types/services/host-monitor.d.ts +32 -0
  241. package/dist/types/services/init.d.ts +71 -0
  242. package/dist/types/services/log-buffer.d.ts +28 -0
  243. package/dist/types/services/log-files.d.ts +87 -0
  244. package/dist/types/services/log-relay.d.ts +36 -0
  245. package/dist/types/services/nanny.d.ts +14 -0
  246. package/dist/types/services/notifications.d.ts +124 -0
  247. package/dist/types/services/panel.d.ts +194 -0
  248. package/dist/types/services/proxy-config.d.ts +83 -0
  249. package/dist/types/services/proxy.d.ts +454 -0
  250. package/dist/types/services/state.d.ts +41 -0
  251. package/dist/types/services/supervisor/compose.d.ts +17 -0
  252. package/dist/types/services/supervisor/entry.d.ts +139 -0
  253. package/dist/types/services/supervisor/health.d.ts +55 -0
  254. package/dist/types/services/supervisor/pending-load.d.ts +6 -0
  255. package/dist/types/services/supervisor/persistent.d.ts +55 -0
  256. package/dist/types/services/supervisor/port-preflight.d.ts +45 -0
  257. package/dist/types/services/supervisor/records.d.ts +38 -0
  258. package/dist/types/services/supervisor/spawn.d.ts +15 -0
  259. package/dist/types/services/supervisor/view.d.ts +4 -0
  260. package/dist/types/services/supervisor.d.ts +113 -0
  261. package/dist/types/services/tls.d.ts +48 -0
  262. package/dist/types/services/ui-update.d.ts +44 -0
  263. package/dist/types/services/ui.d.ts +50 -0
  264. package/dist/types/shared/api-client.d.ts +137 -0
  265. package/dist/types/shared/backup-scope.d.ts +109 -0
  266. package/dist/types/shared/clone.d.ts +14 -0
  267. package/dist/types/shared/contracts.d.ts +4233 -0
  268. package/dist/types/shared/cpu-scale.d.ts +25 -0
  269. package/dist/types/shared/ddns-form.d.ts +62 -0
  270. package/dist/types/shared/endpoint.d.ts +8 -0
  271. package/dist/types/shared/error-message.d.ts +8 -0
  272. package/dist/types/shared/fields.d.ts +21 -0
  273. package/dist/types/shared/generated.d.ts +26 -0
  274. package/dist/types/shared/host-readings.d.ts +185 -0
  275. package/dist/types/shared/patch-diff.d.ts +94 -0
  276. package/dist/types/shared/probe-latency.d.ts +25 -0
  277. package/dist/types/shared/proxy-form.d.ts +182 -0
  278. package/dist/types/shared/server-attention.d.ts +37 -0
  279. package/dist/types/shared/server-key.d.ts +13 -0
  280. package/dist/types/shared/server-readings.d.ts +55 -0
  281. package/dist/types/shared/server-url.d.ts +43 -0
  282. package/dist/types/shared/shape.d.ts +17 -0
  283. package/dist/types/shared/ui-format.d.ts +89 -0
  284. package/docs/API.md +180 -0
  285. package/docs/BACKUPS.md +97 -0
  286. package/docs/CLI.md +122 -0
  287. package/docs/DDNS.md +9 -1
  288. package/docs/RESTORE_DEMO.md +1 -1
  289. package/docs/REVERSE_PROXY.md +2 -2
  290. package/docs/SECURITY.md +82 -0
  291. package/docs/SERVERS.md +41 -13
  292. package/docs/UI_CREATION.md +82 -291
  293. package/package.json +18 -8
  294. package/uis/stock/dist/assets/de-DyGrM1KK.js +1 -0
  295. package/uis/stock/dist/assets/es-BebHdc0E.js +1 -0
  296. package/uis/stock/dist/assets/fr-DsDTrxhI.js +1 -0
  297. package/uis/stock/dist/assets/index-6LANO2Ua.css +2 -0
  298. package/uis/stock/dist/assets/{index-KdyqrVv8.js → index-D06cUZbM.js} +15 -12
  299. package/uis/stock/dist/assets/ja-D3RARJjW.js +1 -0
  300. package/uis/stock/dist/assets/ko-CKI3dFoD.js +1 -0
  301. package/uis/stock/dist/assets/ru-DEU5ujXt.js +1 -0
  302. package/uis/stock/dist/assets/vi-ULKPnasj.js +1 -0
  303. package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +1 -0
  304. package/uis/stock/dist/index.html +2 -2
  305. package/uis/stock/dist/ui.json +3 -3
  306. package/uis/stock/dist/assets/de-0YLueNal.js +0 -1
  307. package/uis/stock/dist/assets/es-FCHhRmn2.js +0 -1
  308. package/uis/stock/dist/assets/fr-C69Z8o0z.js +0 -1
  309. package/uis/stock/dist/assets/index-Cok5msAO.css +0 -2
  310. package/uis/stock/dist/assets/ja-Chz9YOqR.js +0 -1
  311. package/uis/stock/dist/assets/ko-CtXZ2x1l.js +0 -1
  312. package/uis/stock/dist/assets/ru-D_jE64xN.js +0 -1
  313. package/uis/stock/dist/assets/vi-sxSffss7.js +0 -1
  314. package/uis/stock/dist/assets/zh-CN-ChTpf29X.js +0 -1
@@ -0,0 +1,797 @@
1
+ import { C as errorMessage, _ as prompt, c as bold, d as dim, f as fail, g as paint, h as invocation, m as green } from "../cli.js";
2
+ import { n as GlobalSettingsStore } from "./settings-BVSBnIwJ.js";
3
+ import { a as globalSettingsPath, i as globalSecretsPath, j as workspacesPath, s as hhDir, x as tlsDir, y as resolveUserPath } from "./paths-BT94q6-w.js";
4
+ import { _ as entryStatePath, a as unknownBackupIds, b as WorkspaceStore, n as buildBackupSources, t as BackupService, v as readEntryState, y as writeEntryState } from "./backups-Bd2SF2qd.js";
5
+ import { n as WorkspaceRegistry } from "./workspaces-CAln2sQ7.js";
6
+ import { g as readNannyState } from "./nanny-20aBXL1o.js";
7
+ import process from "node:process";
8
+ import { defineCommand } from "citty";
9
+ import path from "node:path";
10
+ import fs from "node:fs";
11
+ //#region src/cli/backup-offline.ts
12
+ /**
13
+ * A backup service for a host whose panel is **not running**.
14
+ *
15
+ * `backup` used to need the daemon because the service is built inside it, so backing up or
16
+ * restoring meant leaving the panel up — the opposite of what someone migrating a machine wants.
17
+ * Nothing in the service needs the daemon: every source is a file, and the one live fact it wants
18
+ * (which entries are running) is on disk as the nanny state each entry writes.
19
+ *
20
+ * This builds the same sources the panel does, through the same `buildBackupSources`, so an offline
21
+ * archive cannot differ from an online one. `runningServers` is answered from `.state/*.json` rather
22
+ * than from supervisor views: a *persistent* entry keeps running when the panel stops, so "no panel"
23
+ * does not mean "nothing is running", and the restore warning has to keep telling the truth.
24
+ */
25
+ /** The workspace ids this host knows, from the registry on disk. */
26
+ function workspaceIds(registry) {
27
+ return registry.all().map((workspace) => ({
28
+ id: workspace.id,
29
+ label: workspace.label
30
+ }));
31
+ }
32
+ /**
33
+ * Entries whose nanny is alive right now, read from the state files they rewrite.
34
+ *
35
+ * Every path comes from `hhDir`, never from the module-level helpers: those resolve from this
36
+ * process's own `HHOSTED_HOME`, so a caller passing `--home` elsewhere would read a different host's
37
+ * state — which is exactly how a test came to depend on the developer's real `~/.home-hosted`.
38
+ */
39
+ function runningFromDisk(hhDir, ids) {
40
+ const running = [];
41
+ for (const workspaceId of ids) {
42
+ const stateDir = path.join(hhDir, workspaceId, ".state");
43
+ let names;
44
+ try {
45
+ names = fs.readdirSync(stateDir);
46
+ } catch {
47
+ continue;
48
+ }
49
+ for (const name of names) {
50
+ if (!name.endsWith(".json") || name.endsWith(".spec.json") || name.endsWith(".tmp")) continue;
51
+ const serverId = name.replace(/\.run\.json$|\.json$/, "");
52
+ if (serverId.length === 0) continue;
53
+ const state = readNannyState(path.join(stateDir, name));
54
+ if (state === null) continue;
55
+ if (Date.now() - state.heartbeatAt <= 3e4) running.push({
56
+ workspaceId,
57
+ serverId
58
+ });
59
+ }
60
+ }
61
+ return running;
62
+ }
63
+ /**
64
+ * Build the service against this host's files.
65
+ *
66
+ * `ensureWorkspace` and `onRestored` are the two panel hooks, and both are deliberately absent: with
67
+ * no daemon there is nothing to reload, and a restore that brings a workspace this host lacks leaves
68
+ * it on disk for the next `up` to pick up. The registry is written by the service itself, which is
69
+ * what makes that work.
70
+ */
71
+ function createOfflineBackup(options = {}) {
72
+ const hhDir$1 = options.hhDir ?? hhDir;
73
+ const settingsPath = options.settingsPath ?? globalSettingsPath;
74
+ const registryPath = path.join(hhDir$1, path.basename(workspacesPath));
75
+ const settings = new GlobalSettingsStore(settingsPath);
76
+ settings.load();
77
+ const registry = new WorkspaceRegistry(registryPath);
78
+ registry.load();
79
+ const workspaces = workspaceIds(registry);
80
+ const ids = workspaces.map((workspace) => workspace.id);
81
+ const loaded = workspaces.map((workspace) => {
82
+ const dir = path.join(hhDir$1, workspace.id);
83
+ const settingsPath = path.join(dir, "settings.json");
84
+ const serversPath = path.join(dir, "servers.config.json");
85
+ const secretsPath = path.join(dir, ".secrets.json");
86
+ const store = new WorkspaceStore(workspace.id, settingsPath, serversPath);
87
+ store.load();
88
+ return {
89
+ id: workspace.id,
90
+ label: workspace.label,
91
+ settingsPath,
92
+ serversPath,
93
+ secretsPath,
94
+ servers: store.servers
95
+ };
96
+ });
97
+ return {
98
+ service: new BackupService({
99
+ dataRoot: hhDir$1,
100
+ getConfig: () => settings.backups,
101
+ /**
102
+ * Register a workspace the archive brought.
103
+ *
104
+ * A panel-only hook in the running case, because the panel creates the runtime itself. With no
105
+ * panel there is nobody to do it, so the registry is written here — otherwise a restored
106
+ * workspace's files land on disk unreachable, and the next `up` never looks at them.
107
+ */
108
+ /**
109
+ * Record the staged dump so the entry's next `up` loads it.
110
+ *
111
+ * Nothing is running to hold it in memory, so this is the only path that matters offline: the
112
+ * panel is started afterwards, reads the entry state, and runs the hook.
113
+ */
114
+ onLoadPending: (workspaceId, serverId, dumpDir) => {
115
+ const dir = path.join(hhDir$1, workspaceId, ".state");
116
+ fs.mkdirSync(dir, { recursive: true });
117
+ const statePath = entryStatePath(dir, serverId);
118
+ const persisted = readEntryState(statePath);
119
+ writeEntryState(statePath, {
120
+ ...persisted ?? {
121
+ restarts: 0,
122
+ bootstrapDone: false
123
+ },
124
+ pendingLoad: dumpDir
125
+ });
126
+ },
127
+ ensureWorkspace: (input) => {
128
+ if (registry.has(input.id)) return;
129
+ registry.create(input);
130
+ },
131
+ getSources: () => buildBackupSources({
132
+ globalSettingsPath: settings.path,
133
+ globalSecretsPath: path.join(hhDir$1, path.basename(globalSecretsPath)),
134
+ tlsDir: path.join(hhDir$1, path.basename(tlsDir)),
135
+ registryPath,
136
+ includePaths: settings.backups.includePaths,
137
+ runningServers: () => runningFromDisk(hhDir$1, ids),
138
+ workspaces: loaded
139
+ })
140
+ }),
141
+ workspaceIds: ids,
142
+ runningNow: () => runningFromDisk(hhDir$1, ids)
143
+ };
144
+ }
145
+ //#endregion
146
+ //#region src/cli/backup.ts
147
+ /**
148
+ * Render plan ids as the tree they already are.
149
+ *
150
+ * Every id is a colon-separated path, so the hierarchy is in the data and the renderer's only job is
151
+ * to show it: one row per prefix, each one level deeper than its parent. Depth is whatever the id
152
+ * says, not a fixed number of columns — `workspace:default:secrets:telegram` sits three deep, and a
153
+ * renderer that assumed two printed it beside its own parent.
154
+ *
155
+ * Both directions print through this, and so does the "what could I act on" list, so the three read
156
+ * alike. A row's note is the panel's own wording, passed through untouched.
157
+ */
158
+ function printPlanTree(rows, out = (text) => process.stdout.write(text)) {
159
+ const known = new Set(rows.map((row) => row.id));
160
+ const nodes = /* @__PURE__ */ new Map();
161
+ const ensure = (id) => {
162
+ const existing = nodes.get(id);
163
+ if (existing !== void 0) return existing;
164
+ const created = {
165
+ note: null,
166
+ children: /* @__PURE__ */ new Set()
167
+ };
168
+ nodes.set(id, created);
169
+ return created;
170
+ };
171
+ for (const row of rows) {
172
+ const segments = row.id.split(":");
173
+ for (let depth = 1; depth <= segments.length; depth++) {
174
+ const id = segments.slice(0, depth).join(":");
175
+ const node = ensure(id);
176
+ if (depth > 1) ensure(segments.slice(0, depth - 1).join(":")).children.add(id);
177
+ if (depth === segments.length && known.has(row.id)) node.note = row.note ?? null;
178
+ }
179
+ }
180
+ const roots = [...nodes.keys()].filter((id) => !id.includes(":"));
181
+ const write = (id, depth) => {
182
+ const node = nodes.get(id);
183
+ if (node === void 0) return;
184
+ out(`${" ".repeat(depth)}${depth === 1 ? "" : "- "}${id}${node.note === null ? "" : ` ${dim(`(${node.note})`)}`}\n`);
185
+ for (const child of node.children) write(child, depth + 1);
186
+ };
187
+ for (const root of roots) write(root, 1);
188
+ }
189
+ function human(bytes) {
190
+ if (bytes < 1024) return `${bytes} B`;
191
+ if (bytes < 1048576) return `${Math.round(bytes / 1024)} KB`;
192
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
193
+ }
194
+ /** The running panel's record, or a message saying what to do instead. */
195
+ async function livePanel() {
196
+ const daemon = await import("./daemon-TwXk5vb8.js");
197
+ const runtime = daemon.readRuntime();
198
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) {
199
+ if (runtime !== null && await daemon.runtimeIsGone(runtime)) daemon.clearRuntime();
200
+ return null;
201
+ }
202
+ return Object.assign(runtime, { request: daemon.requestControl });
203
+ }
204
+ /**
205
+ * Whether to talk to a panel or work on the files directly.
206
+ *
207
+ * Both paths run the same service, so the only question is who owns the state: a live panel is the
208
+ * authority on what is running, and a stopped one has no opinion to disagree with.
209
+ */
210
+ async function usesPanel() {
211
+ const daemon = await import("./daemon-TwXk5vb8.js");
212
+ const runtime = daemon.readRuntime();
213
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) return false;
214
+ return (await daemon.probeRuntime(runtime)).reachable;
215
+ }
216
+ /**
217
+ * The offline service.
218
+ *
219
+ * It reads the same files the panel does — every workspace's `settings.json` and
220
+ * `servers.config.json` under the state root — so an archive taken with the panel down holds what a
221
+ * running one would have captured.
222
+ */
223
+ async function offlineBackup() {
224
+ return createOfflineBackup();
225
+ }
226
+ /** Turn a non-200 control answer into the panel's own message, or the status. */
227
+ function refusal(answer) {
228
+ const body = answer.body;
229
+ if (body?.message !== void 0) fail(body.message);
230
+ fail(`the panel answered ${answer.status}`);
231
+ }
232
+ /**
233
+ * The flag combination, as far as it can be judged without asking the panel.
234
+ *
235
+ * `null` means "neither flag", which only the caller can resolve — it lists the available ids, and
236
+ * that needs a panel. Every other case is decided here, before any lookup, so a typo is refused
237
+ * whether or not anything is running.
238
+ */
239
+ function parseScope(all, raw) {
240
+ if (all && raw !== void 0) fail("--include and --all are exclusive — pass one or the other");
241
+ if (all) return { kind: "all" };
242
+ if (raw === void 0) return null;
243
+ const ids = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
244
+ if (ids.length === 0) fail("--include is empty — name the ids to act on, or pass --all for everything");
245
+ return {
246
+ kind: "include",
247
+ ids
248
+ };
249
+ }
250
+ /**
251
+ * The plan rows a scope selects, and an exclusion drops.
252
+ *
253
+ * `kind` is deliberately not part of this: it is the panel's label for a row, not an id, and every id
254
+ * the plan prints is already prefixed with it (`global:settings`, `workspace:default:servers`).
255
+ */
256
+ /** Flatten a nested plan into the rows the tree renders. */
257
+ function flattenRows(rows) {
258
+ return rows.flatMap((row) => [{
259
+ id: row.id,
260
+ note: row.note ?? null
261
+ }, ...(row.items ?? []).map((leaf) => ({
262
+ id: leaf.id,
263
+ note: leaf.note ?? null
264
+ }))]);
265
+ }
266
+ function filterEntries(entries, scope, exclude) {
267
+ const unwanted = exclude ?? [];
268
+ const excluded = (id) => unwanted.some((entry) => id === entry || id.startsWith(`${entry}:`));
269
+ const named = (id) => scope.kind === "all" || scope.ids.some((entry) => id === entry || id.startsWith(`${entry}:`) || entry.startsWith(`${id}:`));
270
+ return entries.filter((entry) => named(entry.id) && !excluded(entry.id)).map((entry) => entry.items === void 0 ? entry : {
271
+ ...entry,
272
+ items: entry.items.filter((leaf) => named(leaf.id) && !excluded(leaf.id))
273
+ });
274
+ }
275
+ /**
276
+ * Refuse an id the plan does not have.
277
+ *
278
+ * An id that matches nothing is silently ignored by the service, which is right for an archive that
279
+ * simply does not carry something — and wrong for a typo: `--exclude global:secret` excludes nothing
280
+ * and says nothing, so the archive carries the credentials the person believed they had dropped.
281
+ *
282
+ * `action` decides the hint, because the two directions list their ids from different places: a
283
+ * create plan lists what this host declares, a restore plan lists what the archive holds — and the
284
+ * command that prints that one is a restore, not a create.
285
+ */
286
+ function assertKnown(ids, entries, flag, action) {
287
+ if (ids === void 0) return;
288
+ const unknown = unknownBackupIds(ids, entries);
289
+ if (unknown.length > 0) {
290
+ const hint = action === "create" ? `\`backup create\` with no flags lists the ids` : `\`backup restore <name>\` with no --include/--exclude lists the ids the archive holds`;
291
+ fail(`${flag} names ${unknown.map((id) => `"${id}"`).join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not in this plan — ${hint}`);
292
+ }
293
+ }
294
+ /** `--exclude` parsed. An empty value is a mistake, not "exclude nothing". */
295
+ function parseExclude(raw) {
296
+ if (raw === void 0) return void 0;
297
+ const ids = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
298
+ if (ids.length === 0) fail("--exclude is empty — name the ids to leave out, or drop the flag");
299
+ return ids;
300
+ }
301
+ /**
302
+ * Neither flag given. Refused outright — the ids are a *bonus*, not the reason.
303
+ *
304
+ * The refusal must not depend on a panel being up: a mistyped command deserves the flag error, not
305
+ * "home-hosted is not running". So the list is best-effort, and a failure to produce it is silent.
306
+ */
307
+ async function refuseWithoutScope(action, suffix) {
308
+ const rows = await availableRows(action, suffix).catch(() => []);
309
+ if (rows.length === 0) fail("name what to act on — pass --include <ids> or --all");
310
+ process.stderr.write(`${paint("31", "error")} name what to act on — pass --include <ids> or --all\n\n`);
311
+ process.stderr.write("available (or narrow it):\n");
312
+ printPlanTree(flattenRows(rows), (text) => process.stderr.write(text));
313
+ process.stderr.write("\n--exclude <ids> leaves those out: --all --exclude global:secrets\n");
314
+ process.exit(1);
315
+ }
316
+ /**
317
+ * The ids an offline run could act on, read from the state files.
318
+ *
319
+ * The refusal has to name real ids whether or not a panel is up — an empty list is the one answer
320
+ * worse than no list, because it reads as "there is nothing to back up".
321
+ */
322
+ async function availableRowsFromDisk(action, suffix) {
323
+ try {
324
+ const { service } = await offlineBackup();
325
+ await service.warm();
326
+ if (action === "create") return service.selection().entries;
327
+ const query = new URLSearchParams(suffix.startsWith("?") ? suffix.slice(1) : suffix);
328
+ const from = query.get("from");
329
+ const name = query.get("name");
330
+ const archive = from !== null && from.length > 0 ? fs.existsSync(from) && fs.statSync(from).isFile() ? from : null : name === null || name.length === 0 ? null : service.resolve(name);
331
+ if (archive === null) return [];
332
+ return ((await service.restore(archive, { confirm: false })).items ?? []).filter((item) => item.selected !== false);
333
+ } catch {
334
+ return [];
335
+ }
336
+ }
337
+ /**
338
+ * The ids this action could be scoped to.
339
+ *
340
+ * `create` asks what the entries declare; `restore` asks what the archive holds. Both come from the
341
+ * panel, so the list in a refusal is the real one rather than a hardcoded guess. A panel that cannot
342
+ * be reached yields no ids — the refusal still fires, it just cannot enumerate.
343
+ */
344
+ async function availableRows(action, suffix) {
345
+ const daemon = await import("./daemon-TwXk5vb8.js");
346
+ const runtime = daemon.readRuntime();
347
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) return await availableRowsFromDisk(action, suffix);
348
+ const path = action === "create" ? "/_hh/backups" : "/_hh/backups/restore";
349
+ const answer = await daemon.requestControl(runtime, `${path}${suffix}`, 12e4);
350
+ if (answer === null || answer.status !== 200) return [];
351
+ const body = answer.body;
352
+ return action === "create" ? body?.entries ?? [] : body?.items ?? [];
353
+ }
354
+ /** `?a=b`, or `''`. */
355
+ function suffixOf(query) {
356
+ return query.size === 0 ? "" : `?${query.toString()}`;
357
+ }
358
+ /** Appends one query parameter, keeping the `?`/`&` right. */
359
+ function withParam(suffix, key, value) {
360
+ return `${suffix}${suffix === "" ? "?" : "&"}${key}=${encodeURIComponent(value)}`;
361
+ }
362
+ /**
363
+ * Ask before writing.
364
+ *
365
+ * A session that cannot be asked gets the plan and a one-line instruction — not a silent write, and
366
+ * not a silent no-op that looks like one.
367
+ */
368
+ async function consent(question) {
369
+ if (process.stdin.isTTY !== true) {
370
+ process.stdout.write("\nnot applied — this session cannot ask. Re-run with `--confirm` to apply.\n");
371
+ return false;
372
+ }
373
+ const answer = await prompt(`${question} [y/N] `);
374
+ if (/^yes$|^y$/i.test(answer.trim())) {
375
+ process.stdout.write("\n");
376
+ return true;
377
+ }
378
+ process.stdout.write("cancelled — nothing was written\n");
379
+ return false;
380
+ }
381
+ /**
382
+ * Run against the panel when one is up, and against the files when it is not.
383
+ *
384
+ * Both run the same `BackupService`, so the archive cannot differ; only the authority on what is
385
+ * running changes. A stopped panel is exactly when someone wants to back up or restore — the services
386
+ * are down because they stopped them on purpose.
387
+ */
388
+ async function runBackupList(json) {
389
+ if (await usesPanel()) {
390
+ const runtime = await livePanel();
391
+ if (runtime !== null) {
392
+ const answer = await runtime.request(runtime, "/_hh/backups", 3e4, "GET");
393
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
394
+ if (answer.status !== 200) refusal(answer);
395
+ printList(answer.body, json);
396
+ return;
397
+ }
398
+ }
399
+ const { service } = await offlineBackup();
400
+ await service.warm();
401
+ printList(service.selection(), json);
402
+ }
403
+ function printList(view, json) {
404
+ const files = view?.files ?? [];
405
+ if (json) {
406
+ process.stdout.write(`${JSON.stringify(view, null, 2)}\n`);
407
+ return;
408
+ }
409
+ if (files.length === 0) {
410
+ process.stdout.write(`no backups yet — \`${invocation()} backup create --all\` takes one\n`);
411
+ return;
412
+ }
413
+ const noun = files.length === 1 ? "archive" : "archives";
414
+ process.stdout.write(`${bold(String(files.length))} ${noun}${view?.dir === void 0 ? "" : ` in ${dim(view.dir)}`}\n`);
415
+ for (const file of files) {
416
+ const when = file.createdAt == null ? "" : new Date(file.createdAt).toISOString().replace("T", " ").slice(0, 16);
417
+ process.stdout.write(` ${file.name.padEnd(36)} ${human(file.sizeBytes).padStart(8)} ${dim(when)}${file.automatic ? dim(" auto") : ""}\n`);
418
+ }
419
+ }
420
+ /**
421
+ * Name the entries still running, without blocking.
422
+ *
423
+ * A **persistent** entry keeps running while the panel is stopped, so "panel off" is not "services
424
+ * off" — and its data being captured mid-write is worth knowing before it is relied on. Warned rather
425
+ * than refused: the user may know, and the panel's own backup has always proceeded here.
426
+ */
427
+ function warnRunning(entries) {
428
+ if (entries.length === 0) return;
429
+ const named = entries.map((entry) => entry.serverId ?? entry.id ?? "").filter((name) => name.length > 0);
430
+ const isOne = named.length === 1;
431
+ process.stdout.write(`${dim(`! ${named.length} entr${isOne ? "y is" : "ies are"} still running (${named.join(", ")}) — its data may be captured mid-write`)}\n`);
432
+ }
433
+ async function runBackupCreate(options) {
434
+ const scope = options.scope;
435
+ const online = await usesPanel();
436
+ const entries = await (async () => {
437
+ if (online) {
438
+ const runtime = await livePanel();
439
+ if (runtime !== null) {
440
+ const answer = await runtime.request(runtime, "/_hh/backups", 12e4);
441
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
442
+ if (answer.status !== 200) refusal(answer);
443
+ return answer.body?.entries ?? [];
444
+ }
445
+ }
446
+ const { service } = await offlineBackup();
447
+ await service.warm();
448
+ return service.selection().entries;
449
+ })();
450
+ assertKnown(options.exclude, entries, "--exclude", "create");
451
+ assertKnown(scope.kind === "include" ? scope.ids : void 0, entries, "--include", "create");
452
+ const wanted = filterEntries(entries, scope, options.exclude);
453
+ if (!options.confirm) {
454
+ if (options.json) {
455
+ process.stdout.write(`${JSON.stringify({
456
+ action: "create",
457
+ apply: false,
458
+ entries: wanted
459
+ }, null, 2)}\n`);
460
+ return;
461
+ }
462
+ process.stdout.write(`${bold("Plan")} — what a backup would capture; nothing has been written yet\n`);
463
+ printPlanTree(flattenRows(wanted));
464
+ if (wanted.length === 0) {
465
+ process.stdout.write(" (nothing matched — check --include, or what the entries declare)\n");
466
+ return;
467
+ }
468
+ warnRunning(await runningEntries());
469
+ if (!await consent("Take this backup?")) return;
470
+ }
471
+ const include = scope.kind === "include" ? scope.ids : void 0;
472
+ const exclude = options.exclude;
473
+ const file = (await (async () => {
474
+ if (online) {
475
+ const runtime = await livePanel();
476
+ if (runtime !== null) {
477
+ const query = new URLSearchParams();
478
+ if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
479
+ if (include !== void 0) query.set("include", include.join(","));
480
+ if (exclude !== void 0) query.set("exclude", exclude.join(","));
481
+ const answer = await runtime.request(runtime, `/_hh/backups${withParam(suffixOf(query), "confirm", "true")}`, 6e5);
482
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
483
+ if (answer.status !== 200) refusal(answer);
484
+ return answer.body;
485
+ }
486
+ }
487
+ const { service } = await offlineBackup();
488
+ await service.warm();
489
+ const result = await service.create({
490
+ password: options.password,
491
+ include,
492
+ exclude
493
+ });
494
+ if (!result.ok) fail(result.error ?? "the backup failed");
495
+ return { file: result.file };
496
+ })())?.file;
497
+ if (file === void 0) fail("the backup reported success but named no archive");
498
+ if (options.json) {
499
+ process.stdout.write(`${JSON.stringify({
500
+ action: "create",
501
+ apply: true,
502
+ file
503
+ }, null, 2)}\n`);
504
+ return;
505
+ }
506
+ process.stdout.write(`${green("backup created")} ${file.name} ${dim(`(${human(file.sizeBytes)})`)}\n`);
507
+ }
508
+ /**
509
+ * The entries running right now.
510
+ *
511
+ * Read from the state files in **both** cases: the panel's own backup view has no per-entry running
512
+ * flag to read, and the state files are the same witness the panel's supervisor would give — a
513
+ * persistent entry keeps its nanny alive and rewrites that file whether or not the panel is up.
514
+ */
515
+ async function runningEntries() {
516
+ return (await offlineBackup()).runningNow();
517
+ }
518
+ /**
519
+ * Why a restore plan is not something to apply, or `null`.
520
+ *
521
+ * The service answers a plan for every archive, including ones it refuses to read: `error` carries
522
+ * the refusal and `items` is empty. A caller that reads only `items` sees a tidy empty restore — and
523
+ * on a blank host, `restored 0 items` printed with exit 0 is the worst possible answer, because
524
+ * nothing distinguishes "this archive was empty" from "this archive could not be opened".
525
+ *
526
+ * `needsPassword` is its own case: it is the one refusal the person can fix from the same command.
527
+ */
528
+ function planRefusal(plan) {
529
+ if (plan === null) return null;
530
+ if (plan.needsPassword === true) return `${plan.error ?? "this backup is password-protected"} — add \`--password <text>\` to unlock it`;
531
+ if (plan.error !== void 0 && plan.error.length > 0) return plan.error;
532
+ return null;
533
+ }
534
+ /**
535
+ * A restore's per-item skips, as lines a person can act on.
536
+ *
537
+ * `skipped` is the same list the UI draws, and it is the only thing that says a piece of an
538
+ * otherwise successful restore was left behind — an unreadable `servers.config.json`, a data path
539
+ * whose declaration changed, a dump staged for an entry with no `load` hook. Printing only the
540
+ * applied count reported such a restore as complete.
541
+ *
542
+ * Read from the outcome of the run that is being reported: the plan and the apply answer different
543
+ * lists, because a skip such as a missing load hook is only known once the files have landed.
544
+ */
545
+ function restoreNotes(outcome) {
546
+ return outcome?.skipped ?? [];
547
+ }
548
+ async function runBackupRestore(options) {
549
+ const scope = options.scope;
550
+ const online = await usesPanel();
551
+ /**
552
+ * What this restore reads from: an archive **name** in the backups directory, or a **path**.
553
+ *
554
+ * A name is an allowlist entry, which is why it is the default. `--from` is for the blank host
555
+ * where the archive is on a USB stick: it names the file to read, not a directory to write in.
556
+ * The two are refused together rather than one quietly winning — on the one command that
557
+ * overwrites live data, a guess about which archive was meant is the wrong default.
558
+ *
559
+ * The path is resolved against *this* process's directory; the panel would resolve a relative
560
+ * one against its own cwd, which is a different directory and so a different file.
561
+ */
562
+ const source = options.from !== void 0 ? {
563
+ kind: "from",
564
+ path: resolveUserPath(options.from)
565
+ } : {
566
+ kind: "name",
567
+ name: options.name ?? ""
568
+ };
569
+ /** What to call it in the plan and the result: the file it read, name or path. */
570
+ const label = source.kind === "from" ? path.basename(source.path) : source.name;
571
+ if (source.kind === "from" && (!fs.existsSync(source.path) || !fs.statSync(source.path).isFile())) fail(`no file at ${source.path} — \`--from\` takes the path to an archive on this machine`);
572
+ const service = online ? null : (await offlineBackup()).service;
573
+ if (service !== null) await service.warm();
574
+ const plan = await (async () => {
575
+ if (service !== null) {
576
+ if (source.kind === "from") return await service.restore(source.path, {
577
+ confirm: false,
578
+ password: options.password,
579
+ include: scope.kind === "include" ? scope.ids : void 0,
580
+ exclude: options.exclude
581
+ });
582
+ const archive = service.resolve(source.name);
583
+ if (archive === null) fail(`no backup named "${source.name}" in ${service.directory} — a restore takes the archive's file name, not a path; pass --from <path> to read the file where it is, or copy it into that directory (\`${invocation()} backup list\` shows what is there)`);
584
+ return await service.restore(archive, {
585
+ confirm: false,
586
+ password: options.password,
587
+ include: scope.kind === "include" ? scope.ids : void 0,
588
+ exclude: options.exclude
589
+ });
590
+ }
591
+ const runtime = await livePanel();
592
+ if (runtime === null) fail(`the control panel is not answering — try again once it is up`);
593
+ const base = restoreQuery(source, options, scope);
594
+ const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
595
+ if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
596
+ if (answer.status !== 200) refusal(answer);
597
+ return answer.body;
598
+ })();
599
+ const refused = planRefusal(plan);
600
+ if (refused !== null) {
601
+ if (options.json) process.stdout.write(`${JSON.stringify({
602
+ action: "restore",
603
+ apply: false,
604
+ name: label,
605
+ error: refused
606
+ }, null, 2)}\n`);
607
+ fail(refused);
608
+ }
609
+ const items = (plan?.items ?? []).filter((item) => item.selected !== false);
610
+ const archiveItems = plan?.items ?? [];
611
+ if (options.exclude !== void 0) assertKnown(options.exclude, archiveItems, "--exclude", "restore");
612
+ if (scope.kind === "include") assertKnown(scope.ids, archiveItems, "--include", "restore");
613
+ if (options.json && !options.confirm) {
614
+ process.stdout.write(`${JSON.stringify({
615
+ action: "restore",
616
+ apply: false,
617
+ name: label,
618
+ items,
619
+ skipped: restoreNotes(plan)
620
+ }, null, 2)}\n`);
621
+ return;
622
+ }
623
+ if (!options.json) {
624
+ process.stdout.write(options.confirm ? `${bold("Plan")} for ${label} — applying it now\n` : `${bold("Plan")} for ${label} — nothing has been written yet\n`);
625
+ printPlanTree(items.map((item) => ({
626
+ id: item.id,
627
+ note: item.note ?? null
628
+ })));
629
+ if (!options.confirm) for (const note of restoreNotes(plan)) process.stdout.write(` ${dim("!")} ${note}\n`);
630
+ if (items.length === 0) {
631
+ process.stdout.write(" (nothing to restore — check --include, or what this host declares)\n");
632
+ return;
633
+ }
634
+ }
635
+ if (!options.confirm && !await consent(`Restore these ${items.length} item(s) over this host?`)) return;
636
+ {
637
+ const outcome = await (async () => {
638
+ if (service !== null) {
639
+ const archive = source.kind === "from" ? source.path : service.resolve(source.name);
640
+ const result = await service.restore(archive, {
641
+ confirm: true,
642
+ password: options.password,
643
+ include: scope.kind === "include" ? scope.ids : void 0,
644
+ exclude: options.exclude
645
+ });
646
+ return {
647
+ ...result,
648
+ items: (result.items ?? []).filter((item) => item.selected !== false)
649
+ };
650
+ }
651
+ const runtime = await livePanel();
652
+ if (runtime === null) fail("the control panel stopped answering — nothing further was written");
653
+ const base = restoreQuery(source, options, scope);
654
+ const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
655
+ if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
656
+ if (answer.status !== 200) refusal(answer);
657
+ const result = answer.body;
658
+ return {
659
+ ...result,
660
+ items: (result?.items ?? plan?.items ?? []).filter((item) => item.selected !== false),
661
+ ...result?.hooks === void 0 && plan?.hooks !== void 0 ? { hooks: plan.hooks } : {}
662
+ };
663
+ })();
664
+ const applyRefused = planRefusal(outcome);
665
+ if (applyRefused !== null) {
666
+ if (options.json) process.stdout.write(`${JSON.stringify({
667
+ action: "restore",
668
+ apply: true,
669
+ name: label,
670
+ error: applyRefused
671
+ }, null, 2)}\n`);
672
+ fail(applyRefused);
673
+ }
674
+ const applied = (outcome.items ?? []).filter((item) => item.selected !== false);
675
+ const hooks = (outcome.hooks ?? []).filter((hook) => hook.action === "load");
676
+ const notes = restoreNotes(outcome);
677
+ if (options.json) {
678
+ process.stdout.write(`${JSON.stringify({
679
+ action: "restore",
680
+ apply: true,
681
+ name: label,
682
+ items: applied,
683
+ hooks,
684
+ skipped: notes,
685
+ ...outcome.restartRequired === true ? { restartRequired: true } : {},
686
+ ...(outcome.createdWorkspaces ?? []).length === 0 ? {} : { createdWorkspaces: outcome.createdWorkspaces },
687
+ ...(outcome.replacedUnderRunning ?? []).length === 0 ? {} : { replacedUnderRunning: outcome.replacedUnderRunning }
688
+ }, null, 2)}\n`);
689
+ return;
690
+ }
691
+ if (applied.length === 0) process.stdout.write(`${green("restored")} nothing — the archive carried no item this host can take\n`);
692
+ else process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${label}\n`);
693
+ for (const hook of hooks) process.stdout.write(` ${dim(`load ${hook.serverId}: ${hook.output ?? "staged"}`)}\n`);
694
+ for (const note of notes) process.stdout.write(` ${dim("!")} ${note}\n`);
695
+ if (outcome.restartRequired === true) process.stdout.write(` ${dim(`! the panel's listener changed — restart it so it binds where the archive says (\`${invocation()} restart\`)`)}\n`);
696
+ if ((outcome.createdWorkspaces ?? []).length > 0) process.stdout.write(` ${dim(`! created ${outcome.createdWorkspaces.join(", ")}, which this host did not have`)}\n`);
697
+ if (service !== null) process.stdout.write(dim(`the panel is not running, so nothing was reloaded — the next \`${invocation()} up\` reads what was restored\n`));
698
+ }
699
+ }
700
+ /**
701
+ * The restore query both the plan and the apply send.
702
+ *
703
+ * One builder, because the two requests must agree: a password or a selection on the plan and not on
704
+ * the apply made the apply answer about different items than the person approved.
705
+ */
706
+ function restoreQuery(source, options, scope) {
707
+ const base = source.kind === "from" ? new URLSearchParams({ from: source.path }) : new URLSearchParams({ name: source.name });
708
+ if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
709
+ if (scope.kind === "include") base.set("include", scope.ids.join(","));
710
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
711
+ return base;
712
+ }
713
+ var backupCommand = defineCommand({
714
+ meta: { name: "backup" },
715
+ args: {
716
+ action: {
717
+ type: "positional",
718
+ description: "list (default) | create | restore",
719
+ required: false
720
+ },
721
+ target: {
722
+ type: "positional",
723
+ description: "the archive name, for restore",
724
+ required: false
725
+ },
726
+ from: {
727
+ type: "string",
728
+ description: "restore from this archive file anywhere on the machine, instead of a name in the backups directory"
729
+ },
730
+ password: {
731
+ type: "string",
732
+ description: "encrypt the archive, or unlock it on restore"
733
+ },
734
+ include: {
735
+ type: "string",
736
+ description: "comma-separated item ids to act on"
737
+ },
738
+ exclude: {
739
+ type: "string",
740
+ description: "comma-separated item ids to leave out, applied after --include"
741
+ },
742
+ all: {
743
+ type: "boolean",
744
+ description: "act on everything, rather than naming ids"
745
+ },
746
+ confirm: {
747
+ type: "boolean",
748
+ description: "apply without asking (a restore writes over live data)"
749
+ },
750
+ json: {
751
+ type: "boolean",
752
+ description: "print the plan or the result as JSON"
753
+ }
754
+ },
755
+ async run({ args }) {
756
+ try {
757
+ const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
758
+ const parsed = action === "create" || action === "restore" ? parseScope(args.all === true, args.include) : null;
759
+ const exclude = action === "create" || action === "restore" ? parseExclude(args.exclude) : void 0;
760
+ if (action !== "restore" && args.from !== void 0 && args.from.length > 0) fail(`--from is for restore — \`${invocation()} backup ${action}\` takes none`);
761
+ if (action === "list") await runBackupList(args.json === true);
762
+ else if (action === "create") {
763
+ const scope = parsed ?? await refuseWithoutScope("create", "");
764
+ await runBackupCreate({
765
+ password: args.password,
766
+ scope,
767
+ exclude,
768
+ confirm: args.confirm === true,
769
+ json: args.json === true
770
+ });
771
+ } else if (action === "restore") {
772
+ const from = args.from !== void 0 && args.from.length > 0 ? args.from : void 0;
773
+ const name = args.target !== void 0 && args.target.length > 0 ? args.target : void 0;
774
+ if (from !== void 0 && name !== void 0) fail("pass an archive name or --from <path>, not both — they name two different archives");
775
+ if (from === void 0 && name === void 0) fail("restore needs an archive — a name (`backup list` shows them), or --from <path> for a file anywhere on this machine");
776
+ const suffix = from !== void 0 ? `?from=${encodeURIComponent(resolveUserPath(from))}` : `?name=${encodeURIComponent(name)}`;
777
+ if (from !== void 0 && parsed === null && !(fs.existsSync(resolveUserPath(from)) && fs.statSync(resolveUserPath(from)).isFile())) fail(`no file at ${resolveUserPath(from)} — \`--from\` takes the path to an archive on this machine`);
778
+ const scope = parsed ?? await refuseWithoutScope("restore", suffix);
779
+ await runBackupRestore({
780
+ ...name === void 0 ? {} : { name },
781
+ ...from === void 0 ? {} : { from },
782
+ password: args.password,
783
+ scope,
784
+ exclude,
785
+ confirm: args.confirm === true,
786
+ json: args.json === true
787
+ });
788
+ } else fail(`unknown action "${action}" — use list, create or restore`);
789
+ } catch (error) {
790
+ fail(errorMessage(error));
791
+ }
792
+ }
793
+ });
794
+ //#endregion
795
+ export { backupCommand };
796
+
797
+ //# sourceMappingURL=backup-CPrJVPJI.js.map