@geekmidas/cli 10.0.0-alpha.6 → 10.0.0-alpha.61

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 (303) hide show
  1. package/README.md +225 -268
  2. package/bin/adjacent-tsconfig.mjs +97 -0
  3. package/bin/gkm.mjs +16 -2
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/{HostingerProvider-h3EbEp-Z.cjs → HostingerProvider-CgDaD8VR.cjs} +21 -22
  7. package/dist/HostingerProvider-CgDaD8VR.cjs.map +1 -0
  8. package/dist/{HostingerProvider-Cft7lEYr.mjs → HostingerProvider-DI_Pr2VE.mjs} +20 -21
  9. package/dist/HostingerProvider-DI_Pr2VE.mjs.map +1 -0
  10. package/dist/LegacyStateStore-C7vFAxbu.mjs +89 -0
  11. package/dist/LegacyStateStore-C7vFAxbu.mjs.map +1 -0
  12. package/dist/LegacyStateStore-JbBVFp_2.cjs +89 -0
  13. package/dist/LegacyStateStore-JbBVFp_2.cjs.map +1 -0
  14. package/dist/LocalStateStore-DHj_-CQB.cjs +176 -0
  15. package/dist/LocalStateStore-DHj_-CQB.cjs.map +1 -0
  16. package/dist/LocalStateStore-DfUwQsL8.mjs +165 -0
  17. package/dist/LocalStateStore-DfUwQsL8.mjs.map +1 -0
  18. package/dist/{openapi-D-dx9Akj.cjs → OpenApiTsGenerator-BSrgw7B0.cjs} +360 -470
  19. package/dist/OpenApiTsGenerator-BSrgw7B0.cjs.map +1 -0
  20. package/dist/{openapi-Bw8DWFWz.mjs → OpenApiTsGenerator-q5B0z8Xg.mjs} +325 -404
  21. package/dist/OpenApiTsGenerator-q5B0z8Xg.mjs.map +1 -0
  22. package/dist/{Route53Provider-RdpUDJQk.mjs → Route53Provider-Cvj40A8I.mjs} +12 -12
  23. package/dist/Route53Provider-Cvj40A8I.mjs.map +1 -0
  24. package/dist/{Route53Provider-di2fMM5N.cjs → Route53Provider-DVILBsvV.cjs} +20 -21
  25. package/dist/Route53Provider-DVILBsvV.cjs.map +1 -0
  26. package/dist/S3StateStore-Dq6hHtzY.mjs +161 -0
  27. package/dist/S3StateStore-Dq6hHtzY.mjs.map +1 -0
  28. package/dist/S3StateStore-xqnpUrzy.cjs +160 -0
  29. package/dist/S3StateStore-xqnpUrzy.cjs.map +1 -0
  30. package/dist/SSMStateStore-5dBRwVlJ.cjs +153 -0
  31. package/dist/SSMStateStore-5dBRwVlJ.cjs.map +1 -0
  32. package/dist/SSMStateStore-SUmvAbLi.mjs +154 -0
  33. package/dist/SSMStateStore-SUmvAbLi.mjs.map +1 -0
  34. package/dist/appPorts-C9z9Pzn9.mjs +223 -0
  35. package/dist/appPorts-C9z9Pzn9.mjs.map +1 -0
  36. package/dist/appPorts-Cu79hJF6.cjs +264 -0
  37. package/dist/appPorts-Cu79hJF6.cjs.map +1 -0
  38. package/dist/aws-DkHdTV-p.cjs +61 -0
  39. package/dist/aws-DkHdTV-p.cjs.map +1 -0
  40. package/dist/aws-DojzQnLd.mjs +61 -0
  41. package/dist/aws-DojzQnLd.mjs.map +1 -0
  42. package/dist/{backup-provisioner-BrsHwYG0.cjs → backup-provisioner-BmhIO_Yr.cjs} +21 -19
  43. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +1 -0
  44. package/dist/{backup-provisioner-Bgj5Vi_L.mjs → backup-provisioner-DIVCbfee.mjs} +10 -7
  45. package/dist/backup-provisioner-DIVCbfee.mjs.map +1 -0
  46. package/dist/{bundler-Be8Zg4Wd.mjs → bundler-B5VsKW-_.mjs} +18 -29
  47. package/dist/bundler-B5VsKW-_.mjs.map +1 -0
  48. package/dist/{bundler-BY1OmV1e.cjs → bundler-DXATpO1T.cjs} +20 -32
  49. package/dist/bundler-DXATpO1T.cjs.map +1 -0
  50. package/dist/cli-DEA_J3Sa.mjs +69 -0
  51. package/dist/cli-DEA_J3Sa.mjs.map +1 -0
  52. package/dist/cli-DQdrVkj2.cjs +69 -0
  53. package/dist/cli-DQdrVkj2.cjs.map +1 -0
  54. package/dist/{config-CxP7P-qG.mjs → config-C5-EEdmr.mjs} +144 -127
  55. package/dist/config-C5-EEdmr.mjs.map +1 -0
  56. package/dist/{config-CNz5KaSR.cjs → config-DXnkCEq0.cjs} +212 -184
  57. package/dist/config-DXnkCEq0.cjs.map +1 -0
  58. package/dist/config.cjs +9 -6
  59. package/dist/config.d.cts +124 -33
  60. package/dist/config.d.cts.map +1 -1
  61. package/dist/config.d.mts +124 -33
  62. package/dist/config.d.mts.map +1 -1
  63. package/dist/config.mjs +3 -5
  64. package/dist/deploy/public.cjs +22 -0
  65. package/dist/deploy/public.d.cts +459 -0
  66. package/dist/deploy/public.d.cts.map +1 -0
  67. package/dist/deploy/public.d.mts +459 -0
  68. package/dist/deploy/public.d.mts.map +1 -0
  69. package/dist/deploy/public.mjs +5 -0
  70. package/dist/deploy/sniffer-envkit-patch.cjs +18 -10
  71. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  72. package/dist/deploy/sniffer-envkit-patch.d.cts +0 -2
  73. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  74. package/dist/deploy/sniffer-envkit-patch.d.mts +0 -2
  75. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  76. package/dist/deploy/sniffer-envkit-patch.mjs +10 -2
  77. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  78. package/dist/deploy/sniffer-hooks.cjs +13 -7
  79. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  80. package/dist/deploy/sniffer-hooks.d.cts +1 -2
  81. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  82. package/dist/deploy/sniffer-hooks.d.mts +1 -2
  83. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  84. package/dist/deploy/sniffer-hooks.mjs +10 -3
  85. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  86. package/dist/deploy/sniffer-loader.cjs +16 -7
  87. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  88. package/dist/deploy/sniffer-loader.d.cts +1 -1
  89. package/dist/deploy/sniffer-loader.d.mts +1 -1
  90. package/dist/deploy/sniffer-loader.mjs +14 -3
  91. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  92. package/dist/deploy/sniffer-routes-worker.cjs +11 -11
  93. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  94. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  95. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  96. package/dist/deploy/sniffer-routes-worker.mjs +3 -3
  97. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  98. package/dist/deploy/sniffer-worker.cjs +15 -6
  99. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  100. package/dist/deploy/sniffer-worker.d.cts +1 -3
  101. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  102. package/dist/deploy/sniffer-worker.d.mts +1 -3
  103. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  104. package/dist/deploy/sniffer-worker.mjs +15 -4
  105. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  106. package/dist/deploy-BJcLmVTc.mjs +3282 -0
  107. package/dist/deploy-BJcLmVTc.mjs.map +1 -0
  108. package/dist/deploy-BbJdgQ2b.cjs +3365 -0
  109. package/dist/deploy-BbJdgQ2b.cjs.map +1 -0
  110. package/dist/{discover-DTmFeloL.cjs → discover-Bc-4eA_p.cjs} +131 -103
  111. package/dist/discover-Bc-4eA_p.cjs.map +1 -0
  112. package/dist/{discover-CAlFgYec.mjs → discover-FrYvzkeC.mjs} +91 -58
  113. package/dist/discover-FrYvzkeC.mjs.map +1 -0
  114. package/dist/{emit-CiZS_5Ub.mjs → emit-C1e8qD08.mjs} +13 -26
  115. package/dist/emit-C1e8qD08.mjs.map +1 -0
  116. package/dist/{emit-CbcRolsa.cjs → emit-Dmc1nvdS.cjs} +31 -57
  117. package/dist/emit-Dmc1nvdS.cjs.map +1 -0
  118. package/dist/encryption-DaA9gRXr.mjs +90 -0
  119. package/dist/encryption-DaA9gRXr.mjs.map +1 -0
  120. package/dist/encryption-ojzUo7-z.cjs +91 -0
  121. package/dist/encryption-ojzUo7-z.cjs.map +1 -0
  122. package/dist/fakes-C9RiT6XG.mjs +125 -0
  123. package/dist/fakes-C9RiT6XG.mjs.map +1 -0
  124. package/dist/fakes-zW-jNAbQ.cjs +148 -0
  125. package/dist/fakes-zW-jNAbQ.cjs.map +1 -0
  126. package/dist/github-Cq57poPj.cjs +213 -0
  127. package/dist/github-Cq57poPj.cjs.map +1 -0
  128. package/dist/github-DmCj2u95.mjs +213 -0
  129. package/dist/github-DmCj2u95.mjs.map +1 -0
  130. package/dist/home-DOzBaWaL.cjs +33 -0
  131. package/dist/home-DOzBaWaL.cjs.map +1 -0
  132. package/dist/home-GI7pJl1M.mjs +22 -0
  133. package/dist/home-GI7pJl1M.mjs.map +1 -0
  134. package/dist/{index-DEbaleny.d.mts → index-Da1-oa9W.d.mts} +4 -23
  135. package/dist/index-Da1-oa9W.d.mts.map +1 -0
  136. package/dist/{index-BGGdjueF.d.cts → index-UiWCaGzU.d.cts} +4 -23
  137. package/dist/index-UiWCaGzU.d.cts.map +1 -0
  138. package/dist/index.cjs +10712 -12248
  139. package/dist/index.cjs.map +1 -1
  140. package/dist/index.d.cts +1 -1
  141. package/dist/index.d.mts +1 -1
  142. package/dist/index.mjs +10480 -12040
  143. package/dist/index.mjs.map +1 -1
  144. package/dist/migrate-5_J5JySj.mjs +265 -0
  145. package/dist/migrate-5_J5JySj.mjs.map +1 -0
  146. package/dist/migrate-BScRpCEx.cjs +270 -0
  147. package/dist/migrate-BScRpCEx.cjs.map +1 -0
  148. package/dist/openapi.cjs +198 -10
  149. package/dist/openapi.cjs.map +1 -0
  150. package/dist/openapi.d.cts +21 -19
  151. package/dist/openapi.d.cts.map +1 -1
  152. package/dist/openapi.d.mts +21 -19
  153. package/dist/openapi.d.mts.map +1 -1
  154. package/dist/openapi.mjs +193 -5
  155. package/dist/openapi.mjs.map +1 -0
  156. package/dist/ready-DQIy21W5.mjs +760 -0
  157. package/dist/ready-DQIy21W5.mjs.map +1 -0
  158. package/dist/ready-XlNx-Gbo.cjs +807 -0
  159. package/dist/ready-XlNx-Gbo.cjs.map +1 -0
  160. package/dist/reconcile/public.cjs +3 -5
  161. package/dist/reconcile/public.d.cts +30 -33
  162. package/dist/reconcile/public.d.cts.map +1 -1
  163. package/dist/reconcile/public.d.mts +30 -33
  164. package/dist/reconcile/public.d.mts.map +1 -1
  165. package/dist/reconcile/public.mjs +3 -4
  166. package/dist/{reconcile-CFs8C_1a.mjs → reconcile--I7V4Klj.mjs} +4 -7
  167. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  168. package/dist/{reconcile-D0pimNiy.cjs → reconcile-CuCQBa5-.cjs} +5 -8
  169. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  170. package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
  171. package/dist/{chunk-CUT6urMc.cjs → rolldown-runtime-C0BPl7ul.cjs} +23 -10
  172. package/dist/sniffer-CQmJnNJM.cjs +7115 -0
  173. package/dist/sniffer-CQmJnNJM.cjs.map +1 -0
  174. package/dist/sniffer-bdleks5l.mjs +6561 -0
  175. package/dist/sniffer-bdleks5l.mjs.map +1 -0
  176. package/dist/storage-BzaUxmqe.mjs +124 -0
  177. package/dist/storage-BzaUxmqe.mjs.map +1 -0
  178. package/dist/storage-CSGoC3bK.cjs +152 -0
  179. package/dist/storage-CSGoC3bK.cjs.map +1 -0
  180. package/dist/store-BS8A7NcA.mjs +415 -0
  181. package/dist/store-BS8A7NcA.mjs.map +1 -0
  182. package/dist/store-KvNQwYaB.cjs +510 -0
  183. package/dist/store-KvNQwYaB.cjs.map +1 -0
  184. package/dist/types-Bp1mVxG0.d.mts +6410 -0
  185. package/dist/types-Bp1mVxG0.d.mts.map +1 -0
  186. package/dist/types-efNLu9xu.d.cts +6411 -0
  187. package/dist/types-efNLu9xu.d.cts.map +1 -0
  188. package/dist/vitest.cjs +65 -0
  189. package/dist/vitest.cjs.map +1 -0
  190. package/dist/vitest.d.cts +29 -0
  191. package/dist/vitest.d.cts.map +1 -0
  192. package/dist/vitest.d.mts +29 -0
  193. package/dist/vitest.d.mts.map +1 -0
  194. package/dist/vitest.mjs +65 -0
  195. package/dist/vitest.mjs.map +1 -0
  196. package/dist/workspace/index.cjs +3 -4
  197. package/dist/workspace/index.d.cts +3 -3
  198. package/dist/workspace/index.d.mts +3 -3
  199. package/dist/workspace/index.mjs +2 -3
  200. package/dist/{workspace-LKiNyaDy.cjs → workspace-B64Xk1Mb.cjs} +1070 -1118
  201. package/dist/workspace-B64Xk1Mb.cjs.map +1 -0
  202. package/dist/{workspace-DIuZx-cc.mjs → workspace-Bp1xVaOz.mjs} +901 -972
  203. package/dist/workspace-Bp1xVaOz.mjs.map +1 -0
  204. package/package.json +38 -20
  205. package/dist/CachedStateProvider-BLo7zv7S.cjs +0 -3
  206. package/dist/CachedStateProvider-BxoAm-B2.mjs +0 -3
  207. package/dist/CachedStateProvider-CqPdW7CB.cjs +0 -60
  208. package/dist/CachedStateProvider-CqPdW7CB.cjs.map +0 -1
  209. package/dist/CachedStateProvider-DTniehMP.mjs +0 -54
  210. package/dist/CachedStateProvider-DTniehMP.mjs.map +0 -1
  211. package/dist/HostingerProvider-Cft7lEYr.mjs.map +0 -1
  212. package/dist/HostingerProvider-h3EbEp-Z.cjs.map +0 -1
  213. package/dist/LocalStateProvider-Bn6tS-oL.mjs +0 -42
  214. package/dist/LocalStateProvider-Bn6tS-oL.mjs.map +0 -1
  215. package/dist/LocalStateProvider-Db9SEjyH.cjs +0 -43
  216. package/dist/LocalStateProvider-Db9SEjyH.cjs.map +0 -1
  217. package/dist/Route53Provider-RdpUDJQk.mjs.map +0 -1
  218. package/dist/Route53Provider-di2fMM5N.cjs.map +0 -1
  219. package/dist/SSMStateProvider-BRt2py-A.mjs +0 -66
  220. package/dist/SSMStateProvider-BRt2py-A.mjs.map +0 -1
  221. package/dist/SSMStateProvider-DyX8s9HI.cjs +0 -66
  222. package/dist/SSMStateProvider-DyX8s9HI.cjs.map +0 -1
  223. package/dist/backup-provisioner-Bgj5Vi_L.mjs.map +0 -1
  224. package/dist/backup-provisioner-BrsHwYG0.cjs.map +0 -1
  225. package/dist/bundler-BY1OmV1e.cjs.map +0 -1
  226. package/dist/bundler-Be8Zg4Wd.mjs.map +0 -1
  227. package/dist/chunk-Duj1WY3L.mjs +0 -7
  228. package/dist/config-CNz5KaSR.cjs.map +0 -1
  229. package/dist/config-CxP7P-qG.mjs.map +0 -1
  230. package/dist/credentials-B5zRHdAl.mjs +0 -141
  231. package/dist/credentials-B5zRHdAl.mjs.map +0 -1
  232. package/dist/credentials-BK3Z93MX.mjs +0 -2548
  233. package/dist/credentials-BK3Z93MX.mjs.map +0 -1
  234. package/dist/credentials-BapzjyV5.cjs +0 -195
  235. package/dist/credentials-BapzjyV5.cjs.map +0 -1
  236. package/dist/credentials-DzsXZzkx.cjs +0 -2680
  237. package/dist/credentials-DzsXZzkx.cjs.map +0 -1
  238. package/dist/discover-CAlFgYec.mjs.map +0 -1
  239. package/dist/discover-DTmFeloL.cjs.map +0 -1
  240. package/dist/dokploy-api-BS2xnJLZ.mjs +0 -3
  241. package/dist/dokploy-api-BsVH0y_s.cjs +0 -718
  242. package/dist/dokploy-api-BsVH0y_s.cjs.map +0 -1
  243. package/dist/dokploy-api-BuxDRo3l.cjs +0 -3
  244. package/dist/dokploy-api-aTFPz7_4.mjs +0 -706
  245. package/dist/dokploy-api-aTFPz7_4.mjs.map +0 -1
  246. package/dist/emit-CbcRolsa.cjs.map +0 -1
  247. package/dist/emit-CiZS_5Ub.mjs.map +0 -1
  248. package/dist/encryption-C6jaU0hE.cjs +0 -54
  249. package/dist/encryption-C6jaU0hE.cjs.map +0 -1
  250. package/dist/encryption-CHzzeR8a.cjs +0 -4
  251. package/dist/encryption-CQUncu7v.mjs +0 -3
  252. package/dist/encryption-D-abyhZx.mjs +0 -42
  253. package/dist/encryption-D-abyhZx.mjs.map +0 -1
  254. package/dist/fullstack-secrets-C-GGohke.cjs +0 -111
  255. package/dist/fullstack-secrets-C-GGohke.cjs.map +0 -1
  256. package/dist/fullstack-secrets-D1o9-G5l.mjs +0 -87
  257. package/dist/fullstack-secrets-D1o9-G5l.mjs.map +0 -1
  258. package/dist/generator-CNzBw7g5.cjs +0 -289
  259. package/dist/generator-CNzBw7g5.cjs.map +0 -1
  260. package/dist/generator-VE2JrFlY.mjs +0 -253
  261. package/dist/generator-VE2JrFlY.mjs.map +0 -1
  262. package/dist/index-BGGdjueF.d.cts.map +0 -1
  263. package/dist/index-DEbaleny.d.mts.map +0 -1
  264. package/dist/openapi-Bw8DWFWz.mjs.map +0 -1
  265. package/dist/openapi-D-dx9Akj.cjs.map +0 -1
  266. package/dist/openapi-react-query-Byltvm_7.mjs +0 -167
  267. package/dist/openapi-react-query-Byltvm_7.mjs.map +0 -1
  268. package/dist/openapi-react-query-CmJ1xDbn.cjs +0 -173
  269. package/dist/openapi-react-query-CmJ1xDbn.cjs.map +0 -1
  270. package/dist/openapi-react-query.cjs +0 -4
  271. package/dist/openapi-react-query.d.cts +0 -11
  272. package/dist/openapi-react-query.d.cts.map +0 -1
  273. package/dist/openapi-react-query.d.mts +0 -11
  274. package/dist/openapi-react-query.d.mts.map +0 -1
  275. package/dist/openapi-react-query.mjs +0 -4
  276. package/dist/reconcile-CFs8C_1a.mjs.map +0 -1
  277. package/dist/reconcile-D0pimNiy.cjs.map +0 -1
  278. package/dist/setup-8IWPsRIN.cjs +0 -11
  279. package/dist/setup-BWMhbW-p.mjs +0 -443
  280. package/dist/setup-BWMhbW-p.mjs.map +0 -1
  281. package/dist/setup-D7L4BgBT.cjs +0 -473
  282. package/dist/setup-D7L4BgBT.cjs.map +0 -1
  283. package/dist/setup-DGIPd2fh.mjs +0 -11
  284. package/dist/storage-BJmzYxt8.cjs +0 -363
  285. package/dist/storage-BJmzYxt8.cjs.map +0 -1
  286. package/dist/storage-BM9hGpgv.cjs +0 -7
  287. package/dist/storage-Bi24WfoW.mjs +0 -297
  288. package/dist/storage-Bi24WfoW.mjs.map +0 -1
  289. package/dist/storage-CYlGwWTj.mjs +0 -3
  290. package/dist/sync-CmEuNZsB.mjs +0 -76
  291. package/dist/sync-CmEuNZsB.mjs.map +0 -1
  292. package/dist/sync-D306yOWu.cjs +0 -4
  293. package/dist/sync-SizaChmC.cjs +0 -93
  294. package/dist/sync-SizaChmC.cjs.map +0 -1
  295. package/dist/sync-hOqAWHR6.mjs +0 -3
  296. package/dist/types-BLSNdrk0.d.cts +0 -2176
  297. package/dist/types-BLSNdrk0.d.cts.map +0 -1
  298. package/dist/types-C3POXhw3.d.mts +0 -2176
  299. package/dist/types-C3POXhw3.d.mts.map +0 -1
  300. package/dist/workspace-CGaUAw5A.cjs +0 -9
  301. package/dist/workspace-CnTqIlB3.mjs +0 -8
  302. package/dist/workspace-DIuZx-cc.mjs.map +0 -1
  303. package/dist/workspace-LKiNyaDy.cjs.map +0 -1
@@ -0,0 +1,3365 @@
1
+ const require_sniffer = require("./sniffer-CQmJnNJM.cjs");
2
+ const require_home = require("./home-DOzBaWaL.cjs");
3
+ const require_discover = require("./discover-Bc-4eA_p.cjs");
4
+ const require_config = require("./config-DXnkCEq0.cjs");
5
+ const require_workspace = require("./workspace-B64Xk1Mb.cjs");
6
+ const require_storage = require("./storage-CSGoC3bK.cjs");
7
+ const require_store = require("./store-KvNQwYaB.cjs");
8
+ let node_path = require("node:path");
9
+ let node_fs_promises = require("node:fs/promises");
10
+ let node_os = require("node:os");
11
+ let _geekmidas_manifest = require("@geekmidas/manifest");
12
+ let node_crypto = require("node:crypto");
13
+ let _geekmidas_db_pg_roles = require("@geekmidas/db/pg/roles");
14
+ let pg = require("pg");
15
+ let _geekmidas_cache_postgres = require("@geekmidas/cache/postgres");
16
+ let node_dns_promises = require("node:dns/promises");
17
+ //#region src/deploy/credentials.ts
18
+ /**
19
+ * How a deploy gets the credentials it acts with.
20
+ *
21
+ * `deploy()` never prompts and never reads a terminal: it asks a
22
+ * `CredentialProvider` and, when the provider has nothing, stops with
23
+ * `MissingCredential` naming what it needed and how to supply it. Whether to
24
+ * ask a person, read a vault or fail is the caller's decision — `gkm deploy`
25
+ * prompts at a terminal and stores what was typed; a CI job sets the
26
+ * environment; a host passes its own provider.
27
+ */
28
+ /** How to supply each kind, for the error that says it is missing. */
29
+ const HOW_TO_PROVIDE = {
30
+ dokploy: "Set DOKPLOY_API_TOKEN (and DOKPLOY_ENDPOINT, or deploy.dokploy.endpoint in gkm.config.ts), run `gkm login --provider dokploy`, or pass them through the deploy's CredentialProvider.",
31
+ registry: "Add the registry in Dokploy (Settings → Docker Registry) and set deploy.dokploy.registryId, set DOCKER_REGISTRY_USERNAME and DOCKER_REGISTRY_PASSWORD, or run `gkm deploy` at a terminal to be asked for them."
32
+ };
33
+ /** A deploy needed a credential, and its provider had none. */
34
+ var MissingCredential = class extends Error {
35
+ kind;
36
+ target;
37
+ howToProvide;
38
+ constructor(kind, target, howToProvide = HOW_TO_PROVIDE[kind]) {
39
+ const what = kind === "dokploy" ? `No Dokploy credentials${target ? ` for ${target}` : ""}.` : `Dokploy has no registry for ${target ?? "the configured registry"}, and there are no credentials to create one with.`;
40
+ super(`${what} ${howToProvide}`);
41
+ this.kind = kind;
42
+ this.target = target;
43
+ this.howToProvide = howToProvide;
44
+ this.name = "MissingCredential";
45
+ }
46
+ };
47
+ /** Whatever was asked for, from the first provider that has it. */
48
+ function chainCredentials(...providers) {
49
+ return { async get(request, options) {
50
+ for (const provider of providers) {
51
+ const found = await provider.get(request, options);
52
+ if (found) return found;
53
+ }
54
+ } };
55
+ }
56
+ /**
57
+ * Credentials from the environment, then from what `gkm login` stored. What
58
+ * `deploy()` uses when it is handed no provider.
59
+ *
60
+ * - Dokploy: `DOKPLOY_API_TOKEN` / `DOKPLOY_ENDPOINT`, each falling back to
61
+ * the stored login, and the endpoint finally to `deploy.dokploy.endpoint`.
62
+ * Each half is read on its own: a token is a secret and belongs in the
63
+ * environment, an endpoint is configuration and belongs in the config.
64
+ * - Registry: `DOCKER_REGISTRY_USERNAME` / `DOCKER_REGISTRY_PASSWORD`.
65
+ */
66
+ function storedCredentials(options = {}) {
67
+ const env = options.env ?? process.env;
68
+ return { async get(asked) {
69
+ const request = asked;
70
+ switch (request.kind) {
71
+ case "dokploy": {
72
+ const stored = (await require_sniffer.readCredentials(options.home ? { home: options.home } : void 0)).dokploy;
73
+ const token = env.DOKPLOY_API_TOKEN ?? stored?.token;
74
+ const endpoint = env.DOKPLOY_ENDPOINT ?? stored?.endpoint ?? request.endpoint;
75
+ if (!token || !endpoint) return void 0;
76
+ return {
77
+ endpoint: endpoint.replace(/\/$/, ""),
78
+ token
79
+ };
80
+ }
81
+ case "registry": {
82
+ const username = env.DOCKER_REGISTRY_USERNAME;
83
+ const password = env.DOCKER_REGISTRY_PASSWORD;
84
+ if (!username || !password) return void 0;
85
+ return {
86
+ username,
87
+ password
88
+ };
89
+ }
90
+ }
91
+ } };
92
+ }
93
+ //#endregion
94
+ //#region src/deploy/events.ts
95
+ /** An error as an event carries it: its name and message, nothing else. */
96
+ function eventError(error) {
97
+ if (error instanceof Error) return {
98
+ name: error.name,
99
+ message: error.message
100
+ };
101
+ return {
102
+ name: "Error",
103
+ message: String(error)
104
+ };
105
+ }
106
+ //#endregion
107
+ //#region src/deploy/fromManifest.ts
108
+ /**
109
+ * The Dokploy target, read off the construct manifest.
110
+ *
111
+ * The AWS target has done this since `fromManifest` landed: a table keyed by
112
+ * declaration kind, each entry turning one declaration into infrastructure and
113
+ * the env keys it resolves. Dokploy had no such thing — it resolved environment
114
+ * from the *sniffer*, which walks application code for `get('X')` calls, and a
115
+ * construct reads its own key inside `@geekmidas/constructs` where there is
116
+ * nothing to find. So a declared app deployed here got none of the model, and
117
+ * nothing reported the absence: the deploy succeeded and the first request that
118
+ * needed a URL failed at runtime.
119
+ *
120
+ * This is the same table, over the REST wrapper instead of over Pulumi.
121
+ *
122
+ * **Two phases, and the split is not incidental.** Creating a Postgres and
123
+ * creating a role inside it are different kinds of act: the first is an API
124
+ * call, the second needs a connection to a database that does not exist yet
125
+ * when the call is made. So provisioners *accumulate* DDL rather than running
126
+ * it, and it is applied once against a cluster that is up — which is exactly
127
+ * what `DatabaseBootstrap` does on AWS, for exactly the same reason.
128
+ *
129
+ * **The DDL itself is shared.** `roleStatements` and `cacheTableStatements` are
130
+ * the same generators the local target and the AWS target use. Dokploy used to
131
+ * write its own `DO $$` block, which meant three targets applying three
132
+ * different definitions of "the role split" and no way to notice they had
133
+ * drifted.
134
+ *
135
+ * Entries are deliberately small and free of I/O ordering: each takes what it
136
+ * needs and returns what it resolved. That is what would let a Pulumi dynamic
137
+ * provider wrap one later without the table itself changing — see §6b.
138
+ */
139
+ /**
140
+ * The internal hostname a Dokploy Postgres answers on.
141
+ *
142
+ * Its own service name on the Docker network — not the server's public address.
143
+ * An app reaching its database over the public internet would be a credential
144
+ * crossing a network that did not need to see it.
145
+ */
146
+ function clusterHost(postgres) {
147
+ return postgres.appName;
148
+ }
149
+ /**
150
+ * What a resource is called in the provider.
151
+ *
152
+ * `cloudName` and nothing else — the same scoped kebab rule the AWS target
153
+ * uses, so a name reads identically on both: `production-shop-orders`.
154
+ *
155
+ * It briefly carried a `-postgres` suffix on the theory that a Dokploy project
156
+ * is one flat list where an application and its database would collide. It is
157
+ * not: `project.one` returns typed collections — `applications`, `postgres`,
158
+ * `redis`, `compose`, `mariadb`, `mongo`, `mysql` — so the kind is already in
159
+ * the shape of the response and an application and a Postgres of the same name
160
+ * are different objects with different ids. The suffix was answering a question
161
+ * nobody had asked.
162
+ */
163
+ function serviceName(scope, id) {
164
+ return (0, _geekmidas_manifest.cloudName)(scope, id);
165
+ }
166
+ const PROVISIONERS = {
167
+ /**
168
+ * A Postgres service, plus the roles that reach it.
169
+ *
170
+ * The service is `findOrCreate`, because a deploy that recreated the
171
+ * database would be a deploy that lost the data. The roles are deferred:
172
+ * they need a connection to a cluster this call has only just asked for.
173
+ */
174
+ database: async (declaration, context) => {
175
+ if (declaration.kind !== "database") throw new WrongKind(declaration.kind);
176
+ const name = require_sniffer.resourceName(declaration.id, declaration.kind, context.stage);
177
+ const { postgres } = await context.api.findOrCreatePostgres(serviceName({
178
+ stage: context.stage,
179
+ app: context.scope ?? context.project
180
+ }, declaration.id), context.projectId, context.environmentId, {
181
+ databaseName: name,
182
+ databasePassword: derivedPassword(context, `${name}:master`)
183
+ });
184
+ const host = clusterHost(postgres);
185
+ context.clusters[postgres.databaseName] = postgres;
186
+ const schema = declaration.schema ?? "app";
187
+ const runtime = name;
188
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
189
+ const reads = readsFrom(context.manifest, declaration.id);
190
+ context.deferred.push(...statementsFor({
191
+ id: declaration.id,
192
+ database: postgres.databaseName,
193
+ ownsDatabase: true,
194
+ runtime,
195
+ owner,
196
+ ...reads ? { reader: (0, _geekmidas_db_pg_roles.readerRole)(runtime) } : {},
197
+ schema,
198
+ context
199
+ }));
200
+ return { provides: {
201
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: postgresUrl(runtime, derivedPassword(context, runtime), host, postgres.databaseName),
202
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "ownerUrl")]: postgresUrl(owner, derivedPassword(context, owner), host, postgres.databaseName)
203
+ } };
204
+ },
205
+ /**
206
+ * A schema in the parent's database, with its own role and its own URL — so
207
+ * the parent's role holds no grant on these tables at all.
208
+ */
209
+ "database-schema": async (declaration, context) => {
210
+ if (declaration.kind !== "database-schema") throw new WrongKind(declaration.kind);
211
+ const parent = context.provisioned[declaration.of];
212
+ if (!parent) throw new UnresolvedParent(declaration.id, declaration.of);
213
+ const runtime = require_sniffer.resourceName(declaration.id, declaration.kind, context.stage);
214
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
215
+ const reads = readsFrom(context.manifest, declaration.id);
216
+ const parentUrl = new URL(parent.provides[(0, _geekmidas_manifest.provideKey)(declaration.of, "url")] ?? "");
217
+ context.deferred.push(...statementsFor({
218
+ id: declaration.id,
219
+ database: parentUrl.pathname.slice(1),
220
+ runtime,
221
+ owner,
222
+ ...reads ? { reader: (0, _geekmidas_db_pg_roles.readerRole)(runtime) } : {},
223
+ schema: declaration.schema,
224
+ context
225
+ }));
226
+ return { provides: {
227
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: postgresUrl(runtime, derivedPassword(context, runtime), parentUrl.hostname, parentUrl.pathname.slice(1)),
228
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "ownerUrl")]: postgresUrl(owner, derivedPassword(context, owner), parentUrl.hostname, parentUrl.pathname.slice(1))
229
+ } };
230
+ },
231
+ /**
232
+ * A read-only endpoint on the same cluster.
233
+ *
234
+ * Nothing is provisioned: a Dokploy Postgres has one endpoint, so this
235
+ * resolves to the writer's address — and that is safe rather than a
236
+ * loophole, because read-only is enforced by the reader role's grants and
237
+ * not by which host the URL names. The role itself was created with its
238
+ * parent.
239
+ */
240
+ "database-reader": async (declaration, context) => {
241
+ if (declaration.kind !== "database-reader") throw new WrongKind(declaration.kind);
242
+ const parent = context.provisioned[declaration.of];
243
+ if (!parent) throw new UnresolvedParent(declaration.id, declaration.of);
244
+ const parentUrl = new URL(parent.provides[(0, _geekmidas_manifest.provideKey)(declaration.of, "url")] ?? "");
245
+ const reader = (0, _geekmidas_db_pg_roles.readerRole)(parentUrl.username);
246
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: postgresUrl(reader, derivedPassword(context, reader), parentUrl.hostname, parentUrl.pathname.slice(1)) } };
247
+ },
248
+ /**
249
+ * A cache, wherever the project said it lives.
250
+ *
251
+ * `db` is a table in a database the manifest already declares, so it
252
+ * provisions no service and costs nothing to run — the same relationship
253
+ * pg-boss has. The table's DDL is deferred with the roles, and the table
254
+ * name travels in the URL because two caches in one database resolve the
255
+ * same connection string.
256
+ */
257
+ cache: async (declaration, context) => {
258
+ if (declaration.kind !== "cache") throw new WrongKind(declaration.kind);
259
+ const parentId = declaration.of ?? (context.cache === "db" ? soleDatabase(context) : void 0);
260
+ if (!parentId) throw new CacheNeedsAHome(declaration.id, context.cache);
261
+ const parent = context.provisioned[parentId];
262
+ if (!parent) throw new UnresolvedParent(declaration.id, parentId);
263
+ const parentUrl = parent.provides[(0, _geekmidas_manifest.provideKey)(parentId, "url")];
264
+ if (!parentUrl) throw new UnresolvedParent(declaration.id, parentId);
265
+ const table = declaration.table ?? (0, _geekmidas_manifest.cacheTable)(declaration.id);
266
+ const schema = schemaOf(context.manifest, parentId);
267
+ const qualified = schema ? `${schema}.${table}` : table;
268
+ context.deferred.push(...(0, _geekmidas_cache_postgres.cacheTableStatements)({ table: qualified }).map((statement) => ({
269
+ id: declaration.id,
270
+ database: new URL(parentUrl).pathname.slice(1),
271
+ describe: statement.describe,
272
+ sql: statement.sql,
273
+ ...statement.exists ? { exists: statement.exists } : {}
274
+ })), {
275
+ id: declaration.id,
276
+ database: new URL(parentUrl).pathname.slice(1),
277
+ describe: `${qualified} is owned by its schema's owner`,
278
+ sql: `ALTER TABLE ${quoted(qualified)} OWNER TO ${quoted((0, _geekmidas_db_pg_roles.ownerRole)(new URL(parentUrl).username))}`
279
+ }, {
280
+ id: declaration.id,
281
+ database: new URL(parentUrl).pathname.slice(1),
282
+ describe: `${new URL(parentUrl).username} may read and write ${qualified}`,
283
+ sql: `GRANT SELECT, INSERT, UPDATE, DELETE ON ${quoted(qualified)} TO ${quoted(new URL(parentUrl).username)}`
284
+ });
285
+ const url = new URL(parentUrl);
286
+ url.searchParams.set("table", table);
287
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: url.toString() } };
288
+ },
289
+ /**
290
+ * A bucket, as a MinIO stack on the box.
291
+ *
292
+ * Dokploy has first-class primitives for Postgres and Redis and none for
293
+ * object storage, so this is the one kind whose infrastructure this target
294
+ * *writes* rather than configures — a compose file with one service in it.
295
+ *
296
+ * The service is named `cloudName(...)` like everything else, which is not
297
+ * cosmetic here: containers on `dokploy-network` resolve each other by
298
+ * service name, so the name is the address. Calling it `minio` would work
299
+ * for exactly one project on the box and then collide.
300
+ *
301
+ * `s3://` carries no credentials, deliberately — deployed on AWS the SDK
302
+ * reads them from an execution role, so a URL that embedded a key would be
303
+ * one more thing to rotate and leak. There is no role here, so the same
304
+ * chain reads `AWS_ACCESS_KEY_ID` beside the URL, exactly as it does
305
+ * locally.
306
+ */
307
+ objects: async (declaration, context) => {
308
+ if (declaration.kind !== "objects") throw new WrongKind(declaration.kind);
309
+ const backend = context.storage ?? "minio";
310
+ if (backend !== "minio") throw new UnprovisionableBucket(declaration.id, backend);
311
+ const service = serviceName({
312
+ stage: context.stage,
313
+ app: context.scope ?? context.project
314
+ }, declaration.id);
315
+ const bucket = require_sniffer.resourceName(declaration.id, declaration.kind, context.stage);
316
+ const user = `${bucket}-root`;
317
+ const password = derivedPassword(context, `objects:${declaration.id}`);
318
+ const { compose } = await context.api.findOrCreateCompose(service, context.projectId, context.environmentId, minioCompose({
319
+ service,
320
+ bucket,
321
+ user,
322
+ password
323
+ }));
324
+ await context.api.deployCompose(compose.composeId);
325
+ return { provides: {
326
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: s3Url(service, bucket),
327
+ AWS_ACCESS_KEY_ID: user,
328
+ AWS_SECRET_ACCESS_KEY: password,
329
+ AWS_REGION: MINIO_REGION
330
+ } };
331
+ },
332
+ /**
333
+ * The address a bucket's objects are served on.
334
+ *
335
+ * Nothing is provisioned: Dokploy runs Traefik, so a second reverse proxy
336
+ * behind the first would terminate TLS twice — which is why the local
337
+ * target's Caddy has no equivalent here. What this resolves is the address,
338
+ * and the `open` prefixes are applied to the bucket rather than to an edge,
339
+ * so a policy is what makes them public wherever the bucket lives.
340
+ *
341
+ * Until a Traefik rule exists it answers on MinIO directly, path-style,
342
+ * which is honest about the shape it has today: the bucket is in the path
343
+ * rather than fronted by a host of its own.
344
+ */
345
+ "file-server": async (declaration, context) => {
346
+ if (declaration.kind !== "file-server") throw new WrongKind(declaration.kind);
347
+ const parentUrl = context.provisioned[declaration.of]?.provides[(0, _geekmidas_manifest.provideKey)(declaration.of, "url")];
348
+ if (!parentUrl) throw new UnresolvedParent(declaration.id, declaration.of);
349
+ const endpoint = new URL(parentUrl).searchParams.get("endpoint");
350
+ const bucket = new URL(parentUrl).hostname;
351
+ if (!endpoint) throw new UnresolvedParent(declaration.id, declaration.of);
352
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: `${endpoint}/${bucket}` } };
353
+ },
354
+ /**
355
+ * A topic, and below it a queue — the same broker either way.
356
+ *
357
+ * Under pg-boss there is nothing to create in Dokploy: the broker is a
358
+ * schema tenant of the database the app already declared, exactly as it is
359
+ * locally, so what this resolves is an address rather than a service. Which
360
+ * is the point of putting the backend in config — the same handlers drain
361
+ * pg-boss here and SQS on AWS because the string they were handed said so.
362
+ *
363
+ * The tenant gets its own role rather than the cluster master, for the
364
+ * reason every other tenant does: pg-boss creates and owns its tables, and
365
+ * a broker that could also read the application's is a broker with a grant
366
+ * nothing asked for.
367
+ */
368
+ topic: async (declaration, context) => {
369
+ if (declaration.kind !== "topic") throw new WrongKind(declaration.kind);
370
+ return broker(declaration.id, context);
371
+ },
372
+ queue: async (declaration, context) => {
373
+ if (declaration.kind !== "queue") throw new WrongKind(declaration.kind);
374
+ return broker(declaration.id, context);
375
+ },
376
+ /**
377
+ * A signing key, generated once and remembered in the stage's store.
378
+ *
379
+ * Random, never derived: a key computed from the project and stage names
380
+ * signs sessions anyone reading the repo could forge. The deploy generates
381
+ * it before provisioning (`withGeneratedSecrets`) and every later deploy
382
+ * reads the same one, so live sessions survive a redeploy. Nothing is
383
+ * created in Dokploy: a secret has no address.
384
+ */
385
+ secret: async (declaration, context) => {
386
+ if (declaration.kind !== "secret") throw new WrongKind(declaration.kind);
387
+ const key = declaration.provides?.[0];
388
+ if (!key) return { provides: {} };
389
+ return { provides: { [key]: supplied(declaration.id, key, context) } };
390
+ },
391
+ /**
392
+ * The keyring the stage keeps in its secrets.
393
+ *
394
+ * Generated on the first deploy (`withGeneratedSecrets`) and rotated only
395
+ * by `gkm encryption:rotate`, so a redeploy never changes a key and nothing
396
+ * written becomes unreadable. Nothing is created in Dokploy: the process
397
+ * holds the keyring.
398
+ */
399
+ encryption: async (declaration, context) => {
400
+ if (declaration.kind !== "encryption") throw new WrongKind(declaration.kind);
401
+ const key = (0, _geekmidas_manifest.provideKey)(declaration.id, "url");
402
+ return { provides: { [key]: supplied(declaration.id, key, context) } };
403
+ },
404
+ /**
405
+ * A third party's credentials, as the stage was given them.
406
+ *
407
+ * Nothing is created and nothing derived: the value was issued by somebody
408
+ * else. A stage that was never given one fails the deploy here, naming the
409
+ * command that sets it — not the first request that needs it.
410
+ */
411
+ credential: async (declaration, context) => {
412
+ if (declaration.kind !== "credential") throw new WrongKind(declaration.kind);
413
+ const key = (0, _geekmidas_manifest.provideKey)(declaration.id, "credentials");
414
+ return { provides: { [key]: supplied(declaration.id, key, context) } };
415
+ },
416
+ /**
417
+ * An API somebody else runs: the URL this stage calls it at, and the
418
+ * credentials it was issued for this stage.
419
+ */
420
+ "external-api": async (declaration, context) => {
421
+ if (declaration.kind !== "external-api") throw new WrongKind(declaration.kind);
422
+ const credentials = (0, _geekmidas_manifest.provideKey)(declaration.id, "credentials");
423
+ return { provides: {
424
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: (0, _geekmidas_manifest.externalApiUrl)(declaration, context.stage),
425
+ [credentials]: supplied(declaration.id, credentials, context)
426
+ } };
427
+ },
428
+ /**
429
+ * A surface, at the address whatever created its domain assigned.
430
+ *
431
+ * Nothing is provisioned here: the application and its domain are the
432
+ * existing engine's, and Dokploy's own Traefik terminates TLS with a Let's
433
+ * Encrypt certificate. What this adds is the *derivation* — who may call it,
434
+ * and where a cookie it sets is readable — from the graph rather than from a
435
+ * hand-maintained list.
436
+ */
437
+ "rest-api": async (declaration, context) => {
438
+ if (declaration.kind !== "rest-api") throw new WrongKind(declaration.kind);
439
+ const url = context.addresses?.[declaration.id];
440
+ if (!url) throw new SurfaceHasNoAddress(declaration.id);
441
+ const origins = [...new Set((0, _geekmidas_manifest.dependentsOf)(context.manifest, declaration.id).map((caller) => context.addresses?.[caller]).filter((address) => Boolean(address)))].sort();
442
+ const domain = (0, _geekmidas_manifest.cookieDomain)([url, ...origins]);
443
+ const schemes = (0, _geekmidas_manifest.dependentsOf)(context.manifest, declaration.id).flatMap((caller) => {
444
+ const app = context.manifest[caller];
445
+ return app?.kind === "mobile-app" ? (0, _geekmidas_manifest.mobileOrigins)((0, _geekmidas_manifest.schemeBase)(context.project, app.scheme)) : [];
446
+ });
447
+ return { provides: {
448
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: url,
449
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "trustedOrigins")]: [...origins, ...schemes].join(","),
450
+ ...domain ? { [(0, _geekmidas_manifest.provideKey)(declaration.id, "cookieDomain")]: domain } : {}
451
+ } };
452
+ }
453
+ };
454
+ /** The provisioner for a kind, or nothing where this target has none yet. */
455
+ function provisionerFor(kind) {
456
+ return PROVISIONERS[kind];
457
+ }
458
+ /**
459
+ * The role DDL for one database or tenant, from the shared generator.
460
+ *
461
+ * The same statements the local target applies and the same ones the AWS
462
+ * bootstrap runs. Dokploy used to write its own, which is how three targets
463
+ * came to hold three definitions of the same split.
464
+ */
465
+ function statementsFor(options) {
466
+ const { id, database, runtime, owner, reader, schema, context } = options;
467
+ return (0, _geekmidas_db_pg_roles.roleStatements)({
468
+ runtime,
469
+ owner,
470
+ ...reader ? { reader } : {},
471
+ schema,
472
+ ...options.ownsDatabase ? { database } : {},
473
+ passwords: {
474
+ runtime: derivedPassword(context, runtime),
475
+ owner: derivedPassword(context, owner),
476
+ ...reader ? { reader: derivedPassword(context, reader) } : {}
477
+ }
478
+ }).map((statement) => ({
479
+ ...statement,
480
+ id,
481
+ database
482
+ }));
483
+ }
484
+ /**
485
+ * The connection string a declared queue or topic publishes on.
486
+ *
487
+ * One broker for the whole project, which is what the local target does and
488
+ * what the runtime expects: the generated pollers open a single connection and
489
+ * subscribe each worker by name on it. So every carrier resolves to the same
490
+ * address, and the DDL that backs it is pushed once however many are declared.
491
+ *
492
+ * Only pg-boss is answered here. SNS needs a topic ARN that has to exist
493
+ * first, and RabbitMQ needs a broker Dokploy has no primitive for — both are
494
+ * the §4.3 question, and composing a plausible URL for either would fail at the
495
+ * first publish instead of here.
496
+ */
497
+ function broker(id, context) {
498
+ const backend = context.events ?? "pgboss";
499
+ if (backend !== "pgboss") throw new UnprovisionableCarrier(id, backend);
500
+ const parentId = soleDatabase(context);
501
+ if (!parentId) throw new BrokerNeedsADatabase(id);
502
+ const parentUrl = context.provisioned[parentId]?.provides[(0, _geekmidas_manifest.provideKey)(parentId, "url")];
503
+ if (!parentUrl) throw new UnresolvedParent(id, parentId);
504
+ const url = new URL(parentUrl);
505
+ const database = url.pathname.slice(1);
506
+ const runtime = `${database}_${PGBOSS_SCHEMA}`;
507
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
508
+ if (!context.provisioned[BROKER_ID]) {
509
+ context.deferred.push(...statementsFor({
510
+ id: BROKER_ID,
511
+ database,
512
+ runtime,
513
+ owner,
514
+ schema: PGBOSS_SCHEMA,
515
+ context
516
+ }));
517
+ context.provisioned[BROKER_ID] = { provides: {} };
518
+ }
519
+ const connection = pgbossUrl(runtime, derivedPassword(context, runtime), url.host, database);
520
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(id, "publisherConnectionString")]: connection } };
521
+ }
522
+ /** The schema pg-boss creates its tables in, here as locally. */
523
+ const PGBOSS_SCHEMA = "pgboss";
524
+ /**
525
+ * The id the broker's DDL is pushed under.
526
+ *
527
+ * Not a construct — no declaration names it — but the deferred statements need
528
+ * an id, and every carrier in the project shares this one.
529
+ */
530
+ const BROKER_ID = "PgBoss";
531
+ /**
532
+ * A pg-boss address: a Postgres URL under a scheme that picks the transport.
533
+ *
534
+ * The protocol is what a producer branches on, so it never branches — the same
535
+ * `.publish()` reaches pg-boss here and SQS on AWS.
536
+ */
537
+ function pgbossUrl(role, password, host, database) {
538
+ return `pgboss://${role}:${encodeURIComponent(password)}@${host}/${database}?schema=${PGBOSS_SCHEMA}`;
539
+ }
540
+ /** The region MinIO is addressed with. It has no regions; the SDK wants one. */
541
+ const MINIO_REGION = "us-east-1";
542
+ /** An `s3://` URL pointing the same S3 client at MinIO on the internal network. */
543
+ function s3Url(service, bucket) {
544
+ return `s3://${bucket}?region=${MINIO_REGION}&endpoint=http://${service}:9000&forcePathStyle=true`;
545
+ }
546
+ /**
547
+ * A one-service compose file for a bucket.
548
+ *
549
+ * `dokploy-network` is external and already exists — it is what every Dokploy
550
+ * service is attached to, and joining it is what makes the app able to resolve
551
+ * this one by name. The bucket itself is created by MinIO's entrypoint rather
552
+ * than by a second call, so there is nothing to reconcile afterwards.
553
+ */
554
+ function minioCompose(options) {
555
+ const { service, bucket, user, password } = options;
556
+ return [
557
+ "services:",
558
+ ` ${service}:`,
559
+ " image: pgsty/minio:RELEASE.2026-08-04T00-00-00Z",
560
+ ` command: server /data --console-address ":9001"`,
561
+ " environment:",
562
+ ` MINIO_ROOT_USER: ${user}`,
563
+ ` MINIO_ROOT_PASSWORD: ${password}`,
564
+ " volumes:",
565
+ ` - ${service}-data:/data`,
566
+ " networks:",
567
+ " - dokploy-network",
568
+ " healthcheck:",
569
+ " test: [\"CMD\", \"mc\", \"ready\", \"local\"]",
570
+ " interval: 10s",
571
+ " retries: 5",
572
+ ` ${service}-bucket:`,
573
+ " image: minio/mc:latest",
574
+ " depends_on:",
575
+ ` ${service}:`,
576
+ " condition: service_healthy",
577
+ " entrypoint: >",
578
+ ` /bin/sh -c "mc alias set s3 http://${service}:9000 ${user} ${password} &&`,
579
+ ` mc mb --ignore-existing s3/${bucket}"`,
580
+ " networks:",
581
+ " - dokploy-network",
582
+ "volumes:",
583
+ ` ${service}-data:`,
584
+ "networks:",
585
+ " dokploy-network:",
586
+ " external: true",
587
+ ""
588
+ ].join("\n");
589
+ }
590
+ /** Whether anything reads through a reader on this construct. */
591
+ function readsFrom(manifest, id) {
592
+ return Object.values(manifest).some((declaration) => declaration.kind === "database-reader" && declaration.of === id);
593
+ }
594
+ /** The schema a database or tenant pins on its roles. */
595
+ function schemaOf(manifest, id) {
596
+ const declaration = manifest[id];
597
+ if (declaration?.kind === "database") return declaration.schema ?? "app";
598
+ if (declaration?.kind === "database-schema") return declaration.schema;
599
+ }
600
+ /**
601
+ * The one declared database, where `cache: 'db'` has to pick.
602
+ *
603
+ * Unambiguous with one and arbitrary with two, so two is an error rather than a
604
+ * coin toss — a cache landing in a database nobody chose surfaces as entries
605
+ * that are never found, long after the deploy reported success.
606
+ */
607
+ function soleDatabase(context) {
608
+ const databases = Object.entries(context.manifest).filter(([, declaration]) => declaration.kind === "database").map(([id]) => id);
609
+ if (databases.length > 1) throw new CacheIsAmbiguous(databases);
610
+ return databases[0];
611
+ }
612
+ /**
613
+ * A password derived from the stage's seed, the project, the stage and the role.
614
+ *
615
+ * Derived rather than stored per role so a redeploy hands the running
616
+ * application the password it already has, and two projects never share one.
617
+ * The seed is what makes it secret: random, generated once and kept in the
618
+ * stage's store. Without it the inputs are all in the repo, and so was every
619
+ * production password.
620
+ */
621
+ function derivedPassword(context, role) {
622
+ return (0, node_crypto.createHash)("sha256").update(`${context.seed}:${context.project}:${context.stage}:role:${role}`).digest("base64url").slice(0, 32);
623
+ }
624
+ /** A connection string for a role on a cluster. */
625
+ function postgresUrl(role, password, host, database) {
626
+ return `postgres://${role}:${encodeURIComponent(password)}@${host}:5432/${database}`;
627
+ }
628
+ /** Quote an identifier, per segment, for DDL that cannot be parameterised. */
629
+ function quoted(name) {
630
+ return name.split(".").map((part) => `"${part.replace(/"/g, "\"\"")}"`).join(".");
631
+ }
632
+ /** A provisioner was handed a declaration of the wrong kind. */
633
+ /**
634
+ * A value only the stage's own secrets can hold.
635
+ *
636
+ * @throws {MissingSuppliedSecret} when the stage was never given it.
637
+ */
638
+ function supplied(id, key, context) {
639
+ const value = context.supplied?.[key];
640
+ if (value === void 0) throw new MissingSuppliedSecret(id, key, context.stage);
641
+ return value;
642
+ }
643
+ /** A construct needs a value the stage was never given. */
644
+ var MissingSuppliedSecret = class extends Error {
645
+ id;
646
+ key;
647
+ stage;
648
+ constructor(id, key, stage) {
649
+ super(`'${id}' needs ${key}, and the stage '${stage}' has none. Nothing can derive it; set it in the stage's secrets: gkm secrets:set ${key} '…' --stage ${stage}`);
650
+ this.id = id;
651
+ this.key = key;
652
+ this.stage = stage;
653
+ this.name = "MissingSuppliedSecret";
654
+ }
655
+ };
656
+ var WrongKind = class extends Error {
657
+ kind;
658
+ constructor(kind) {
659
+ super(`No Dokploy provisioner handles '${kind}'`);
660
+ this.kind = kind;
661
+ this.name = "WrongKind";
662
+ }
663
+ };
664
+ /** A derived construct whose parent has not been provisioned. */
665
+ var UnresolvedParent = class extends Error {
666
+ id;
667
+ parent;
668
+ constructor(id, parent) {
669
+ super(`'${id}' derives from '${parent}', which has not been provisioned. Provision in \`provisionOrder\`, which puts parents first.`);
670
+ this.id = id;
671
+ this.parent = parent;
672
+ this.name = "UnresolvedParent";
673
+ }
674
+ };
675
+ /** A cache with nowhere to live. */
676
+ var CacheNeedsAHome = class extends Error {
677
+ id;
678
+ backend;
679
+ constructor(id, backend) {
680
+ super(`'${id}' is a cache and nothing says where it lives. Declare it from its database — \`orders.cache('${id}')\`.` + (backend ? ` The deploy target's backend is '${backend}'.` : ""));
681
+ this.id = id;
682
+ this.backend = backend;
683
+ this.name = "CacheNeedsAHome";
684
+ }
685
+ };
686
+ /** A `'db'` cache (a server target's default) with more than one database. */
687
+ var CacheIsAmbiguous = class extends Error {
688
+ databases;
689
+ constructor(databases) {
690
+ super(`A cache backed by the database needs to know which one, and this app declares ${databases.length}: ${databases.join(", ")}. Declare the cache from its database rather than as a bare new Cache().`);
691
+ this.databases = databases;
692
+ this.name = "CacheIsAmbiguous";
693
+ }
694
+ };
695
+ /** A surface reached provisioning before its domain existed. */
696
+ var SurfaceHasNoAddress = class extends Error {
697
+ id;
698
+ constructor(id) {
699
+ super(`'${id}' is a surface and no address was supplied for it. The domain is created before the manifest is provisioned, so this means the two ran out of order.`);
700
+ this.id = id;
701
+ this.name = "SurfaceHasNoAddress";
702
+ }
703
+ };
704
+ /** A queue or topic on a backend this target has no primitive for. */
705
+ var UnprovisionableCarrier = class extends Error {
706
+ id;
707
+ backend;
708
+ constructor(id, backend) {
709
+ super(`'${id}' is carried by '${backend}', which this target cannot provision. SNS needs a topic ARN that has to exist first and RabbitMQ needs a broker Dokploy has no primitive for; pg-boss is a schema tenant of a database this app already declares, which is why it is the one that works here. Deploy this app to a target that has the backend.`);
710
+ this.id = id;
711
+ this.backend = backend;
712
+ this.name = "UnprovisionableCarrier";
713
+ }
714
+ };
715
+ /** A pg-boss carrier in an app that declares no database to host it. */
716
+ var BrokerNeedsADatabase = class extends Error {
717
+ id;
718
+ constructor(id) {
719
+ super(`'${id}' is carried by pg-boss, which lives in the database the app declares — and this app declares none. Declare a database, or deploy to a target whose broker is its own.`);
720
+ this.id = id;
721
+ this.name = "BrokerNeedsADatabase";
722
+ }
723
+ };
724
+ /** A bucket on a backend this target has no primitive for. */
725
+ var UnprovisionableBucket = class extends Error {
726
+ id;
727
+ backend;
728
+ constructor(id, backend) {
729
+ super(`'${id}' is stored on '${backend}', which this target cannot provision: an S3 or R2 bucket belongs to an account this deploy does not hold, the way an API key does. Supply the bucket's URL.`);
730
+ this.id = id;
731
+ this.backend = backend;
732
+ this.name = "UnprovisionableBucket";
733
+ }
734
+ };
735
+ //#endregion
736
+ //#region src/deploy/declared.ts
737
+ /**
738
+ * The declared half of a Dokploy deploy.
739
+ *
740
+ * `fromManifest.ts` decides what each construct resolves to; this runs it —
741
+ * discovers the manifest, walks it parents-first, and applies the DDL the
742
+ * provisioners deferred.
743
+ *
744
+ * It is deliberately separate from the engine in `index.ts`. That file deploys
745
+ * *applications*: images, registries, domains, the things a project has whether
746
+ * or not it declares anything. This is the part that exists because the app
747
+ * declared it, and keeping the two apart is what lets a project adopt the model
748
+ * without rewriting its deploy — and lets this one be tested without one.
749
+ */
750
+ /**
751
+ * Provision everything the workspace declares, and return what it resolved.
752
+ */
753
+ async function provisionDeclared(options) {
754
+ const { workspace } = options;
755
+ const empty = {
756
+ env: {},
757
+ statements: [],
758
+ provisioned: {},
759
+ clusters: {}
760
+ };
761
+ const manifest = options.manifest ?? await require_discover.discover({
762
+ patterns: require_sniffer.constructGlobs(workspace),
763
+ cwd: workspace.root
764
+ });
765
+ if (Object.keys(manifest).length === 0) return empty;
766
+ const context = {
767
+ manifest,
768
+ provisioned: {},
769
+ api: options.api,
770
+ projectId: options.projectId,
771
+ environmentId: options.environmentId,
772
+ stage: options.stage,
773
+ project: workspace.name,
774
+ scope: options.scope ?? workspace.name,
775
+ cache: require_sniffer.cacheBackendFor(require_sniffer.providerOf(workspace)),
776
+ events: require_sniffer.eventsBackendFor(require_sniffer.providerOf(workspace)),
777
+ storage: require_sniffer.storageBackendFor(require_sniffer.providerOf(workspace)),
778
+ addresses: surfaceAddresses(manifest, options.appUrls),
779
+ seed: options.seed,
780
+ ...options.supplied ? { supplied: options.supplied } : {},
781
+ deferred: [],
782
+ clusters: {}
783
+ };
784
+ const env = {};
785
+ for (const id of carriersLast((0, _geekmidas_manifest.provisionOrder)(manifest), manifest)) {
786
+ const declaration = manifest[id];
787
+ if (!declaration) continue;
788
+ const provisioner = provisionerFor(declaration.kind);
789
+ if (!provisioner) continue;
790
+ const result = await provisioner(declaration, context);
791
+ context.provisioned[id] = result;
792
+ Object.assign(env, result.provides);
793
+ }
794
+ return {
795
+ env,
796
+ statements: context.deferred.map((statement) => ({
797
+ id: statement.id,
798
+ describe: statement.describe,
799
+ ...statement.database ? { database: statement.database } : {},
800
+ ...statement.exists ? { exists: statement.exists } : {},
801
+ create: statement.sql
802
+ })),
803
+ provisioned: context.provisioned,
804
+ clusters: context.clusters
805
+ };
806
+ }
807
+ /**
808
+ * Run the deferred DDL against a cluster that is now reachable.
809
+ *
810
+ * The same applier the local target uses: every statement asks whether it is
811
+ * needed first, so a redeploy is free and a half-applied run recovers by being
812
+ * run again.
813
+ */
814
+ async function applyDeclared(client, statements) {
815
+ return (await require_sniffer.applyPostgres(client, statements)).filter((entry) => entry.created).length;
816
+ }
817
+ /**
818
+ * The provisioning order, with queues and topics moved to the end.
819
+ *
820
+ * `provisionOrder` walks `of` edges, and a carrier has none: a topic is not
821
+ * *derived from* a database, because under SNS it does not live in one. Where
822
+ * it lives is a fact about the backend, which is config — so the dependency is
823
+ * real under pg-boss and absent under SNS, and writing it into the declaration
824
+ * would state it in the one place that cannot know.
825
+ *
826
+ * Here it can. This runs where the backend is known, and the rule needs no
827
+ * branch on it: nothing depends on a carrier. A queue's worker and a topic's
828
+ * subscribers are *bound* to it rather than dependent on it, which is why
829
+ * neither holds a key of its own — so a carrier can always go last, and under
830
+ * pg-boss that is exactly late enough for the database it reads to be there.
831
+ */
832
+ function carriersLast(ordered, manifest) {
833
+ const carries = (id) => {
834
+ const kind = manifest[id]?.kind;
835
+ return kind === "queue" || kind === "topic";
836
+ };
837
+ return [...ordered.filter((id) => !carries(id)), ...ordered.filter(carries)];
838
+ }
839
+ /**
840
+ * Where each declared surface answers: its own app's address.
841
+ *
842
+ * Every surface is an app of its own, keyed by its id the way the derivation
843
+ * keyed it — `Api` is `api`, `Webhooks` is `webhooks` — and answers on that
844
+ * app's host, `{subdomain}.{domain}`. It used to be handed the first backend's
845
+ * address, so a workspace with two APIs pointed both at the same one.
846
+ */
847
+ function surfaceAddresses(manifest, appUrls) {
848
+ const addresses = {};
849
+ for (const [id, declaration] of Object.entries(manifest)) {
850
+ if (declaration.kind !== "rest-api") continue;
851
+ const url = appUrls[require_config.appKey(id)];
852
+ if (url) addresses[id] = url;
853
+ }
854
+ return addresses;
855
+ }
856
+ //#endregion
857
+ //#region src/deploy/dns/DnsProvider.ts
858
+ /**
859
+ * Check if value is a DnsProvider implementation.
860
+ */
861
+ function isDnsProvider(value) {
862
+ return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.getRecords === "function" && typeof value.upsertRecords === "function" && typeof value.deleteRecords === "function";
863
+ }
864
+ /**
865
+ * Create a DNS provider based on configuration.
866
+ *
867
+ * - 'hostinger': HostingerProvider
868
+ * - 'route53': Route53Provider
869
+ * - 'manual': Returns null (user handles DNS)
870
+ * - Custom: Use provided DnsProvider implementation
871
+ */
872
+ async function createDnsProvider(options) {
873
+ const { config } = options;
874
+ if (config.provider === "manual") return null;
875
+ if (isDnsProvider(config.provider)) return config.provider;
876
+ const provider = config.provider;
877
+ if (provider === "hostinger") {
878
+ const { HostingerProvider } = await Promise.resolve().then(() => require("./HostingerProvider-CgDaD8VR.cjs"));
879
+ return new HostingerProvider();
880
+ }
881
+ if (provider === "route53") {
882
+ const { Route53Provider } = await Promise.resolve().then(() => require("./Route53Provider-DVILBsvV.cjs"));
883
+ const route53Config = config;
884
+ return new Route53Provider({
885
+ region: route53Config.region,
886
+ profile: route53Config.profile,
887
+ hostedZoneId: route53Config.hostedZoneId
888
+ });
889
+ }
890
+ if (provider === "cloudflare") throw new Error("Cloudflare DNS provider not yet implemented");
891
+ throw new Error(`Unknown DNS provider: ${JSON.stringify(config)}`);
892
+ }
893
+ //#endregion
894
+ //#region src/deploy/dns/index.ts
895
+ /**
896
+ * DNS orchestration for deployments
897
+ *
898
+ * Handles automatic DNS record creation for deployed applications.
899
+ */
900
+ const logger$3 = require_discover.output;
901
+ /**
902
+ * Check if DNS config is legacy format (single domain with `domain` property)
903
+ */
904
+ function isLegacyDnsConfig(config) {
905
+ return typeof config === "object" && config !== null && "provider" in config && "domain" in config;
906
+ }
907
+ /**
908
+ * Normalize DNS config to new multi-domain format
909
+ */
910
+ function normalizeDnsConfig(config) {
911
+ if (isLegacyDnsConfig(config)) {
912
+ const { domain, ...providerConfig } = config;
913
+ return { [domain]: providerConfig };
914
+ }
915
+ return config;
916
+ }
917
+ /**
918
+ * Find the root domain for a hostname from available DNS configs
919
+ *
920
+ * @example
921
+ * findRootDomain('api.geekmidas.com', { 'geekmidas.com': {...}, 'geekmidas.dev': {...} })
922
+ * // Returns 'geekmidas.com'
923
+ */
924
+ function findRootDomain(hostname, dnsConfig) {
925
+ const domains = Object.keys(dnsConfig).sort((a, b) => b.length - a.length);
926
+ for (const domain of domains) if (hostname === domain || hostname.endsWith(`.${domain}`)) return domain;
927
+ return null;
928
+ }
929
+ /**
930
+ * Group hostnames by their root domain
931
+ */
932
+ function groupHostnamesByDomain(appHostnames, dnsConfig) {
933
+ const grouped = /* @__PURE__ */ new Map();
934
+ for (const [appName, hostname] of appHostnames) {
935
+ const rootDomain = findRootDomain(hostname, dnsConfig);
936
+ if (!rootDomain) {
937
+ logger$3.log(` ⚠ No DNS config found for hostname: ${hostname}`);
938
+ continue;
939
+ }
940
+ if (!grouped.has(rootDomain)) grouped.set(rootDomain, /* @__PURE__ */ new Map());
941
+ grouped.get(rootDomain).set(appName, hostname);
942
+ }
943
+ return grouped;
944
+ }
945
+ /**
946
+ * Resolve IP address from a hostname
947
+ */
948
+ async function resolveHostnameToIp(hostname) {
949
+ try {
950
+ return (await (0, node_dns_promises.lookup)(hostname, { family: 4 })).address;
951
+ } catch (error) {
952
+ throw new Error(`Failed to resolve IP for ${hostname}: ${error instanceof Error ? error.message : "Unknown error"}`);
953
+ }
954
+ }
955
+ /**
956
+ * Extract subdomain from full hostname relative to root domain
957
+ *
958
+ * @example
959
+ * extractSubdomain('api.joemoer.traflabs.io', 'traflabs.io') => 'api.joemoer'
960
+ * extractSubdomain('joemoer.traflabs.io', 'traflabs.io') => 'joemoer'
961
+ */
962
+ function extractSubdomain(hostname, rootDomain) {
963
+ if (!hostname.endsWith(rootDomain)) throw new Error(`Hostname ${hostname} is not under root domain ${rootDomain}`);
964
+ return hostname.slice(0, -(rootDomain.length + 1)) || "@";
965
+ }
966
+ /**
967
+ * Generate required DNS records for a deployment
968
+ */
969
+ function generateRequiredRecords(appHostnames, rootDomain, serverIp) {
970
+ const records = [];
971
+ for (const [appName, hostname] of appHostnames) {
972
+ const subdomain = extractSubdomain(hostname, rootDomain);
973
+ records.push({
974
+ hostname,
975
+ subdomain,
976
+ type: "A",
977
+ value: serverIp,
978
+ appName
979
+ });
980
+ }
981
+ return records;
982
+ }
983
+ /**
984
+ * Print DNS records table
985
+ */
986
+ function printDnsRecordsTable(records, rootDomain) {
987
+ logger$3.log(`\n 📋 DNS Records for ${rootDomain}:`);
988
+ logger$3.log(" ┌─────────────────────────────────────┬──────┬─────────────────┬────────┐");
989
+ logger$3.log(" │ Subdomain │ Type │ Value │ Status │");
990
+ logger$3.log(" ├─────────────────────────────────────┼──────┼─────────────────┼────────┤");
991
+ for (const record of records) {
992
+ const subdomain = record.subdomain.padEnd(35);
993
+ const type = record.type.padEnd(4);
994
+ const value = record.value.padEnd(15);
995
+ let status;
996
+ if (record.error) status = "✗";
997
+ else if (record.created) status = "✓ new";
998
+ else if (record.existed) status = "✓";
999
+ else status = "?";
1000
+ logger$3.log(` │ ${subdomain} │ ${type} │ ${value} │ ${status.padEnd(6)} │`);
1001
+ }
1002
+ logger$3.log(" └─────────────────────────────────────┴──────┴─────────────────┴────────┘");
1003
+ }
1004
+ /**
1005
+ * Print DNS records in a simple format for manual setup
1006
+ */
1007
+ function printDnsRecordsSimple(records, rootDomain) {
1008
+ logger$3.log("\n 📋 Required DNS Records:");
1009
+ logger$3.log(` Add these A records to your DNS provider (${rootDomain}):\n`);
1010
+ for (const record of records) logger$3.log(` ${record.subdomain} → ${record.value} (A record)`);
1011
+ logger$3.log("");
1012
+ }
1013
+ /**
1014
+ * Create DNS records for a single domain using its configured provider
1015
+ */
1016
+ async function createDnsRecordsForDomain(records, rootDomain, providerConfig) {
1017
+ const ttl = "ttl" in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300;
1018
+ let provider;
1019
+ try {
1020
+ provider = await createDnsProvider({ config: providerConfig });
1021
+ } catch (error) {
1022
+ const message = error instanceof Error ? error.message : "Unknown error";
1023
+ logger$3.log(` ⚠ Failed to create DNS provider for ${rootDomain}: ${message}`);
1024
+ return records.map((r) => ({
1025
+ ...r,
1026
+ error: message
1027
+ }));
1028
+ }
1029
+ if (!provider) return records.map((r) => ({
1030
+ ...r,
1031
+ created: false,
1032
+ existed: false
1033
+ }));
1034
+ const results = [];
1035
+ const upsertRecords = records.map((r) => ({
1036
+ name: r.subdomain,
1037
+ type: r.type,
1038
+ ttl,
1039
+ value: r.value
1040
+ }));
1041
+ try {
1042
+ const upsertResults = await provider.upsertRecords(rootDomain, upsertRecords);
1043
+ for (const [i, record] of records.entries()) {
1044
+ const result = upsertResults[i];
1045
+ if (!result) {
1046
+ results.push({
1047
+ hostname: record.hostname,
1048
+ subdomain: record.subdomain,
1049
+ type: record.type,
1050
+ value: record.value,
1051
+ appName: record.appName,
1052
+ error: "No result returned from provider"
1053
+ });
1054
+ continue;
1055
+ }
1056
+ if (result.unchanged) results.push({
1057
+ hostname: record.hostname,
1058
+ subdomain: record.subdomain,
1059
+ type: record.type,
1060
+ value: record.value,
1061
+ appName: record.appName,
1062
+ existed: true,
1063
+ created: false
1064
+ });
1065
+ else results.push({
1066
+ hostname: record.hostname,
1067
+ subdomain: record.subdomain,
1068
+ type: record.type,
1069
+ value: record.value,
1070
+ appName: record.appName,
1071
+ created: result.created,
1072
+ existed: !result.created
1073
+ });
1074
+ }
1075
+ } catch (error) {
1076
+ const message = error instanceof Error ? error.message : "Unknown error";
1077
+ logger$3.log(` ⚠ Failed to create DNS records for ${rootDomain}: ${message}`);
1078
+ return records.map((r) => ({
1079
+ hostname: r.hostname,
1080
+ subdomain: r.subdomain,
1081
+ type: r.type,
1082
+ value: r.value,
1083
+ appName: r.appName,
1084
+ error: message
1085
+ }));
1086
+ }
1087
+ return results;
1088
+ }
1089
+ /**
1090
+ * Main DNS orchestration function for deployments
1091
+ *
1092
+ * Supports both legacy single-domain format and new multi-domain format:
1093
+ * - Legacy: { provider: 'hostinger', domain: 'example.com' }
1094
+ * - Multi: { 'example.com': { provider: 'hostinger' }, 'example.dev': { provider: 'route53' } }
1095
+ *
1096
+ * @param appHostnames - Map of app names to hostnames
1097
+ * @param dnsConfig - DNS configuration (legacy or multi-domain)
1098
+ * @param dokployEndpoint - Dokploy server endpoint to resolve IP from
1099
+ * @param state - Optional state to save created records for later deletion
1100
+ */
1101
+ async function orchestrateDns(appHostnames, dnsConfig, dokployEndpoint, state) {
1102
+ if (!dnsConfig) return null;
1103
+ const normalizedConfig = normalizeDnsConfig(dnsConfig);
1104
+ logger$3.log("\n🌐 Setting up DNS records...");
1105
+ let serverIp;
1106
+ try {
1107
+ const endpointUrl = new URL(dokployEndpoint);
1108
+ serverIp = await resolveHostnameToIp(endpointUrl.hostname);
1109
+ logger$3.log(` Server IP: ${serverIp} (from ${endpointUrl.hostname})`);
1110
+ } catch (error) {
1111
+ const message = error instanceof Error ? error.message : "Unknown error";
1112
+ logger$3.log(` ⚠ Failed to resolve server IP: ${message}`);
1113
+ return null;
1114
+ }
1115
+ const groupedHostnames = groupHostnamesByDomain(appHostnames, normalizedConfig);
1116
+ if (groupedHostnames.size === 0) {
1117
+ logger$3.log(" No DNS records needed (no hostnames match configured domains)");
1118
+ return {
1119
+ records: [],
1120
+ success: true,
1121
+ serverIp
1122
+ };
1123
+ }
1124
+ const allRecords = [];
1125
+ let hasFailures = false;
1126
+ for (const [rootDomain, domainHostnames] of groupedHostnames) {
1127
+ const providerConfig = normalizedConfig[rootDomain];
1128
+ if (!providerConfig) {
1129
+ logger$3.log(` ⚠ No provider config for ${rootDomain}`);
1130
+ continue;
1131
+ }
1132
+ const providerName = typeof providerConfig.provider === "string" ? providerConfig.provider : "custom";
1133
+ const requiredRecords = generateRequiredRecords(domainHostnames, rootDomain, serverIp);
1134
+ if (requiredRecords.length === 0) continue;
1135
+ logger$3.log(` Creating DNS records for ${rootDomain} (${providerName})...`);
1136
+ const domainRecords = await createDnsRecordsForDomain(requiredRecords, rootDomain, providerConfig);
1137
+ allRecords.push(...domainRecords);
1138
+ const created = domainRecords.filter((r) => r.created).length;
1139
+ const existed = domainRecords.filter((r) => r.existed).length;
1140
+ const failed = domainRecords.filter((r) => r.error).length;
1141
+ if (created > 0) logger$3.log(` ✓ Created ${created} DNS record(s) for ${rootDomain}`);
1142
+ if (existed > 0) logger$3.log(` ✓ ${existed} record(s) already exist for ${rootDomain}`);
1143
+ if (failed > 0) {
1144
+ logger$3.log(` ⚠ ${failed} record(s) failed for ${rootDomain}`);
1145
+ hasFailures = true;
1146
+ }
1147
+ if (state) {
1148
+ for (const record of domainRecords) if (record.created || record.existed) require_sniffer.setDnsRecord(state, {
1149
+ domain: rootDomain,
1150
+ name: record.subdomain,
1151
+ type: record.type,
1152
+ value: record.value,
1153
+ ttl: "ttl" in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300
1154
+ });
1155
+ }
1156
+ printDnsRecordsTable(domainRecords, rootDomain);
1157
+ if (providerConfig.provider === "manual" || failed > 0) printDnsRecordsSimple(domainRecords.filter((r) => !r.created && !r.existed), rootDomain);
1158
+ }
1159
+ return {
1160
+ records: allRecords,
1161
+ success: !hasFailures,
1162
+ serverIp
1163
+ };
1164
+ }
1165
+ /**
1166
+ * Verify DNS records resolve correctly after deployment.
1167
+ *
1168
+ * This function:
1169
+ * 1. Checks state for previously verified hostnames (skips if already verified with same IP)
1170
+ * 2. Attempts to resolve each hostname to an IP
1171
+ * 3. Compares resolved IP with expected server IP
1172
+ * 4. Updates state with verification results
1173
+ *
1174
+ * @param appHostnames - Map of app names to hostnames
1175
+ * @param serverIp - Expected IP address the hostnames should resolve to
1176
+ * @param state - Deploy state for caching verification results
1177
+ * @returns Array of verification results
1178
+ */
1179
+ async function verifyDnsRecords(appHostnames, serverIp, state) {
1180
+ const results = [];
1181
+ logger$3.log("\n🔍 Verifying DNS records...");
1182
+ for (const [appName, hostname] of appHostnames) {
1183
+ if (require_sniffer.isDnsVerified(state, hostname, serverIp)) {
1184
+ logger$3.log(` ✓ ${hostname} (previously verified)`);
1185
+ results.push({
1186
+ hostname,
1187
+ appName,
1188
+ verified: true,
1189
+ expectedIp: serverIp,
1190
+ skipped: true
1191
+ });
1192
+ continue;
1193
+ }
1194
+ try {
1195
+ const resolvedIp = await resolveHostnameToIp(hostname);
1196
+ if (resolvedIp === serverIp) {
1197
+ require_sniffer.setDnsVerification(state, hostname, serverIp);
1198
+ logger$3.log(` ✓ ${hostname} → ${resolvedIp}`);
1199
+ results.push({
1200
+ hostname,
1201
+ appName,
1202
+ verified: true,
1203
+ resolvedIp,
1204
+ expectedIp: serverIp
1205
+ });
1206
+ } else {
1207
+ logger$3.log(` ⚠ ${hostname} resolves to ${resolvedIp}, expected ${serverIp}`);
1208
+ results.push({
1209
+ hostname,
1210
+ appName,
1211
+ verified: false,
1212
+ resolvedIp,
1213
+ expectedIp: serverIp
1214
+ });
1215
+ }
1216
+ } catch (error) {
1217
+ const message = error instanceof Error ? error.message : "Unknown error";
1218
+ logger$3.log(` ⚠ ${hostname} DNS not propagated (${message})`);
1219
+ results.push({
1220
+ hostname,
1221
+ appName,
1222
+ verified: false,
1223
+ expectedIp: serverIp,
1224
+ error: message
1225
+ });
1226
+ }
1227
+ }
1228
+ const verified = results.filter((r) => r.verified).length;
1229
+ const skipped = results.filter((r) => r.skipped).length;
1230
+ const pending = results.filter((r) => !r.verified).length;
1231
+ if (pending > 0) {
1232
+ logger$3.log(`\n ${verified} verified, ${pending} pending propagation`);
1233
+ logger$3.log(" DNS changes may take 5-30 minutes to propagate");
1234
+ } else if (skipped > 0) logger$3.log(` ${verified} verified (${skipped} from cache)`);
1235
+ return results;
1236
+ }
1237
+ //#endregion
1238
+ //#region src/deploy/docker.ts
1239
+ const logger$2 = require_discover.output;
1240
+ /**
1241
+ * The id the Dockerfile templates mount the encrypted credentials under:
1242
+ * `RUN --mount=type=secret,id=gkm_credentials`.
1243
+ */
1244
+ const CREDENTIALS_SECRET_ID = "gkm_credentials";
1245
+ /**
1246
+ * Get the full image reference
1247
+ */
1248
+ function getImageRef(registry, imageName, tag) {
1249
+ if (registry) return `${registry}/${imageName}:${tag}`;
1250
+ return `${imageName}:${tag}`;
1251
+ }
1252
+ /**
1253
+ * The `docker build` argv for an image.
1254
+ *
1255
+ * One element per value, so nothing in a ref or a build arg is read by a
1256
+ * shell, and `--opt=value` rather than `--opt value`, so a value that starts
1257
+ * with `-` cannot be taken for one of docker's own flags.
1258
+ *
1259
+ * @internal Exported for testing
1260
+ */
1261
+ function dockerBuildArgs(options) {
1262
+ const { dockerfilePath, imageRef, buildArgs = [], credentialsFile } = options;
1263
+ return [
1264
+ "build",
1265
+ "--platform=linux/amd64",
1266
+ `--file=${dockerfilePath}`,
1267
+ `--tag=${imageRef}`,
1268
+ ...buildArgs.map((arg) => `--build-arg=${arg}`),
1269
+ ...credentialsFile ? [`--secret=id=${CREDENTIALS_SECRET_ID},src=${credentialsFile}`] : [],
1270
+ "."
1271
+ ];
1272
+ }
1273
+ /**
1274
+ * Write the encrypted credentials where `docker build --secret` reads them.
1275
+ *
1276
+ * Two lines — ciphertext, then IV — so a template can split them with `sed`
1277
+ * in any base image. Owner-only, in a directory of its own, and the returned
1278
+ * cleanup removes both whatever the build did.
1279
+ *
1280
+ * @internal Exported for testing
1281
+ */
1282
+ async function writeCredentialsFile(credentials) {
1283
+ const dir = await (0, node_fs_promises.mkdtemp)((0, node_path.join)((0, node_os.tmpdir)(), "gkm-credentials-"));
1284
+ const path = (0, node_path.join)(dir, CREDENTIALS_SECRET_ID);
1285
+ await (0, node_fs_promises.writeFile)(path, `${credentials.encrypted}\n${credentials.iv}\n`, { mode: 384 });
1286
+ await (0, node_fs_promises.chmod)(path, 384);
1287
+ return {
1288
+ path,
1289
+ cleanup: () => (0, node_fs_promises.rm)(dir, {
1290
+ recursive: true,
1291
+ force: true
1292
+ })
1293
+ };
1294
+ }
1295
+ /**
1296
+ * Build Docker image
1297
+ * @param imageRef - Full image reference (registry/name:tag)
1298
+ * @param buildArgs - Build arguments to pass to docker build
1299
+ * @param credentials - Encrypted credentials, passed as a build secret
1300
+ */
1301
+ async function buildImage(imageRef, buildArgs, credentials, { cwd, signal, stdio }) {
1302
+ logger$2.log(`\n🔨 Building Docker image: ${imageRef}`);
1303
+ logger$2.log(" Generating Dockerfile for the pre-built bundle...");
1304
+ await require_sniffer.dockerCommand({
1305
+ slim: true,
1306
+ cwd
1307
+ });
1308
+ const dockerfilePath = (0, node_path.join)(cwd, ".gkm", "docker", "Dockerfile");
1309
+ const secret = credentials ? await writeCredentialsFile(credentials) : void 0;
1310
+ try {
1311
+ await require_sniffer.run("docker", dockerBuildArgs({
1312
+ dockerfilePath,
1313
+ imageRef,
1314
+ buildArgs,
1315
+ credentialsFile: secret?.path
1316
+ }), {
1317
+ cwd,
1318
+ env: {
1319
+ ...process.env,
1320
+ DOCKER_BUILDKIT: "1"
1321
+ },
1322
+ ...signal ? { signal } : {},
1323
+ ...stdio ? { stdio } : {}
1324
+ });
1325
+ logger$2.log(`✅ Image built: ${imageRef}`);
1326
+ } catch (error) {
1327
+ throw new require_sniffer.DockerBuildFailed(imageRef, error);
1328
+ } finally {
1329
+ await secret?.cleanup();
1330
+ }
1331
+ }
1332
+ /**
1333
+ * Push Docker image to registry
1334
+ */
1335
+ async function pushImage(imageRef, { cwd, signal, stdio }) {
1336
+ logger$2.log(`\n☁️ Pushing image: ${imageRef}`);
1337
+ try {
1338
+ await require_sniffer.run("docker", ["push", imageRef], {
1339
+ cwd,
1340
+ ...signal ? { signal } : {},
1341
+ ...stdio ? { stdio } : {}
1342
+ });
1343
+ logger$2.log(`✅ Image pushed: ${imageRef}`);
1344
+ } catch (error) {
1345
+ throw new require_sniffer.DockerPushFailed(imageRef, error);
1346
+ }
1347
+ }
1348
+ /**
1349
+ * The digest the registry gave a pushed image, `sha256:…`.
1350
+ *
1351
+ * A tag can be pushed over — by the next deploy, or by anything else that
1352
+ * shares the repository — and the digest is what says which image a stage
1353
+ * actually ran. `RepoDigests` has one entry per repository the image was
1354
+ * pushed to, so the one for this ref's repository is picked by name.
1355
+ *
1356
+ * @internal Exported for testing
1357
+ */
1358
+ async function pushedDigest(imageRef, { cwd, signal } = { cwd: process.cwd() }) {
1359
+ const repository = imageRef.split("@")[0].replace(/:[\w][\w.-]*$/, "");
1360
+ const output = await require_sniffer.runOutput("docker", [
1361
+ "image",
1362
+ "inspect",
1363
+ "--format={{json .RepoDigests}}",
1364
+ imageRef
1365
+ ], {
1366
+ cwd,
1367
+ ...signal ? { signal } : {}
1368
+ });
1369
+ let digests;
1370
+ try {
1371
+ digests = JSON.parse(output.trim() || "[]");
1372
+ } catch {
1373
+ return;
1374
+ }
1375
+ if (!Array.isArray(digests)) return void 0;
1376
+ return digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`))?.slice(repository.length + 1);
1377
+ }
1378
+ /**
1379
+ * Deploy using Docker (build and optionally push image)
1380
+ */
1381
+ async function deployDocker(options) {
1382
+ const { stage, tag, skipPush, masterKey, config, buildArgs, credentials } = options;
1383
+ const imageName = config.imageName;
1384
+ const imageRef = require_sniffer.validateImageRef(getImageRef(config.registry, imageName, tag));
1385
+ const docker = {
1386
+ cwd: options.cwd ?? process.cwd(),
1387
+ ...options.signal ? { signal: options.signal } : {},
1388
+ ...options.stdio ? { stdio: options.stdio } : {}
1389
+ };
1390
+ await buildImage(imageRef, buildArgs, credentials, docker);
1391
+ let digest;
1392
+ if (!skipPush) {
1393
+ if (!config.registry) logger$2.warn("\n⚠️ No registry configured. Use --skip-push or configure docker.registry in gkm.config.ts");
1394
+ else {
1395
+ await pushImage(imageRef, docker);
1396
+ digest = await pushedDigest(imageRef, docker);
1397
+ }
1398
+ }
1399
+ logger$2.log("\n✅ Docker deployment ready!");
1400
+ logger$2.log(`\n📋 Deployment details:`);
1401
+ logger$2.log(` Image: ${imageRef}`);
1402
+ logger$2.log(` Stage: ${stage}`);
1403
+ if (masterKey) logger$2.log(`\n🔐 Run the container with GKM_MASTER_KEY set to the key with fingerprint ${require_sniffer.keyFingerprint(masterKey)}.`);
1404
+ return {
1405
+ imageRef,
1406
+ ...digest ? { digest } : {},
1407
+ masterKey
1408
+ };
1409
+ }
1410
+ //#endregion
1411
+ //#region src/deploy/env-resolver.ts
1412
+ /**
1413
+ * Environment Variable Resolution for Dokploy Deployments
1414
+ *
1415
+ * Resolves sniffed environment variables to actual values during deployment.
1416
+ * Auto-supports common variables like DATABASE_URL, REDIS_URL, BETTER_AUTH_*,
1417
+ * and falls back to user-provided secrets.
1418
+ */
1419
+ /**
1420
+ * Generate a secure random secret (64 hex characters = 32 bytes)
1421
+ */
1422
+ function generateSecret() {
1423
+ return (0, node_crypto.randomBytes)(32).toString("hex");
1424
+ }
1425
+ /**
1426
+ * Get or generate a secret for an app.
1427
+ * If the secret already exists in state, returns it.
1428
+ * Otherwise generates a new one and stores it.
1429
+ */
1430
+ function getOrGenerateSecret(state, appName, secretName) {
1431
+ const existing = require_sniffer.getGeneratedSecret(state, appName, secretName);
1432
+ if (existing) return existing;
1433
+ const generated = generateSecret();
1434
+ require_sniffer.setGeneratedSecret(state, appName, secretName, generated);
1435
+ return generated;
1436
+ }
1437
+ /**
1438
+ * Resolve a single environment variable
1439
+ */
1440
+ function resolveEnvVar(varName, context) {
1441
+ switch (varName) {
1442
+ case "PORT": return String(context.app.port);
1443
+ case "NODE_ENV": return "production";
1444
+ case "STAGE": return context.stage;
1445
+ case "BETTER_AUTH_URL": return `https://${context.appHostname}`;
1446
+ case "BETTER_AUTH_SECRET": return getOrGenerateSecret(context.state, context.appName, "BETTER_AUTH_SECRET");
1447
+ case "BETTER_AUTH_TRUSTED_ORIGINS":
1448
+ if (context.frontendUrls.length > 0) return context.frontendUrls.join(",");
1449
+ break;
1450
+ case "GKM_MASTER_KEY": if (context.masterKey) return context.masterKey;
1451
+ }
1452
+ if (context.dependencyUrls && varName.endsWith("_URL")) {
1453
+ const depName = (require_workspace.stripPublicPrefix(varName) ?? varName).slice(0, -4).toLowerCase();
1454
+ if (context.dependencyUrls[depName]) return context.dependencyUrls[depName];
1455
+ }
1456
+ if (context.userSecrets) {
1457
+ if (context.userSecrets.custom[varName]) return context.userSecrets.custom[varName];
1458
+ if (varName in context.userSecrets.urls) return context.userSecrets.urls[varName];
1459
+ if (varName === "POSTGRES_PASSWORD" && context.userSecrets.services.postgres) return context.userSecrets.services.postgres.password;
1460
+ if (varName === "REDIS_PASSWORD" && context.userSecrets.services.redis) return context.userSecrets.services.redis.password;
1461
+ }
1462
+ }
1463
+ /**
1464
+ * Resolve all environment variables for an app
1465
+ */
1466
+ function resolveEnvVars(requiredVars, context) {
1467
+ const resolved = {};
1468
+ const missing = [];
1469
+ for (const varName of requiredVars) {
1470
+ const value = resolveEnvVar(varName, context);
1471
+ if (value !== void 0) resolved[varName] = value;
1472
+ else missing.push(varName);
1473
+ }
1474
+ return {
1475
+ resolved,
1476
+ missing
1477
+ };
1478
+ }
1479
+ /**
1480
+ * Format missing variables error message
1481
+ */
1482
+ function formatMissingVarsError(appName, missing, stage) {
1483
+ return `Deployment failed: ${appName} is missing required environment variables:\n${missing.map((v) => ` - ${v}`).join("\n")}\n\nAdd them with:\n gkm secrets:set <VAR_NAME> <value> --stage ${stage}\n\nOr add them to the app's requiredEnv in gkm.config.ts to have them auto-resolved.`;
1484
+ }
1485
+ /**
1486
+ * Validate that all required environment variables can be resolved
1487
+ */
1488
+ function validateEnvVars(requiredVars, context) {
1489
+ const { resolved, missing } = resolveEnvVars(requiredVars, context);
1490
+ return {
1491
+ valid: missing.length === 0,
1492
+ missing,
1493
+ resolved
1494
+ };
1495
+ }
1496
+ //#endregion
1497
+ //#region src/deploy/journal.ts
1498
+ var DeployJournal = class DeployJournal {
1499
+ store;
1500
+ stage;
1501
+ state;
1502
+ resources;
1503
+ version;
1504
+ existed;
1505
+ constructor(store, stage, state, resources, version, existed) {
1506
+ this.store = store;
1507
+ this.stage = stage;
1508
+ this.state = state;
1509
+ this.resources = resources;
1510
+ this.version = version;
1511
+ this.existed = existed;
1512
+ }
1513
+ /**
1514
+ * The stage's journal — its stored state, or `initial` written as the
1515
+ * stage's first state, so there is somewhere to record the very first
1516
+ * resource before it is created.
1517
+ */
1518
+ static async open(store, stage, initial) {
1519
+ const stored = await store.read(stage);
1520
+ if (stored) return new DeployJournal(store, stage, stored.state, stored.resources, stored.version, true);
1521
+ const state = initial();
1522
+ const version = await store.write(stage, state, { expectedVersion: null });
1523
+ return new DeployJournal(store, stage, state, {}, version, false);
1524
+ }
1525
+ record(key) {
1526
+ return this.resources[key];
1527
+ }
1528
+ /** The keys a previous run marked `pending` and never saw created. */
1529
+ unfinished() {
1530
+ return Object.values(this.resources).filter((record) => record.status === "pending").map((record) => record.key);
1531
+ }
1532
+ /** Records that `entry` is about to be created. */
1533
+ async pending(entry) {
1534
+ await this.put({
1535
+ ...entry,
1536
+ status: "pending"
1537
+ });
1538
+ }
1539
+ /** Records `entry` as existing with `id`; a no-op if it already is. */
1540
+ async ready(entry, id) {
1541
+ const current = this.resources[entry.key];
1542
+ if (current?.status === "ready" && current.id === id) return;
1543
+ await this.put({
1544
+ ...entry,
1545
+ status: "ready",
1546
+ id
1547
+ });
1548
+ }
1549
+ /**
1550
+ * The resource `entry` names: by its recorded id, else by looking it up,
1551
+ * else created — with `pending` written before the create and `ready`
1552
+ * after, so a run that dies in between leaves a record the next run
1553
+ * resolves by looking the resource up rather than creating another.
1554
+ */
1555
+ async ensure(entry, steps) {
1556
+ const record = this.resources[entry.key];
1557
+ let staleId;
1558
+ if (record?.status === "ready" && record.id && steps.get) {
1559
+ const known = await steps.get(record.id);
1560
+ if (known) {
1561
+ await this.ready(entry, steps.id(known));
1562
+ return {
1563
+ resource: known,
1564
+ via: "recorded"
1565
+ };
1566
+ }
1567
+ staleId = record.id;
1568
+ }
1569
+ const existing = await steps.find();
1570
+ if (existing) {
1571
+ await this.ready(entry, steps.id(existing));
1572
+ return {
1573
+ resource: existing,
1574
+ via: record?.status === "pending" ? "resumed" : "found",
1575
+ ...staleId ? { staleId } : {}
1576
+ };
1577
+ }
1578
+ await this.pending(entry);
1579
+ const created = await steps.create();
1580
+ await this.ready(entry, steps.id(created));
1581
+ return {
1582
+ resource: created,
1583
+ via: "created",
1584
+ ...staleId ? { staleId } : {}
1585
+ };
1586
+ }
1587
+ /** Writes the stage's state, keeping its resource records. */
1588
+ async save() {
1589
+ this.state.lastDeployedAt = (/* @__PURE__ */ new Date()).toISOString();
1590
+ this.version = await this.store.write(this.stage, this.state, { expectedVersion: this.version });
1591
+ }
1592
+ async put(record) {
1593
+ this.version = await this.store.putResource(this.stage, record, { expectedVersion: this.version });
1594
+ this.resources = {
1595
+ ...this.resources,
1596
+ [record.key]: {
1597
+ ...record,
1598
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1599
+ }
1600
+ };
1601
+ }
1602
+ };
1603
+ //#endregion
1604
+ //#region src/deploy/ownership.ts
1605
+ /**
1606
+ * Which Dokploy project a deploy is allowed to deploy into.
1607
+ *
1608
+ * Deploy used to take any project whose name matched the workspace's, in any
1609
+ * case — so a second workspace called `shop` (or `Shop`) on the same server
1610
+ * deployed into the first one's project, over its images and applications. A
1611
+ * project is now claimed by an ownership marker in its description, and a
1612
+ * project with the right name and no marker is somebody else's.
1613
+ */
1614
+ /**
1615
+ * A Dokploy project with the name this deploy would use exists, and nothing
1616
+ * says this workspace created it.
1617
+ */
1618
+ var ProjectNotOwned = class extends Error {
1619
+ projectName;
1620
+ projectId;
1621
+ identity;
1622
+ ownedBy;
1623
+ constructor(projectName, projectId, identity, ownedBy) {
1624
+ super(`The Dokploy project '${projectName}' (${projectId}) was not created by this workspace (${identity})${ownedBy ? ` — it is marked '${ownedBy}'` : ""}, so deploy will not use it. Set deploy.namespace in gkm.config.ts to deploy under a name of your own, or, if this project really is this workspace's, add 'gkm:${identity}' to its description in Dokploy.`);
1625
+ this.projectName = projectName;
1626
+ this.projectId = projectId;
1627
+ this.identity = identity;
1628
+ this.ownedBy = ownedBy;
1629
+ this.name = "ProjectNotOwned";
1630
+ }
1631
+ };
1632
+ /** A description with the marker added, keeping what was there. */
1633
+ function withMarker(description, marker) {
1634
+ const existing = (description ?? "").trim();
1635
+ return existing ? `${existing}\n${marker}` : marker;
1636
+ }
1637
+ /** `project.one`, or `null` when Dokploy no longer has the project. */
1638
+ async function projectById(api, projectId) {
1639
+ try {
1640
+ return await api.getProject(projectId) ?? null;
1641
+ } catch (error) {
1642
+ if (error instanceof require_sniffer.DokployApiError) return null;
1643
+ throw error;
1644
+ }
1645
+ }
1646
+ /**
1647
+ * The project this identity owns, if there is one — read only, so a dry run
1648
+ * asks the same question a deploy does:
1649
+ *
1650
+ * 1. The one the stage's state names, if Dokploy still has it. State written
1651
+ * before markers existed is trusted — it holds an id this workspace was
1652
+ * given when it created the project.
1653
+ * 2. One with this name *and* this identity's marker.
1654
+ *
1655
+ * A project that matches by name (in any case) but carries no marker, or
1656
+ * another identity's, raises `ProjectNotOwned` — it is never adopted.
1657
+ */
1658
+ async function findProject(api, identity, stateProjectId) {
1659
+ const name = require_store.projectName(identity);
1660
+ const marker = require_store.ownershipMarker(identity);
1661
+ if (stateProjectId) {
1662
+ const known = await projectById(api, stateProjectId);
1663
+ if (known) {
1664
+ const claimed = require_store.markerOf(known.description);
1665
+ if (claimed && claimed !== marker) throw new ProjectNotOwned(known.name, known.projectId, identity.key, claimed);
1666
+ return {
1667
+ projectId: known.projectId,
1668
+ name: known.name,
1669
+ description: known.description ?? null,
1670
+ environments: known.environments ?? [],
1671
+ via: "state",
1672
+ needsClaim: !claimed
1673
+ };
1674
+ }
1675
+ }
1676
+ const projects = await api.listProjects();
1677
+ const owned = projects.find((p) => p.name.toLowerCase() === name.toLowerCase() && require_store.isOwnedBy(p.description, identity));
1678
+ if (owned) {
1679
+ const details = await api.getProject(owned.projectId);
1680
+ return {
1681
+ projectId: owned.projectId,
1682
+ name: owned.name,
1683
+ description: owned.description ?? null,
1684
+ environments: details.environments ?? [],
1685
+ via: "marker",
1686
+ needsClaim: false
1687
+ };
1688
+ }
1689
+ const clash = projects.find((p) => p.name.toLowerCase() === name.toLowerCase());
1690
+ if (clash) throw new ProjectNotOwned(clash.name, clash.projectId, identity.key, require_store.markerOf(clash.description));
1691
+ return null;
1692
+ }
1693
+ /**
1694
+ * The project this deploy deploys into: the one {@link findProject} finds —
1695
+ * claimed with this identity's marker if it carries none yet, so the next
1696
+ * deploy without state still finds it — or a new one, marked.
1697
+ */
1698
+ async function resolveProject(api, identity, stateProjectId, log = () => {}, hooks = {}) {
1699
+ const marker = require_store.ownershipMarker(identity);
1700
+ const found = await findProject(api, identity, stateProjectId);
1701
+ if (found) {
1702
+ if (found.needsClaim) {
1703
+ await api.updateProject(found.projectId, {
1704
+ name: found.name,
1705
+ description: withMarker(found.description, marker)
1706
+ });
1707
+ log(` Claimed project ${found.name} for ${identity.key}`);
1708
+ }
1709
+ return {
1710
+ projectId: found.projectId,
1711
+ name: found.name,
1712
+ environments: found.environments,
1713
+ via: found.via
1714
+ };
1715
+ }
1716
+ await hooks.beforeCreate?.();
1717
+ const created = await api.createProject(require_store.projectName(identity), withMarker("Deployed by gkm.", marker));
1718
+ return {
1719
+ projectId: created.project.projectId,
1720
+ name: created.project.name,
1721
+ environments: [created.environment],
1722
+ via: "created"
1723
+ };
1724
+ }
1725
+ //#endregion
1726
+ //#region src/deploy/registry.ts
1727
+ /**
1728
+ * Which Dokploy registry a stage's images are pulled through.
1729
+ *
1730
+ * It used to be one id stored per machine (`~/.gkm/credentials.json`), and
1731
+ * when that was empty, the first registry Dokploy listed — so an image could be
1732
+ * deployed with credentials for a registry nobody chose, and two workspaces
1733
+ * deployed from one machine shared whichever was stored last. The id is now
1734
+ * kept in the stage's state, and found only from what the workspace
1735
+ * configured.
1736
+ */
1737
+ /** There is nowhere to push images to, so Dokploy has nothing to pull. */
1738
+ var RegistryNotConfigured = class extends Error {
1739
+ stage;
1740
+ constructor(stage) {
1741
+ super(`Deploying '${stage}' needs a container registry: Dokploy pulls each app's image from one. Set deploy.dokploy.registry in gkm.config.ts (e.g. 'ghcr.io/acme'), and deploy.dokploy.registryId if Dokploy already holds that registry's credentials.`);
1742
+ this.stage = stage;
1743
+ this.name = "RegistryNotConfigured";
1744
+ }
1745
+ };
1746
+ /** `deploy.dokploy.registryId` names a registry Dokploy does not have. */
1747
+ var RegistryNotFound = class extends Error {
1748
+ registryId;
1749
+ constructor(registryId) {
1750
+ super(`deploy.dokploy.registryId '${registryId}' is not a registry on this Dokploy server. Find the right id under Settings → Docker Registry in Dokploy and set it in gkm.config.ts, or remove it to have deploy find the registry by its URL.`);
1751
+ this.registryId = registryId;
1752
+ this.name = "RegistryNotFound";
1753
+ }
1754
+ };
1755
+ /** More than one Dokploy registry serves the configured registry. */
1756
+ var RegistryAmbiguous = class extends Error {
1757
+ registry;
1758
+ registryIds;
1759
+ constructor(registry, registryIds) {
1760
+ super(`Dokploy has ${registryIds.length} registries for '${registry}' (${registryIds.join(", ")}). Set deploy.dokploy.registryId in gkm.config.ts to the one this workspace pushes with.`);
1761
+ this.registry = registry;
1762
+ this.registryIds = registryIds;
1763
+ this.name = "RegistryAmbiguous";
1764
+ }
1765
+ };
1766
+ /** `https://ghcr.io/acme/` → `{ host: 'ghcr.io', path: 'acme' }`. */
1767
+ function parts(url) {
1768
+ const [host = "", ...path] = url.replace(/^[a-z]+:\/\//i, "").replace(/\/+$/, "").toLowerCase().split("/");
1769
+ return {
1770
+ host,
1771
+ path: path.join("/")
1772
+ };
1773
+ }
1774
+ /**
1775
+ * The Dokploy registries that serve `registry`: the same host, and — where
1776
+ * Dokploy's own entry names one — the same path.
1777
+ */
1778
+ function serving(registries, registry) {
1779
+ const wanted = parts(registry);
1780
+ const sameHost = registries.filter((r) => parts(r.registryUrl ?? "").host === wanted.host);
1781
+ if (sameHost.length <= 1) return sameHost;
1782
+ return sameHost.filter((r) => {
1783
+ return (parts(r.registryUrl ?? "").path || (r.imagePrefix ?? "").toLowerCase()) === wanted.path;
1784
+ });
1785
+ }
1786
+ /** `registry.one`, or `null` when Dokploy says it has no such registry. */
1787
+ async function registryById(api, registryId) {
1788
+ try {
1789
+ return await api.getRegistry(registryId) ?? null;
1790
+ } catch (error) {
1791
+ if (error instanceof require_sniffer.DokployApiError) return null;
1792
+ throw error;
1793
+ }
1794
+ }
1795
+ /**
1796
+ * The registry id for a stage, in order: the configured id, the one in the
1797
+ * stage's state, the one Dokploy has for the configured registry URL, and
1798
+ * otherwise a new one. Never a registry the workspace did not point at.
1799
+ */
1800
+ async function resolveRegistry(api, options) {
1801
+ const { stage, registry, configuredId, stateId, log = () => {} } = options;
1802
+ if (!registry) throw new RegistryNotConfigured(stage);
1803
+ if (configuredId) {
1804
+ const configured = await registryById(api, configuredId);
1805
+ if (!configured) throw new RegistryNotFound(configuredId);
1806
+ return configured;
1807
+ }
1808
+ if (stateId) {
1809
+ const known = await registryById(api, stateId);
1810
+ if (known) return known;
1811
+ log(` ⚠ The stage's registry ${stateId} no longer exists in Dokploy`);
1812
+ }
1813
+ const matches = serving(await api.listRegistries(), registry);
1814
+ if (matches.length > 1) throw new RegistryAmbiguous(registry, matches.map((r) => r.registryId));
1815
+ if (matches[0]) return matches[0];
1816
+ return options.create(registry);
1817
+ }
1818
+ //#endregion
1819
+ //#region src/deploy/secrets.ts
1820
+ /**
1821
+ * Filter secrets to only include the env vars that an app requires.
1822
+ *
1823
+ * @param stageSecrets - All secrets for the stage
1824
+ * @param sniffedEnv - The sniffed environment requirements for the app
1825
+ * @returns Filtered secrets with found/missing tracking
1826
+ */
1827
+ function filterSecretsForApp(stageSecrets, sniffedEnv) {
1828
+ const allSecrets = require_storage.toEmbeddableSecrets(stageSecrets);
1829
+ const filtered = {};
1830
+ const found = [];
1831
+ const missing = [];
1832
+ for (const key of sniffedEnv.requiredEnvVars) if (key in allSecrets) {
1833
+ filtered[key] = allSecrets[key];
1834
+ found.push(key);
1835
+ } else missing.push(key);
1836
+ return {
1837
+ appName: sniffedEnv.appName,
1838
+ secrets: filtered,
1839
+ found: found.sort(),
1840
+ missing: missing.sort()
1841
+ };
1842
+ }
1843
+ /**
1844
+ * Encrypt filtered secrets for an app.
1845
+ * Generates an ephemeral master key that should be injected into Dokploy.
1846
+ *
1847
+ * @param filteredSecrets - The filtered secrets for the app
1848
+ * @returns Encrypted payload with master key
1849
+ */
1850
+ function encryptSecretsForApp(filteredSecrets) {
1851
+ const payload = require_sniffer.encryptSecrets(filteredSecrets.secrets);
1852
+ return {
1853
+ appName: filteredSecrets.appName,
1854
+ payload,
1855
+ masterKey: payload.masterKey,
1856
+ secretCount: Object.keys(filteredSecrets.secrets).length,
1857
+ missingSecrets: filteredSecrets.missing
1858
+ };
1859
+ }
1860
+ /**
1861
+ * Filter and encrypt secrets for an app in one step.
1862
+ *
1863
+ * @param stageSecrets - All secrets for the stage
1864
+ * @param sniffedEnv - The sniffed environment requirements for the app
1865
+ * @returns Encrypted secrets with master key
1866
+ */
1867
+ function prepareSecretsForApp(stageSecrets, sniffedEnv) {
1868
+ return encryptSecretsForApp(filterSecretsForApp(stageSecrets, sniffedEnv));
1869
+ }
1870
+ /**
1871
+ * Prepare secrets for multiple apps.
1872
+ *
1873
+ * @param stageSecrets - All secrets for the stage
1874
+ * @param sniffedApps - Map of app name to sniffed environment
1875
+ * @returns Map of app name to encrypted secrets
1876
+ */
1877
+ function prepareSecretsForAllApps(stageSecrets, sniffedApps) {
1878
+ const results = /* @__PURE__ */ new Map();
1879
+ for (const [appName, sniffedEnv] of sniffedApps) if (sniffedEnv.requiredEnvVars.length > 0) {
1880
+ const encrypted = prepareSecretsForApp(stageSecrets, sniffedEnv);
1881
+ results.set(appName, encrypted);
1882
+ }
1883
+ return results;
1884
+ }
1885
+ /**
1886
+ * Generate a report on secrets preparation.
1887
+ */
1888
+ function generateSecretsReport(encryptedApps, sniffedApps) {
1889
+ const appsWithSecrets = [];
1890
+ const appsWithoutSecrets = [];
1891
+ const appsWithMissingSecrets = [];
1892
+ for (const [appName, sniffedEnv] of sniffedApps) {
1893
+ if (sniffedEnv.requiredEnvVars.length === 0) {
1894
+ appsWithoutSecrets.push(appName);
1895
+ continue;
1896
+ }
1897
+ const encrypted = encryptedApps.get(appName);
1898
+ if (encrypted) {
1899
+ appsWithSecrets.push(appName);
1900
+ if (encrypted.missingSecrets.length > 0) appsWithMissingSecrets.push({
1901
+ appName,
1902
+ missing: encrypted.missingSecrets
1903
+ });
1904
+ }
1905
+ }
1906
+ return {
1907
+ totalApps: sniffedApps.size,
1908
+ appsWithSecrets: appsWithSecrets.sort(),
1909
+ appsWithoutSecrets: appsWithoutSecrets.sort(),
1910
+ appsWithMissingSecrets
1911
+ };
1912
+ }
1913
+ //#endregion
1914
+ //#region src/deploy/terminal.ts
1915
+ /**
1916
+ * The credentials `gkm deploy` can ask a person for. CLI layer only.
1917
+ *
1918
+ * `deploy()` asks its `CredentialProvider` and stops with `MissingCredential`
1919
+ * when the answer is nothing. At a terminal, `gkm deploy` would rather ask:
1920
+ * this provider reads the environment and the stored login first, and only
1921
+ * when both are empty prompts — and stores a Dokploy login it validated, so
1922
+ * the next deploy does not ask again. With no terminal it answers nothing, and
1923
+ * the deploy says what was missing instead of waiting on a prompt nobody sees.
1924
+ */
1925
+ const logger$1 = require_discover.output;
1926
+ /** What answers a deploy prompt without a terminal. */
1927
+ const INSTEAD = "Please configure manually.";
1928
+ /** The Dokploy URL typed at the prompt is not a URL. */
1929
+ var DokployEndpointInvalid = class extends Error {
1930
+ endpoint;
1931
+ constructor(endpoint) {
1932
+ super("Invalid URL format");
1933
+ this.endpoint = endpoint;
1934
+ this.name = "DokployEndpointInvalid";
1935
+ }
1936
+ };
1937
+ /** Dokploy refused the token typed at the prompt; nothing was stored. */
1938
+ var DokployTokenRejected = class extends Error {
1939
+ endpoint;
1940
+ constructor(endpoint) {
1941
+ super("Invalid credentials. Please check your token.");
1942
+ this.endpoint = endpoint;
1943
+ this.name = "DokployTokenRejected";
1944
+ }
1945
+ };
1946
+ /** Asks the person at the terminal for what nothing else supplied. */
1947
+ function asking() {
1948
+ return { async get(asked) {
1949
+ if (!require_sniffer.canPrompt()) return void 0;
1950
+ const request = asked;
1951
+ if (request.kind === "dokploy") {
1952
+ logger$1.log("\n📋 Dokploy credentials not found. Let's set them up.");
1953
+ const endpoint = (await require_sniffer.prompt("Dokploy URL (e.g., https://dokploy.example.com): ", { instead: INSTEAD })).replace(/\/$/, "");
1954
+ try {
1955
+ new URL(endpoint);
1956
+ } catch {
1957
+ throw new DokployEndpointInvalid(endpoint);
1958
+ }
1959
+ logger$1.log(`\nGenerate a token at: ${endpoint}/settings/profile\n`);
1960
+ const token = await require_sniffer.prompt("API Token: ", {
1961
+ hidden: true,
1962
+ instead: INSTEAD
1963
+ });
1964
+ logger$1.log("\nValidating credentials...");
1965
+ if (!await require_sniffer.validateDokployToken(endpoint, token)) throw new DokployTokenRejected(endpoint);
1966
+ await require_sniffer.storeDokployCredentials(token, endpoint);
1967
+ logger$1.log("✓ Credentials saved");
1968
+ return {
1969
+ endpoint,
1970
+ token
1971
+ };
1972
+ }
1973
+ logger$1.log(` Dokploy has no registry for ${request.url}. Let's create one.`);
1974
+ return {
1975
+ username: await require_sniffer.prompt("Registry username: ", { instead: INSTEAD }),
1976
+ password: await require_sniffer.prompt("Registry password/token: ", {
1977
+ hidden: true,
1978
+ instead: INSTEAD
1979
+ })
1980
+ };
1981
+ } };
1982
+ }
1983
+ /**
1984
+ * The environment, then the stored login, then — at a terminal — the person
1985
+ * running the command.
1986
+ */
1987
+ function terminalCredentials(base = storedCredentials()) {
1988
+ return chainCredentials(base, asking());
1989
+ }
1990
+ //#endregion
1991
+ //#region src/deploy/index.ts
1992
+ /**
1993
+ * Deploy Module
1994
+ *
1995
+ * Handles deployment of GKM workspaces to various providers (Docker, Dokploy).
1996
+ *
1997
+ * ## Per-App Database Credentials
1998
+ *
1999
+ * When deploying to Dokploy with Postgres, this module creates per-app database
2000
+ * users with isolated schemas. This follows the same pattern as local dev mode
2001
+ * (docker/postgres/init.sh).
2002
+ *
2003
+ * ### How It Works
2004
+ *
2005
+ * 1. **Provisioning**: Creates Postgres service with master credentials
2006
+ * 2. **User Creation**: For each backend app that needs DATABASE_URL:
2007
+ * - Generates a unique password (stored in deploy state)
2008
+ * - Creates a database user with that password
2009
+ * - Assigns schema permissions based on app name
2010
+ * 3. **Schema Assignment**:
2011
+ * - `api` app: Uses `public` schema (shared tables)
2012
+ * - Other apps (e.g., `auth`): Get their own schema with `search_path` set
2013
+ * 4. **Environment Injection**: Each app receives its own DATABASE_URL
2014
+ *
2015
+ * ### Security
2016
+ *
2017
+ * - External Postgres port is enabled only during user creation, then disabled
2018
+ * - Each app can only access its own schema
2019
+ * - Credentials are stored in `.gkm/deploy-{stage}.json` (gitignored)
2020
+ * - Subsequent deploys reuse existing credentials from state
2021
+ *
2022
+ * ### Example Flow
2023
+ *
2024
+ * ```
2025
+ * gkm deploy --stage production
2026
+ * ├─ Create Postgres (user: postgres, db: myproject)
2027
+ * ├─ Enable external port temporarily
2028
+ * ├─ Create user "api" → public schema
2029
+ * ├─ Create user "auth" → auth schema (search_path=auth)
2030
+ * ├─ Disable external port
2031
+ * ├─ Deploy "api" with DATABASE_URL=postgresql://api:xxx@postgres:5432/myproject
2032
+ * └─ Deploy "auth" with DATABASE_URL=postgresql://auth:yyy@postgres:5432/myproject
2033
+ * ```
2034
+ *
2035
+ * @module deploy
2036
+ */
2037
+ const logger = require_discover.output;
2038
+ /**
2039
+ * Wait for Postgres to be ready to accept connections.
2040
+ *
2041
+ * Polls the Postgres server until it accepts a connection or max retries reached.
2042
+ * Used after enabling the external port to ensure the database is accessible
2043
+ * before creating users.
2044
+ *
2045
+ * @param host - The Postgres server hostname
2046
+ * @param port - The external port (typically 5432)
2047
+ * @param user - Master database user (postgres)
2048
+ * @param password - Master database password
2049
+ * @param database - Database name to connect to
2050
+ * @param maxRetries - Maximum number of connection attempts (default: 30)
2051
+ * @param retryIntervalMs - Milliseconds between retries (default: 2000)
2052
+ * @throws Error if Postgres is not ready after maxRetries
2053
+ */
2054
+ async function waitForPostgres(host, port, user, password, database, maxRetries = 30, retryIntervalMs = 2e3) {
2055
+ for (let i = 0; i < maxRetries; i++) try {
2056
+ const client = new pg.Client({
2057
+ host,
2058
+ port,
2059
+ user,
2060
+ password,
2061
+ database,
2062
+ connectionTimeoutMillis: 5e3
2063
+ });
2064
+ client.on("error", () => {});
2065
+ await client.connect();
2066
+ await client.end();
2067
+ return;
2068
+ } catch {
2069
+ if (i < maxRetries - 1) {
2070
+ logger.log(` Waiting for Postgres... (${i + 1}/${maxRetries})`);
2071
+ await new Promise((r) => setTimeout(r, retryIntervalMs));
2072
+ }
2073
+ }
2074
+ throw new PostgresNotReady(host, port, maxRetries);
2075
+ }
2076
+ /** A Postgres published for the role DDL never accepted a connection. */
2077
+ var PostgresNotReady = class extends Error {
2078
+ host;
2079
+ port;
2080
+ attempts;
2081
+ constructor(host, port, attempts) {
2082
+ super(`Postgres not ready after ${attempts} retries (${host}:${port}). Check that the port is reachable from here — a firewall in front of the server drops it silently — and deploy again.`);
2083
+ this.host = host;
2084
+ this.port = port;
2085
+ this.attempts = attempts;
2086
+ this.name = "PostgresNotReady";
2087
+ }
2088
+ };
2089
+ /** No port could be published for a cluster, so its DDL cannot reach it. */
2090
+ var PostgresPortUnavailable = class extends Error {
2091
+ appName;
2092
+ taken;
2093
+ constructor(appName, taken) {
2094
+ super(`Could not publish a port for ${appName}. In use on this server: ${[...taken].sort((a, b) => a - b).join(", ") || "none reported"}. The role DDL needs to reach the cluster from here.`);
2095
+ this.appName = appName;
2096
+ this.taken = taken;
2097
+ this.name = "PostgresPortUnavailable";
2098
+ }
2099
+ };
2100
+ /**
2101
+ * Run the manifest's DDL against a Dokploy Postgres.
2102
+ *
2103
+ * The cluster is only reachable from outside while an external port is
2104
+ * published, so this opens one, applies, and leaves it as it found it. The
2105
+ * alternative — running DDL from inside the network — needs a container to run
2106
+ * it in, which is what `DatabaseBootstrap` is on AWS and what a Dokploy target
2107
+ * has no equivalent for yet.
2108
+ *
2109
+ * The applier is the local target's, so every statement asks whether it is
2110
+ * needed first: a redeploy is free, and a half-applied run recovers by being
2111
+ * run again.
2112
+ */
2113
+ /**
2114
+ * A high port for one service, the same one every time.
2115
+ *
2116
+ * Derived from the service name rather than random so two deploys of the same
2117
+ * database agree and two different databases do not collide — and in the
2118
+ * ephemeral range, above anything a server is likely to have bound
2119
+ * deliberately.
2120
+ */
2121
+ function derivedPort(appName) {
2122
+ const digest = (0, node_crypto.createHash)("sha256").update(appName).digest();
2123
+ return 49152 + (digest[0] << 8 | digest[1]) % 16e3;
2124
+ }
2125
+ async function applyDeclaredStatements(api, postgres, serverHostname, statements) {
2126
+ let externalPort = await api.getPostgres(postgres.postgresId).then((current) => current.externalPort).catch(() => null) ?? void 0;
2127
+ const opened = externalPort === void 0;
2128
+ if (externalPort === void 0) {
2129
+ const taken = await api.publishedPorts().catch(() => /* @__PURE__ */ new Set());
2130
+ const candidates = [5432, derivedPort(postgres.appName)].filter((port) => !taken.has(port));
2131
+ for (const candidate of candidates) try {
2132
+ await api.savePostgresExternalPort(postgres.postgresId, candidate);
2133
+ externalPort = candidate;
2134
+ break;
2135
+ } catch (error) {
2136
+ if (!(error instanceof Error ? error.message : String(error)).includes("already in use")) throw error;
2137
+ logger.log(` Port ${candidate} is taken; trying another...`);
2138
+ }
2139
+ if (externalPort === void 0) throw new PostgresPortUnavailable(postgres.appName, [...taken]);
2140
+ logger.log(` Publishing ${postgres.appName} on ${externalPort}...`);
2141
+ }
2142
+ await api.deployPostgres(postgres.postgresId);
2143
+ await waitForPostgres(serverHostname, externalPort, postgres.databaseUser, postgres.databasePassword, postgres.databaseName);
2144
+ const client = { async query(database, sql, values) {
2145
+ const connection = new pg.Client({
2146
+ host: serverHostname,
2147
+ port: externalPort,
2148
+ user: postgres.databaseUser,
2149
+ password: postgres.databasePassword,
2150
+ database: database ?? postgres.databaseName,
2151
+ connectionTimeoutMillis: 15e3
2152
+ });
2153
+ connection.on("error", () => {});
2154
+ await connection.connect();
2155
+ try {
2156
+ return (await connection.query(sql, values)).rows;
2157
+ } finally {
2158
+ await connection.end();
2159
+ }
2160
+ } };
2161
+ const unpublish = async () => {
2162
+ if (!opened) return;
2163
+ await api.savePostgresExternalPort(postgres.postgresId, null).then(() => api.deployPostgres(postgres.postgresId)).catch(() => {
2164
+ logger.log(` ⚠ Could not close external port ${externalPort} on ${postgres.appName} — close it in Dokploy.`);
2165
+ });
2166
+ };
2167
+ let lastError;
2168
+ try {
2169
+ for (let attempt = 1; attempt <= 3; attempt++) try {
2170
+ return await applyDeclared(client, statements);
2171
+ } catch (error) {
2172
+ lastError = error;
2173
+ if (attempt === 3) break;
2174
+ const message = error instanceof Error ? error.message : String(error);
2175
+ logger.log(` ⏳ Cluster still settling (${message}); retrying (${attempt}/2)...`);
2176
+ await new Promise((resolve) => setTimeout(resolve, 1e4));
2177
+ await waitForPostgres(serverHostname, externalPort, postgres.databaseUser, postgres.databasePassword, postgres.databaseName).catch(() => {});
2178
+ }
2179
+ throw lastError;
2180
+ } finally {
2181
+ await unpublish();
2182
+ }
2183
+ }
2184
+ /**
2185
+ * Get the server hostname from the Dokploy endpoint URL
2186
+ */
2187
+ function getServerHostname(endpoint) {
2188
+ return new URL(endpoint).hostname;
2189
+ }
2190
+ /**
2191
+ * Generate image tag from stage and timestamp
2192
+ */
2193
+ function generateTag(stage) {
2194
+ return `${stage}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
2195
+ }
2196
+ /**
2197
+ * The things this deploy creates a container for.
2198
+ *
2199
+ * A deploy unit is a *declaration*, not a config entry — and since that is now
2200
+ * true of every app, not just the ones being deployed, this is the workspace's
2201
+ * own derivation under the name the deploy phases call it by.
2202
+ */
2203
+ function deployUnits(manifest, workspace) {
2204
+ return require_config.derivedApps(manifest, workspace);
2205
+ }
2206
+ /**
2207
+ * The variables an app cannot start without.
2208
+ *
2209
+ * The sniffer reports every key it saw in `requiredEnvVars` and says which of
2210
+ * them were read through `.optional()` or `.default()` in `optionalEnvVars`.
2211
+ * Reading only the first treats a key that is *absent by design* as a missing
2212
+ * secret — `AUTH_COOKIE_DOMAIN` is published only when a surface has a domain
2213
+ * to widen a cookie to, and one host has nothing to share it with.
2214
+ *
2215
+ * The same distinction `bundleServer` draws. It is drawn twice because the
2216
+ * bundle and the deploy each validate, and the deploy was the half still
2217
+ * failing on an answer that was correct.
2218
+ */
2219
+ function requiredOf(requirements) {
2220
+ if (!requirements) return [];
2221
+ const optional = new Set(requirements.optionalEnvVars);
2222
+ return requirements.requiredEnvVars.map((name) => name.endsWith("?") ? name.slice(0, -1) : name).filter((name) => !optional.has(name));
2223
+ }
2224
+ /** Apps were asked for by name that the workspace does not have. */
2225
+ var UnknownDeployApps = class extends Error {
2226
+ apps;
2227
+ available;
2228
+ constructor(apps, available) {
2229
+ super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
2230
+ this.apps = apps;
2231
+ this.available = available;
2232
+ this.name = "UnknownDeployApps";
2233
+ }
2234
+ };
2235
+ /** Every app asked for deploys somewhere other than Dokploy. */
2236
+ var NoDeployableApps = class extends Error {
2237
+ stage;
2238
+ constructor(stage) {
2239
+ super("No apps to deploy. All selected apps have unsupported deploy targets.");
2240
+ this.stage = stage;
2241
+ this.name = "NoDeployableApps";
2242
+ }
2243
+ };
2244
+ /** A backend failed, so the run stopped before deploying anything after it. */
2245
+ var BackendDeployFailed = class extends Error {
2246
+ app;
2247
+ constructor(app, cause) {
2248
+ super(`Backend deployment failed for ${app}. Aborting to prevent partial deployment.`, { cause });
2249
+ this.app = app;
2250
+ this.name = "BackendDeployFailed";
2251
+ }
2252
+ };
2253
+ /** An app's environment needs values the stage does not have. */
2254
+ var MissingEnvVars = class extends Error {
2255
+ app;
2256
+ missing;
2257
+ stage;
2258
+ constructor(app, missing, stage) {
2259
+ super(formatMissingVarsError(app, [...missing], stage));
2260
+ this.app = app;
2261
+ this.missing = missing;
2262
+ this.stage = stage;
2263
+ this.name = "MissingEnvVars";
2264
+ }
2265
+ };
2266
+ /** Workspace deploys go to Dokploy; another provider was asked for. */
2267
+ var DeployProviderUnsupported = class extends Error {
2268
+ provider;
2269
+ constructor(provider) {
2270
+ super(`Workspace deployment only supports Dokploy. Got: ${provider}`);
2271
+ this.provider = provider;
2272
+ this.name = "DeployProviderUnsupported";
2273
+ }
2274
+ };
2275
+ /** How `resolveProject` found a project, in the journal's words. */
2276
+ const PROJECT_VIA = {
2277
+ state: "recorded",
2278
+ marker: "found",
2279
+ created: "created"
2280
+ };
2281
+ /**
2282
+ * Deploy every app in a workspace to Dokploy.
2283
+ *
2284
+ * Two-phase orchestration:
2285
+ * - PHASE 1: Deploy backend apps (with encrypted secrets)
2286
+ * - PHASE 2: Deploy frontend apps (with public URLs from backends)
2287
+ *
2288
+ * Security model:
2289
+ * - Backend apps get encrypted secrets embedded at build time
2290
+ * - Only GKM_MASTER_KEY is injected as Dokploy env var
2291
+ * - Frontend apps get public URLs baked in at build time (no secrets)
2292
+ *
2293
+ * The engine under `deploy()` and `gkm deploy`. It never prompts and never
2294
+ * exits: credentials come from `ctx.credentials`, progress goes to
2295
+ * `ctx.emit` and to `output`, and every failure is thrown.
2296
+ *
2297
+ * @internal
2298
+ */
2299
+ async function runDeploy(source, request, ctx) {
2300
+ const { stage, tag, apps: selectedApps } = request;
2301
+ ctx.emit({
2302
+ type: "phase.started",
2303
+ phase: "validate"
2304
+ });
2305
+ const configured = typeof source === "function" ? await source() : source;
2306
+ const manifest = await require_discover.discover({
2307
+ patterns: require_sniffer.constructGlobs(configured),
2308
+ cwd: configured.root
2309
+ });
2310
+ const units = deployUnits(manifest, configured);
2311
+ const workspace = Object.keys(units).length > 0 ? {
2312
+ ...configured,
2313
+ apps: units
2314
+ } : configured;
2315
+ const identity = require_store.deployIdentity(workspace, stage);
2316
+ logger.log(`\n🚀 Deploying workspace "${workspace.name}" to Dokploy...`);
2317
+ logger.log(` Stage: ${stage}`);
2318
+ const imageTag = tag ?? generateTag(stage);
2319
+ logger.log(` Tag: ${imageTag}`);
2320
+ const buildOrder = require_workspace.getAppBuildOrder(workspace);
2321
+ let appsToDeployNames = buildOrder;
2322
+ if (selectedApps && selectedApps.length > 0) {
2323
+ const invalidApps = selectedApps.filter((name) => !workspace.apps[name]);
2324
+ if (invalidApps.length > 0) throw new UnknownDeployApps(invalidApps, Object.keys(workspace.apps));
2325
+ appsToDeployNames = buildOrder.filter((name) => selectedApps.includes(name));
2326
+ logger.log(` Deploying apps: ${appsToDeployNames.join(", ")}`);
2327
+ } else logger.log(` Deploying all apps: ${appsToDeployNames.join(", ")}`);
2328
+ const skipped = [];
2329
+ const skip = (app, reason) => {
2330
+ skipped.push({
2331
+ app,
2332
+ reason
2333
+ });
2334
+ ctx.emit({
2335
+ type: "app.skipped",
2336
+ app,
2337
+ reason
2338
+ });
2339
+ };
2340
+ const dokployApps = appsToDeployNames.filter((name) => {
2341
+ const target = workspace.apps[name].resolvedDeployTarget;
2342
+ if (target === "sst") {
2343
+ const reason = `it deploys with SST — run \`gkm build && sst deploy --stage ${stage}\``;
2344
+ logger.log(` ⚠️ Skipping ${name}: ${reason}`);
2345
+ skip(name, reason);
2346
+ return false;
2347
+ }
2348
+ if (!require_workspace.isDeployTargetSupported(target)) {
2349
+ const reason = require_workspace.getDeployTargetError(target, name);
2350
+ logger.log(` ⚠️ Skipping ${name}: ${reason}`);
2351
+ skip(name, reason);
2352
+ return false;
2353
+ }
2354
+ return true;
2355
+ });
2356
+ if (dokployApps.length === 0) throw new NoDeployableApps(stage);
2357
+ appsToDeployNames = dokployApps;
2358
+ for (const name of appsToDeployNames) if (workspace.apps[name].type === "mobile") skip(name, MOBILE_SKIP_REASON);
2359
+ ctx.emit({
2360
+ type: "deploy.started",
2361
+ stage,
2362
+ identity: identity.key,
2363
+ tag: imageTag,
2364
+ apps: appsToDeployNames.filter((name) => workspace.apps[name].type !== "mobile"),
2365
+ dryRun: ctx.dryRun
2366
+ });
2367
+ const store = await require_sniffer.createStateStore({
2368
+ config: workspace.state,
2369
+ workspaceRoot: workspace.root,
2370
+ workspaceName: workspace.name
2371
+ });
2372
+ const run = {
2373
+ workspace,
2374
+ manifest,
2375
+ stage,
2376
+ imageTag,
2377
+ appsToDeployNames,
2378
+ identity,
2379
+ store,
2380
+ skipped,
2381
+ ctx
2382
+ };
2383
+ if (ctx.dryRun) return planDeploy(run);
2384
+ const lock = await store.lock(stage, { operation: "deploy" });
2385
+ try {
2386
+ return await deployLocked(run);
2387
+ } finally {
2388
+ await lock.release();
2389
+ }
2390
+ }
2391
+ /**
2392
+ * The stage's secrets and every app's environment requirements. A dry run
2393
+ * reads the secrets and generates nothing into the store.
2394
+ */
2395
+ async function preflight({ workspace, manifest, stage, ctx }) {
2396
+ logger.log("\n🔐 Loading secrets and analyzing environment requirements...");
2397
+ const secretsStore = await require_store.secretsStoreFor(workspace, stage, { ...ctx.home ? { home: ctx.home } : {} });
2398
+ const stored = await secretsStore.read(stage);
2399
+ if (!stored) logger.log(` ⚠️ No secrets found for stage "${stage}"; starting them`);
2400
+ const { secrets: stageSecrets, generated } = require_sniffer.withGeneratedSecrets(stored ?? require_storage.initStageSecrets(stage), manifest);
2401
+ if (generated.length > 0) {
2402
+ if (ctx.dryRun) logger.log(` 🔑 Would generate for "${stage}" (${secretsStore.name}): ${generated.join(", ")}`);
2403
+ else {
2404
+ await secretsStore.write(stage, stageSecrets);
2405
+ logger.log(` 🔑 Generated for "${stage}" (${secretsStore.name}): ${generated.join(", ")}`);
2406
+ }
2407
+ }
2408
+ const sniffedApps = await require_sniffer.sniffAllApps(workspace.apps, workspace.root);
2409
+ const encryptedSecrets = stageSecrets ? prepareSecretsForAllApps(stageSecrets, sniffedApps) : /* @__PURE__ */ new Map();
2410
+ if (stageSecrets) {
2411
+ const report = generateSecretsReport(encryptedSecrets, sniffedApps);
2412
+ if (report.appsWithSecrets.length > 0) logger.log(` ✓ Encrypted secrets for: ${report.appsWithSecrets.join(", ")}`);
2413
+ if (report.appsWithMissingSecrets.length > 0) for (const { appName, missing } of report.appsWithMissingSecrets) logger.log(` ⚠️ ${appName}: Missing secrets: ${missing.join(", ")}`);
2414
+ }
2415
+ return {
2416
+ stageSecrets,
2417
+ sniffedApps,
2418
+ encryptedSecrets
2419
+ };
2420
+ }
2421
+ /** Everything a deploy does while it holds the stage's lock. */
2422
+ async function deployLocked(run) {
2423
+ const { workspace, manifest, stage, imageTag, appsToDeployNames, identity, store, ctx } = run;
2424
+ const { stageSecrets, sniffedApps, encryptedSecrets } = await preflight(run);
2425
+ ctx.emit({
2426
+ type: "phase.finished",
2427
+ phase: "validate"
2428
+ });
2429
+ const changes = [];
2430
+ const applied = (change, via) => {
2431
+ changes.push(change);
2432
+ ctx.emit({
2433
+ type: "resource.applied",
2434
+ ...change,
2435
+ via
2436
+ });
2437
+ };
2438
+ ctx.signal?.throwIfAborted();
2439
+ ctx.emit({
2440
+ type: "phase.started",
2441
+ phase: "provision"
2442
+ });
2443
+ const { api, endpoint } = await dokployApi(workspace, ctx);
2444
+ logger.log("\n📋 Loading deploy state...");
2445
+ const journal = await DeployJournal.open(store, stage, () => require_sniffer.createEmptyState(stage, "", ""));
2446
+ const state = journal.state;
2447
+ if (journal.existed) logger.log(` Found existing state for stage "${stage}"`);
2448
+ else logger.log(` Creating new state for stage "${stage}"`);
2449
+ const unfinished = journal.unfinished();
2450
+ if (unfinished.length > 0) logger.log(` ⚠ A previous run stopped while creating: ${unfinished.join(", ")} — looking for them before creating anything`);
2451
+ logger.log("\n📁 Setting up Dokploy project...");
2452
+ logger.log(` Identity: ${identity.key}`);
2453
+ const projectEntry = {
2454
+ key: "project",
2455
+ type: "project",
2456
+ data: {
2457
+ name: require_store.projectName(identity),
2458
+ identity: identity.key
2459
+ }
2460
+ };
2461
+ const project = await resolveProject(api, identity, state.projectId || void 0, (message) => logger.log(message), { beforeCreate: () => journal.pending(projectEntry) });
2462
+ await journal.ready(projectEntry, project.projectId);
2463
+ applied({
2464
+ key: "project",
2465
+ resourceType: "project",
2466
+ action: project.via === "created" ? "create" : "reuse",
2467
+ id: project.projectId
2468
+ }, PROJECT_VIA[project.via]);
2469
+ if (project.via === "created") logger.log(` ✓ Created project: ${project.projectId}`);
2470
+ else logger.log(` Found existing project: ${project.name}`);
2471
+ const environmentEntry = {
2472
+ key: "environment",
2473
+ type: "environment",
2474
+ data: { name: stage }
2475
+ };
2476
+ const environment = await journal.ensure(environmentEntry, {
2477
+ find: async () => project.environments.find((e) => e.name.toLowerCase() === stage.toLowerCase()),
2478
+ create: () => {
2479
+ logger.log(` Creating "${stage}" environment...`);
2480
+ return api.createEnvironment(project.projectId, stage);
2481
+ },
2482
+ id: (e) => e.environmentId
2483
+ });
2484
+ const environmentId = environment.resource.environmentId;
2485
+ applied({
2486
+ key: "environment",
2487
+ resourceType: "environment",
2488
+ action: environment.via === "created" ? "create" : "reuse",
2489
+ id: environmentId
2490
+ }, environment.via);
2491
+ if (environment.via === "created") logger.log(` ✓ Created environment: ${stage}`);
2492
+ else logger.log(` Using environment: ${environment.resource.name}`);
2493
+ if (journal.existed) {
2494
+ if (state.projectId && state.projectId !== project.projectId) logger.log(` ⚠ Project ID changed, updating state`);
2495
+ if (state.environmentId && state.environmentId !== environmentId) logger.log(` ⚠ Environment ID changed, updating state`);
2496
+ }
2497
+ state.projectId = project.projectId;
2498
+ state.environmentId = environmentId;
2499
+ state.identity = identity.key;
2500
+ logger.log("\n🐳 Checking registry...");
2501
+ const registry = workspace.deploy.dokploy?.registry;
2502
+ let registryCreated = false;
2503
+ const dokployRegistry = await resolveRegistry(api, {
2504
+ stage,
2505
+ registry,
2506
+ configuredId: workspace.deploy.dokploy?.registryId,
2507
+ stateId: state.registryId,
2508
+ log: (message) => logger.log(message),
2509
+ create: async (url) => {
2510
+ const login = await ctx.credentials.get({
2511
+ kind: "registry",
2512
+ url
2513
+ }, { signal: ctx.signal });
2514
+ if (!login) throw new MissingCredential("registry", url);
2515
+ const created = await api.createRegistry("Default Registry", url, login.username, login.password);
2516
+ registryCreated = true;
2517
+ logger.log(` ✓ Registry created: ${created.registryId}`);
2518
+ return created;
2519
+ }
2520
+ });
2521
+ const registryId = dokployRegistry.registryId;
2522
+ state.registryId = registryId;
2523
+ applied({
2524
+ key: "registry",
2525
+ resourceType: "registry",
2526
+ action: registryCreated ? "create" : "reuse",
2527
+ id: registryId
2528
+ }, registryCreated ? "created" : "found");
2529
+ logger.log(` Using registry: ${dokployRegistry.registryName}`);
2530
+ await journal.save();
2531
+ const skippedMobileApps = appsToDeployNames.filter((name) => workspace.apps[name].type === "mobile");
2532
+ if (skippedMobileApps.length > 0) logger.log(`\n📱 Skipping ${skippedMobileApps.length} mobile app(s) — deploy via framework toolchain: ${skippedMobileApps.join(", ")}`);
2533
+ let declaredEnv = {};
2534
+ let declaredClusters = {};
2535
+ {
2536
+ logger.log("\n📦 Provisioning declared constructs...");
2537
+ const appUrls = {};
2538
+ for (const appName of appsToDeployNames) {
2539
+ if (workspace.apps[appName]?.type !== "backend") continue;
2540
+ appUrls[appName] = `https://${hostOf(workspace, appName, stage)}`;
2541
+ }
2542
+ const declared = await provisionDeclared({
2543
+ api,
2544
+ workspace,
2545
+ projectId: project.projectId,
2546
+ environmentId,
2547
+ stage,
2548
+ scope: identity.scope,
2549
+ appUrls,
2550
+ supplied: stageSecrets.custom,
2551
+ seed: stageSecrets.seed,
2552
+ manifest
2553
+ });
2554
+ declaredEnv = declared.env;
2555
+ declaredClusters = declared.clusters;
2556
+ if (Object.keys(declaredEnv).length > 0) logger.log(` 🔌 Resolved ${Object.keys(declaredEnv).length} declared URL(s)`);
2557
+ if (declared.statements.length > 0) {
2558
+ const serverHostname = getServerHostname(endpoint);
2559
+ for (const [databaseName, cluster] of Object.entries(declared.clusters)) {
2560
+ const statements = declared.statements.filter((statement) => statement.database === databaseName);
2561
+ if (statements.length === 0) continue;
2562
+ const created = await applyDeclaredStatements(api, cluster, serverHostname, statements);
2563
+ logger.log(` 🗄️ ${databaseName}: applied ${statements.length} statement(s), ${created} new`);
2564
+ }
2565
+ }
2566
+ }
2567
+ const backupCluster = Object.values(declaredClusters)[0];
2568
+ if (workspace.deploy?.backups && backupCluster) {
2569
+ logger.log("\n💾 Provisioning backup destination...");
2570
+ const { provisionBackupDestination } = await Promise.resolve().then(() => require("./backup-provisioner-BmhIO_Yr.cjs"));
2571
+ const backupState = await provisionBackupDestination({
2572
+ api,
2573
+ projectId: project.projectId,
2574
+ projectName: identity.scope,
2575
+ stage,
2576
+ config: workspace.deploy.backups,
2577
+ existingState: require_sniffer.getBackupState(state),
2578
+ logger
2579
+ });
2580
+ require_sniffer.setBackupState(state, backupState);
2581
+ if (!backupState.postgresBackupId) {
2582
+ const backupSchedule = workspace.deploy.backups.schedule ?? "0 2 * * *";
2583
+ const backupRetention = workspace.deploy.backups.retention ?? 30;
2584
+ logger.log(" Creating postgres backup schedule...");
2585
+ const backup = await api.createPostgresBackup({
2586
+ schedule: backupSchedule,
2587
+ prefix: `${stage}/postgres`,
2588
+ destinationId: backupState.destinationId,
2589
+ database: backupCluster.databaseName,
2590
+ postgresId: backupCluster.postgresId,
2591
+ enabled: true,
2592
+ keepLatestCount: backupRetention
2593
+ });
2594
+ require_sniffer.setPostgresBackupId(state, backup.backupId);
2595
+ logger.log(` ✓ Postgres backup schedule created (${backupSchedule})`);
2596
+ } else logger.log(" ✓ Using existing postgres backup schedule");
2597
+ }
2598
+ ctx.emit({
2599
+ type: "phase.finished",
2600
+ phase: "provision"
2601
+ });
2602
+ const backendApps = appsToDeployNames.filter((name) => workspace.apps[name].type === "backend");
2603
+ const frontendApps = appsToDeployNames.filter((name) => workspace.apps[name].type === "web");
2604
+ const publicUrls = {};
2605
+ const results = [];
2606
+ const appHostnames = /* @__PURE__ */ new Map();
2607
+ const appDomainIds = /* @__PURE__ */ new Map();
2608
+ /** An app is up: say so, and remember where. */
2609
+ const deployed = (appName, result, host) => {
2610
+ const url = `https://${host}`;
2611
+ results.push({
2612
+ ...result,
2613
+ success: true,
2614
+ url
2615
+ });
2616
+ ctx.emit({
2617
+ type: "app.deployed",
2618
+ app: appName,
2619
+ applicationId: result.applicationId,
2620
+ imageRef: result.imageRef,
2621
+ url
2622
+ });
2623
+ };
2624
+ /** An app failed: say so, and record it in the result. */
2625
+ const failed = (appName, app, error) => {
2626
+ const message = error instanceof Error ? error.message : "Unknown error";
2627
+ logger.log(` ✗ Failed to deploy ${appName}: ${message}`);
2628
+ results.push({
2629
+ appName,
2630
+ type: app.type,
2631
+ success: false,
2632
+ error: message
2633
+ });
2634
+ ctx.emit({
2635
+ type: "app.failed",
2636
+ app: appName,
2637
+ error: eventError(error)
2638
+ });
2639
+ };
2640
+ /** An image is pushed: worth keeping even if what follows fails. */
2641
+ const built = async (appName, image, ref) => {
2642
+ require_sniffer.setDeployedImage(state, appName, {
2643
+ ref: image.imageRef ?? ref,
2644
+ ...image.digest ? { digest: image.digest } : {}
2645
+ });
2646
+ await journal.save();
2647
+ ctx.emit({
2648
+ type: "artifact.built",
2649
+ app: appName,
2650
+ imageRef: image.imageRef ?? ref,
2651
+ ...image.digest ? { digest: image.digest } : {}
2652
+ });
2653
+ changes.push({
2654
+ key: `image:${appName}`,
2655
+ resourceType: "image",
2656
+ action: "build",
2657
+ id: image.digest ?? image.imageRef ?? ref
2658
+ });
2659
+ };
2660
+ const frontendUrls = [];
2661
+ for (const appName of frontendApps) frontendUrls.push(`https://${hostOf(workspace, appName, stage)}`);
2662
+ ctx.signal?.throwIfAborted();
2663
+ ctx.emit({
2664
+ type: "phase.started",
2665
+ phase: "release"
2666
+ });
2667
+ if (backendApps.length > 0) {
2668
+ logger.log("\n📦 PHASE 1: Deploying backend applications...");
2669
+ for (const appName of backendApps) {
2670
+ ctx.signal?.throwIfAborted();
2671
+ const app = workspace.apps[appName];
2672
+ logger.log(`\n ⚙️ Deploying ${appName}...`);
2673
+ try {
2674
+ const application = await ensureApplication(api, journal, appName, require_store.applicationName(identity, appName), project.projectId, environmentId, applied);
2675
+ const appSecrets = encryptedSecrets.get(appName);
2676
+ const credentials = appSecrets && appSecrets.secretCount > 0 ? {
2677
+ encrypted: appSecrets.payload.encrypted,
2678
+ iv: appSecrets.payload.iv
2679
+ } : void 0;
2680
+ if (appSecrets && credentials) logger.log(` Encrypted ${appSecrets.secretCount} secrets`);
2681
+ const imageRef$1 = require_store.imageRef(identity, appName, registry, imageTag);
2682
+ logger.log(` Building Docker image: ${imageRef$1}`);
2683
+ const image = await deployDocker({
2684
+ stage,
2685
+ tag: imageTag,
2686
+ skipPush: false,
2687
+ config: {
2688
+ registry,
2689
+ imageName: require_store.imageName(identity, appName),
2690
+ appName
2691
+ },
2692
+ credentials,
2693
+ ...dockerRun(workspace, app, ctx)
2694
+ });
2695
+ await built(appName, image, imageRef$1);
2696
+ const backendHost = hostOf(workspace, appName, stage);
2697
+ const dependencyUrls = {};
2698
+ if (app.dependencies) {
2699
+ for (const dep of app.dependencies) if (publicUrls[dep]) dependencyUrls[dep] = publicUrls[dep];
2700
+ }
2701
+ const envContext = {
2702
+ app,
2703
+ appName,
2704
+ stage,
2705
+ state,
2706
+ appHostname: backendHost,
2707
+ frontendUrls,
2708
+ userSecrets: stageSecrets ?? void 0,
2709
+ masterKey: appSecrets?.masterKey,
2710
+ dependencyUrls
2711
+ };
2712
+ const sniffedVars = requiredOf(sniffedApps.get(appName));
2713
+ const { valid, missing, resolved } = validateEnvVars([.../* @__PURE__ */ new Set([
2714
+ "PORT",
2715
+ "NODE_ENV",
2716
+ "STAGE",
2717
+ ...sniffedVars
2718
+ ])], envContext);
2719
+ if (!valid) throw new MissingEnvVars(appName, missing, stage);
2720
+ const withDeclared = {
2721
+ ...resolved,
2722
+ ...declaredEnv
2723
+ };
2724
+ const envVars = Object.entries(withDeclared).map(([key, value]) => `${key}=${value}`);
2725
+ if (Object.keys(withDeclared).length > 0) logger.log(` Resolved ${Object.keys(withDeclared).length} env vars: ${Object.keys(withDeclared).sort().join(", ")}`);
2726
+ await api.saveDockerProvider(application.applicationId, imageRef$1, { registryId });
2727
+ await api.saveApplicationEnv(application.applicationId, envVars.join("\n"));
2728
+ logger.log(` Deploying to Dokploy...`);
2729
+ await api.deployApplication(application.applicationId);
2730
+ const domainId = await ensureDomain(api, journal, backendHost, app.port, application.applicationId, applied);
2731
+ appHostnames.set(appName, backendHost);
2732
+ if (domainId) appDomainIds.set(appName, domainId);
2733
+ publicUrls[appName] = `https://${backendHost}`;
2734
+ deployed(appName, {
2735
+ appName,
2736
+ type: app.type,
2737
+ applicationId: application.applicationId,
2738
+ imageRef: imageRef$1,
2739
+ ...image.digest ? { digest: image.digest } : {}
2740
+ }, backendHost);
2741
+ logger.log(` ✓ ${appName} deployed successfully`);
2742
+ } catch (error) {
2743
+ if (ctx.signal?.aborted) throw ctx.signal.reason;
2744
+ failed(appName, app, error);
2745
+ throw new BackendDeployFailed(appName, error);
2746
+ }
2747
+ }
2748
+ }
2749
+ if (frontendApps.length > 0) {
2750
+ logger.log("\n🌐 PHASE 2: Deploying frontend applications...");
2751
+ for (const appName of frontendApps) {
2752
+ ctx.signal?.throwIfAborted();
2753
+ const app = workspace.apps[appName];
2754
+ logger.log(`\n 🌐 Deploying ${appName}...`);
2755
+ try {
2756
+ const application = await ensureApplication(api, journal, appName, require_store.applicationName(identity, appName), project.projectId, environmentId, applied);
2757
+ const dependencyUrls = {};
2758
+ if (app.dependencies) {
2759
+ for (const dep of app.dependencies) if (publicUrls[dep]) dependencyUrls[dep] = publicUrls[dep];
2760
+ }
2761
+ const frontendHost = hostOf(workspace, appName, stage);
2762
+ const envContext = {
2763
+ app,
2764
+ appName,
2765
+ stage,
2766
+ state,
2767
+ appHostname: frontendHost,
2768
+ frontendUrls: [],
2769
+ userSecrets: stageSecrets ?? void 0,
2770
+ dependencyUrls
2771
+ };
2772
+ const { valid, missing, resolved } = validateEnvVars(requiredOf(sniffedApps.get(appName)), envContext);
2773
+ if (!valid) throw new MissingEnvVars(appName, missing, stage);
2774
+ if (Object.keys(resolved).length > 0) logger.log(` Resolved ${Object.keys(resolved).length} env vars: ${Object.keys(resolved).join(", ")}`);
2775
+ const publicPrefix = require_workspace.getPublicEnvPrefix(app.framework);
2776
+ const buildArgs = [];
2777
+ const publicUrlArgNames = [];
2778
+ if (publicPrefix) {
2779
+ for (const [key, value] of Object.entries(resolved)) if (key.startsWith(publicPrefix)) {
2780
+ buildArgs.push(`${key}=${value}`);
2781
+ publicUrlArgNames.push(key);
2782
+ }
2783
+ }
2784
+ if (buildArgs.length > 0) logger.log(` Build args: ${publicUrlArgNames.join(", ")}`);
2785
+ const imageRef$2 = require_store.imageRef(identity, appName, registry, imageTag);
2786
+ logger.log(` Building Docker image: ${imageRef$2}`);
2787
+ const image = await deployDocker({
2788
+ stage,
2789
+ tag: imageTag,
2790
+ skipPush: false,
2791
+ config: {
2792
+ registry,
2793
+ imageName: require_store.imageName(identity, appName),
2794
+ appName
2795
+ },
2796
+ buildArgs,
2797
+ publicUrlArgs: publicUrlArgNames,
2798
+ ...dockerRun(workspace, app, ctx)
2799
+ });
2800
+ await built(appName, image, imageRef$2);
2801
+ const envVars = [
2802
+ `NODE_ENV=production`,
2803
+ `PORT=${app.port}`,
2804
+ `STAGE=${stage}`
2805
+ ];
2806
+ for (const [key, value] of Object.entries(resolved)) envVars.push(`${key}=${value}`);
2807
+ await api.saveDockerProvider(application.applicationId, imageRef$2, { registryId });
2808
+ await api.saveApplicationEnv(application.applicationId, envVars.join("\n"));
2809
+ logger.log(` Deploying to Dokploy...`);
2810
+ await api.deployApplication(application.applicationId);
2811
+ const domainId = await ensureDomain(api, journal, frontendHost, app.port, application.applicationId, applied);
2812
+ appHostnames.set(appName, frontendHost);
2813
+ if (domainId) appDomainIds.set(appName, domainId);
2814
+ publicUrls[appName] = `https://${frontendHost}`;
2815
+ deployed(appName, {
2816
+ appName,
2817
+ type: app.type,
2818
+ applicationId: application.applicationId,
2819
+ imageRef: imageRef$2,
2820
+ ...image.digest ? { digest: image.digest } : {}
2821
+ }, frontendHost);
2822
+ logger.log(` ✓ ${appName} deployed successfully`);
2823
+ } catch (error) {
2824
+ if (ctx.signal?.aborted) throw ctx.signal.reason;
2825
+ failed(appName, app, error);
2826
+ }
2827
+ }
2828
+ }
2829
+ logger.log("\n📋 Saving deploy state...");
2830
+ await journal.save();
2831
+ logger.log(" ✓ State saved");
2832
+ ctx.emit({
2833
+ type: "phase.finished",
2834
+ phase: "release"
2835
+ });
2836
+ ctx.signal?.throwIfAborted();
2837
+ ctx.emit({
2838
+ type: "phase.started",
2839
+ phase: "verify"
2840
+ });
2841
+ const dnsConfig = workspace.deploy.dns;
2842
+ if (dnsConfig && appHostnames.size > 0) {
2843
+ const dnsResult = await orchestrateDns(appHostnames, dnsConfig, endpoint);
2844
+ if (dnsResult?.serverIp && appHostnames.size > 0) {
2845
+ await verifyDnsRecords(appHostnames, dnsResult.serverIp, state);
2846
+ await journal.save();
2847
+ }
2848
+ if (dnsResult?.success && appHostnames.size > 0) {
2849
+ logger.log("\n🔒 Validating domains for SSL certificates...");
2850
+ for (const [appName, hostname] of appHostnames) try {
2851
+ const result = await api.validateDomain(hostname);
2852
+ if (result.isValid) logger.log(` ✓ ${appName}: ${hostname} → ${result.resolvedIp}`);
2853
+ else logger.log(` ⚠ ${appName}: ${hostname} not valid`);
2854
+ } catch (validationError) {
2855
+ const message = validationError instanceof Error ? validationError.message : "Unknown error";
2856
+ logger.log(` ⚠ ${appName}: validation failed - ${message}`);
2857
+ }
2858
+ }
2859
+ }
2860
+ ctx.emit({
2861
+ type: "phase.finished",
2862
+ phase: "verify"
2863
+ });
2864
+ const successCount = results.filter((r) => r.success).length;
2865
+ const failedCount = results.filter((r) => !r.success).length;
2866
+ logger.log(`\n${"─".repeat(50)}`);
2867
+ logger.log(`\n✅ Workspace deployment complete!`);
2868
+ logger.log(` Project: ${project.projectId}`);
2869
+ logger.log(` Successful: ${successCount}`);
2870
+ if (failedCount > 0) logger.log(` Failed: ${failedCount}`);
2871
+ if (Object.keys(publicUrls).length > 0) {
2872
+ logger.log("\n 📡 Deployed URLs:");
2873
+ for (const [name, url] of Object.entries(publicUrls)) logger.log(` ${name}: ${url}`);
2874
+ }
2875
+ return {
2876
+ apps: results,
2877
+ projectId: project.projectId,
2878
+ environmentId,
2879
+ successCount,
2880
+ failedCount,
2881
+ stage,
2882
+ identity: identity.key,
2883
+ tag: imageTag,
2884
+ dryRun: false,
2885
+ skipped: run.skipped,
2886
+ urls: publicUrls,
2887
+ changes
2888
+ };
2889
+ }
2890
+ /**
2891
+ * An app's Dokploy application, through the journal: by the id recorded for
2892
+ * it, else by its name in the stage's environment, else created. Its id goes
2893
+ * into `state.applications` too, which the env resolver and `state:show` read.
2894
+ */
2895
+ async function ensureApplication(api, journal, appName, dokployAppName, projectId, environmentId, applied) {
2896
+ const recorded = journal.record(`application:${appName}`);
2897
+ if (recorded?.status === "ready" && recorded.id) logger.log(` Using cached ID: ${recorded.id}`);
2898
+ const { resource, via, staleId } = await journal.ensure({
2899
+ key: `application:${appName}`,
2900
+ type: "application",
2901
+ data: { name: dokployAppName }
2902
+ }, {
2903
+ get: (id) => api.getApplication(id),
2904
+ find: () => api.findApplicationByName(projectId, dokployAppName, environmentId),
2905
+ create: () => api.createApplication(dokployAppName, projectId, environmentId),
2906
+ id: (application) => application.applicationId
2907
+ });
2908
+ if (staleId) logger.log(` ⚠ Cached ID invalid, will create new`);
2909
+ logger.log(` ${{
2910
+ recorded: "✓ Application found",
2911
+ resumed: "Resumed application a stopped run created",
2912
+ found: "Found existing application",
2913
+ created: "Created application"
2914
+ }[via]}: ${resource.applicationId}`);
2915
+ applied({
2916
+ key: `application:${appName}`,
2917
+ resourceType: "application",
2918
+ action: via === "created" ? "create" : "reuse",
2919
+ id: resource.applicationId
2920
+ }, via);
2921
+ require_sniffer.setApplicationId(journal.state, appName, resource.applicationId);
2922
+ return resource;
2923
+ }
2924
+ /**
2925
+ * The domain `host` routes to an application, through the journal — found on
2926
+ * the application before it is created, so a re-run never adds a second.
2927
+ *
2928
+ * A domain that cannot be created is reported and skipped rather than
2929
+ * failing the app: the application is deployed and reachable on Dokploy's
2930
+ * own address, and DNS is fixed by hand more easily than a half deploy.
2931
+ */
2932
+ async function ensureDomain(api, journal, host, port, applicationId, applied) {
2933
+ try {
2934
+ const { resource, via } = await journal.ensure({
2935
+ key: `domain:${host}`,
2936
+ type: "domain",
2937
+ data: {
2938
+ host,
2939
+ applicationId
2940
+ }
2941
+ }, {
2942
+ find: async () => (await api.getDomainsByApplicationId(applicationId)).find((d) => d.host === host),
2943
+ create: () => api.createDomain({
2944
+ host,
2945
+ port,
2946
+ https: true,
2947
+ certificateType: "letsencrypt",
2948
+ applicationId
2949
+ }),
2950
+ id: (domain) => domain.domainId
2951
+ });
2952
+ logger.log(` ✓ Domain: https://${host} (${via === "created" ? "created" : "existing"})`);
2953
+ applied({
2954
+ key: `domain:${host}`,
2955
+ resourceType: "domain",
2956
+ action: via === "created" ? "create" : "reuse",
2957
+ id: resource.domainId
2958
+ }, via);
2959
+ return resource.domainId;
2960
+ } catch (domainError) {
2961
+ if (domainError instanceof require_sniffer.StateVersionConflict || domainError instanceof require_sniffer.StateStoreBusy || isAbort(domainError)) throw domainError;
2962
+ const message = domainError instanceof Error ? domainError.message : "Unknown error";
2963
+ logger.log(` ⚠ Domain creation failed: ${message}`);
2964
+ return;
2965
+ }
2966
+ }
2967
+ /** Whether `error` is a run being stopped rather than something failing. */
2968
+ function isAbort(error) {
2969
+ return error instanceof Error && error.name === "AbortError";
2970
+ }
2971
+ /** Where docker runs for one app: in the app's own directory. */
2972
+ function dockerRun(workspace, app, ctx) {
2973
+ return {
2974
+ cwd: (0, node_path.resolve)(workspace.root, app.path),
2975
+ ...ctx.signal ? { signal: ctx.signal } : {},
2976
+ ...ctx.stdio ? { stdio: ctx.stdio } : {}
2977
+ };
2978
+ }
2979
+ /** The Dokploy login, from the run's provider, or `MissingCredential`. */
2980
+ async function dokployApi(workspace, ctx) {
2981
+ const configured = workspace.deploy.dokploy?.endpoint;
2982
+ const creds = await ctx.credentials.get({
2983
+ kind: "dokploy",
2984
+ ...configured ? { endpoint: configured } : {}
2985
+ }, { signal: ctx.signal });
2986
+ if (!creds) throw new MissingCredential("dokploy", configured);
2987
+ return {
2988
+ api: new require_sniffer.DokployApi({
2989
+ baseUrl: creds.endpoint,
2990
+ token: creds.token,
2991
+ ...ctx.signal ? { signal: ctx.signal } : {}
2992
+ }),
2993
+ endpoint: creds.endpoint
2994
+ };
2995
+ }
2996
+ /** Each app's public host, the same way the deploy resolves it. */
2997
+ function hostOf(workspace, appName, stage) {
2998
+ const app = workspace.apps[appName];
2999
+ return require_sniffer.resolveHost(appName, app, stage, workspace.deploy?.domains, app.type === "web" && require_sniffer.isMainFrontendApp(appName, app, workspace.apps));
3000
+ }
3001
+ /**
3002
+ * What a deploy would do, from the same lookups it starts with — and nothing
3003
+ * else: no lock, no state written, no secret generated, no Dokploy resource
3004
+ * created or changed, no image built or pushed.
3005
+ */
3006
+ async function planDeploy(run) {
3007
+ const { workspace, manifest, stage, imageTag, appsToDeployNames, identity } = run;
3008
+ const { ctx } = run;
3009
+ await preflight(run);
3010
+ ctx.emit({
3011
+ type: "phase.finished",
3012
+ phase: "validate"
3013
+ });
3014
+ ctx.signal?.throwIfAborted();
3015
+ ctx.emit({
3016
+ type: "phase.started",
3017
+ phase: "plan"
3018
+ });
3019
+ logger.log("\n🔎 Dry run: nothing will be created, changed, built or pushed.");
3020
+ const changes = [];
3021
+ const plan = (change, detail) => {
3022
+ changes.push(change);
3023
+ ctx.emit({
3024
+ type: "resource.planned",
3025
+ ...change
3026
+ });
3027
+ const sign = change.action === "reuse" ? "=" : "+";
3028
+ logger.log(` ${sign} ${change.action} ${change.key} (${detail})`);
3029
+ };
3030
+ const { api } = await dokployApi(workspace, ctx);
3031
+ const state = (await run.store.read(stage))?.state;
3032
+ const project = await findProject(api, identity, state?.projectId);
3033
+ if (project) plan({
3034
+ key: "project",
3035
+ resourceType: "project",
3036
+ action: "reuse",
3037
+ id: project.projectId
3038
+ }, project.needsClaim ? `${project.name}, would be claimed for ${identity.key}` : project.name);
3039
+ else plan({
3040
+ key: "project",
3041
+ resourceType: "project",
3042
+ action: "create"
3043
+ }, require_store.projectName(identity));
3044
+ const environment = project?.environments.find((e) => e.name.toLowerCase() === stage.toLowerCase());
3045
+ plan(environment ? {
3046
+ key: "environment",
3047
+ resourceType: "environment",
3048
+ action: "reuse",
3049
+ id: environment.environmentId
3050
+ } : {
3051
+ key: "environment",
3052
+ resourceType: "environment",
3053
+ action: "create"
3054
+ }, stage);
3055
+ let registryPlanned;
3056
+ const registry = await resolveRegistry(api, {
3057
+ stage,
3058
+ registry: workspace.deploy.dokploy?.registry,
3059
+ configuredId: workspace.deploy.dokploy?.registryId,
3060
+ stateId: state?.registryId,
3061
+ log: (message) => logger.log(message),
3062
+ create: async (url) => {
3063
+ registryPlanned = {
3064
+ key: "registry",
3065
+ resourceType: "registry",
3066
+ action: "create"
3067
+ };
3068
+ return {
3069
+ registryId: "",
3070
+ registryName: url
3071
+ };
3072
+ }
3073
+ });
3074
+ plan(registryPlanned ?? {
3075
+ key: "registry",
3076
+ resourceType: "registry",
3077
+ action: "reuse",
3078
+ id: registry.registryId
3079
+ }, registry.registryName);
3080
+ for (const [id, declaration] of Object.entries(manifest)) plan({
3081
+ key: `construct:${id}`,
3082
+ resourceType: declaration.kind,
3083
+ action: "ensure"
3084
+ }, declaration.kind);
3085
+ const apps = [];
3086
+ const urls = {};
3087
+ for (const appName of appsToDeployNames) {
3088
+ const app = workspace.apps[appName];
3089
+ if (app.type === "mobile") continue;
3090
+ const dokployAppName = require_store.applicationName(identity, appName);
3091
+ const recordedId = state?.applications?.[appName];
3092
+ const existing = project && environment ? (recordedId ? await api.getApplication(recordedId).catch(() => null) : null) ?? await api.findApplicationByName(project.projectId, dokployAppName, environment.environmentId) : null;
3093
+ plan(existing ? {
3094
+ key: `application:${appName}`,
3095
+ resourceType: "application",
3096
+ action: "reuse",
3097
+ id: existing.applicationId
3098
+ } : {
3099
+ key: `application:${appName}`,
3100
+ resourceType: "application",
3101
+ action: "create"
3102
+ }, dokployAppName);
3103
+ const ref = require_store.imageRef(identity, appName, workspace.deploy.dokploy?.registry, imageTag);
3104
+ plan({
3105
+ key: `image:${appName}`,
3106
+ resourceType: "image",
3107
+ action: "build"
3108
+ }, ref);
3109
+ const host = hostOf(workspace, appName, stage);
3110
+ const domain = existing ? (await api.getDomainsByApplicationId(existing.applicationId)).find((d) => d.host === host) : void 0;
3111
+ plan(domain ? {
3112
+ key: `domain:${host}`,
3113
+ resourceType: "domain",
3114
+ action: "reuse",
3115
+ id: domain.domainId
3116
+ } : {
3117
+ key: `domain:${host}`,
3118
+ resourceType: "domain",
3119
+ action: "create"
3120
+ }, `https://${host}`);
3121
+ urls[appName] = `https://${host}`;
3122
+ apps.push({
3123
+ appName,
3124
+ type: app.type,
3125
+ success: true,
3126
+ imageRef: ref,
3127
+ url: urls[appName],
3128
+ ...existing ? { applicationId: existing.applicationId } : {}
3129
+ });
3130
+ }
3131
+ const creates = changes.filter((c) => c.action !== "reuse").length;
3132
+ logger.log(`\n✅ Dry run complete: ${creates} to create or build, ${changes.length - creates} to reuse.`);
3133
+ ctx.emit({
3134
+ type: "phase.finished",
3135
+ phase: "plan"
3136
+ });
3137
+ return {
3138
+ apps,
3139
+ projectId: project?.projectId ?? "",
3140
+ environmentId: environment?.environmentId ?? "",
3141
+ successCount: apps.length,
3142
+ failedCount: 0,
3143
+ stage,
3144
+ identity: identity.key,
3145
+ tag: imageTag,
3146
+ dryRun: true,
3147
+ skipped: run.skipped,
3148
+ urls,
3149
+ changes
3150
+ };
3151
+ }
3152
+ /** Why a mobile app is left out of a Dokploy deploy. */
3153
+ const MOBILE_SKIP_REASON = "deploys via its framework toolchain";
3154
+ //#endregion
3155
+ //#region src/deploy/deploy.ts
3156
+ /**
3157
+ * `deploy()`: a deploy as a library call.
3158
+ *
3159
+ * `gkm deploy` could only be driven from an interactive terminal: it prompted
3160
+ * for what it lacked and exited the process on failure, worked out of
3161
+ * `process.cwd()`, and reported progress by printing. Here the caller says
3162
+ * where the project is, hands over the credentials and a signal, and gets back
3163
+ * a run — events to iterate while it goes, and a structured result at the end.
3164
+ * Nothing below this asks a person anything or ends the process; `gkm deploy`
3165
+ * is a thin wrapper that does both.
3166
+ */
3167
+ /**
3168
+ * Every event a run emits, kept so that each iteration — however late it
3169
+ * starts — sees the run from its first event to its last.
3170
+ */
3171
+ var EventLog = class {
3172
+ events = [];
3173
+ closed = false;
3174
+ waiting = [];
3175
+ push(event) {
3176
+ this.events.push(event);
3177
+ this.wake();
3178
+ }
3179
+ close() {
3180
+ this.closed = true;
3181
+ this.wake();
3182
+ }
3183
+ wake() {
3184
+ const waiting = this.waiting;
3185
+ this.waiting = [];
3186
+ for (const resume of waiting) resume();
3187
+ }
3188
+ async *iterate() {
3189
+ let next = 0;
3190
+ while (true) if (next < this.events.length) yield this.events[next++];
3191
+ else if (this.closed) return;
3192
+ else await new Promise((resume) => this.waiting.push(resume));
3193
+ }
3194
+ };
3195
+ /** `childOutput` as `spawn` reads it, where it is not the default. */
3196
+ const CHILD_STDIO = {
3197
+ stderr: [
3198
+ "ignore",
3199
+ 2,
3200
+ 2
3201
+ ],
3202
+ ignore: "ignore"
3203
+ };
3204
+ function forward(logger, level, message) {
3205
+ if (!logger) return;
3206
+ if (level === "info") logger.info(message);
3207
+ else if (level === "error" && logger.error) logger.error(message);
3208
+ else logger.warn(message);
3209
+ }
3210
+ /**
3211
+ * Deploy a project's stage.
3212
+ *
3213
+ * ```ts
3214
+ * import { deploy } from '@geekmidas/cli/deploy';
3215
+ *
3216
+ * const run = deploy({ cwd: '/srv/checkouts/shop', stage: 'production' });
3217
+ * for await (const event of run) {
3218
+ * if (event.type === 'app.deployed') console.log(event.app, event.url);
3219
+ * }
3220
+ * const result = await run.result;
3221
+ * ```
3222
+ *
3223
+ * The run starts at once; iterating it is optional, and an iteration started
3224
+ * late still sees every event from the first.
3225
+ */
3226
+ function deploy(input) {
3227
+ const log = new EventLog();
3228
+ const emit = (event) => {
3229
+ log.push(event);
3230
+ if (event.type === "log") forward(input.logger, event.level, event.message);
3231
+ };
3232
+ const ctx = {
3233
+ emit,
3234
+ credentials: input.credentials ?? storedCredentials({ home: input.home ?? require_home.gkmHome() }),
3235
+ dryRun: input.dryRun ?? false,
3236
+ home: input.home ?? require_home.gkmHome(),
3237
+ ...input.signal ? { signal: input.signal } : {},
3238
+ ...input.childOutput && input.childOutput !== "inherit" ? { stdio: CHILD_STDIO[input.childOutput] } : {}
3239
+ };
3240
+ const result = require_discover.withOutput((level, message) => emit({
3241
+ type: "log",
3242
+ level,
3243
+ message
3244
+ }), async () => {
3245
+ try {
3246
+ input.signal?.throwIfAborted();
3247
+ const deployed = await runDeploy(() => load(input), {
3248
+ stage: input.stage,
3249
+ ...input.tag ? { tag: input.tag } : {},
3250
+ ...input.apps ? { apps: input.apps } : {}
3251
+ }, ctx);
3252
+ emit({
3253
+ type: "deploy.finished",
3254
+ result: deployed
3255
+ });
3256
+ return deployed;
3257
+ } catch (error) {
3258
+ emit({
3259
+ type: "deploy.failed",
3260
+ error: eventError(error)
3261
+ });
3262
+ throw error;
3263
+ } finally {
3264
+ log.close();
3265
+ }
3266
+ });
3267
+ result.catch(() => {});
3268
+ return {
3269
+ result,
3270
+ [Symbol.asyncIterator]: () => log.iterate()
3271
+ };
3272
+ }
3273
+ /** The workspace at `input.cwd`, refusing a stage it does not deploy. */
3274
+ async function load(input) {
3275
+ const { workspace } = await require_config.loadWorkspaceConfig((0, node_path.resolve)(input.cwd));
3276
+ require_workspace.assertDeployedStage(workspace.stages, input.stage);
3277
+ return workspace;
3278
+ }
3279
+ //#endregion
3280
+ Object.defineProperty(exports, "BackendDeployFailed", {
3281
+ enumerable: true,
3282
+ get: function() {
3283
+ return BackendDeployFailed;
3284
+ }
3285
+ });
3286
+ Object.defineProperty(exports, "DeployProviderUnsupported", {
3287
+ enumerable: true,
3288
+ get: function() {
3289
+ return DeployProviderUnsupported;
3290
+ }
3291
+ });
3292
+ Object.defineProperty(exports, "MissingCredential", {
3293
+ enumerable: true,
3294
+ get: function() {
3295
+ return MissingCredential;
3296
+ }
3297
+ });
3298
+ Object.defineProperty(exports, "MissingEnvVars", {
3299
+ enumerable: true,
3300
+ get: function() {
3301
+ return MissingEnvVars;
3302
+ }
3303
+ });
3304
+ Object.defineProperty(exports, "NoDeployableApps", {
3305
+ enumerable: true,
3306
+ get: function() {
3307
+ return NoDeployableApps;
3308
+ }
3309
+ });
3310
+ Object.defineProperty(exports, "ProjectNotOwned", {
3311
+ enumerable: true,
3312
+ get: function() {
3313
+ return ProjectNotOwned;
3314
+ }
3315
+ });
3316
+ Object.defineProperty(exports, "RegistryAmbiguous", {
3317
+ enumerable: true,
3318
+ get: function() {
3319
+ return RegistryAmbiguous;
3320
+ }
3321
+ });
3322
+ Object.defineProperty(exports, "RegistryNotConfigured", {
3323
+ enumerable: true,
3324
+ get: function() {
3325
+ return RegistryNotConfigured;
3326
+ }
3327
+ });
3328
+ Object.defineProperty(exports, "RegistryNotFound", {
3329
+ enumerable: true,
3330
+ get: function() {
3331
+ return RegistryNotFound;
3332
+ }
3333
+ });
3334
+ Object.defineProperty(exports, "UnknownDeployApps", {
3335
+ enumerable: true,
3336
+ get: function() {
3337
+ return UnknownDeployApps;
3338
+ }
3339
+ });
3340
+ Object.defineProperty(exports, "chainCredentials", {
3341
+ enumerable: true,
3342
+ get: function() {
3343
+ return chainCredentials;
3344
+ }
3345
+ });
3346
+ Object.defineProperty(exports, "deploy", {
3347
+ enumerable: true,
3348
+ get: function() {
3349
+ return deploy;
3350
+ }
3351
+ });
3352
+ Object.defineProperty(exports, "storedCredentials", {
3353
+ enumerable: true,
3354
+ get: function() {
3355
+ return storedCredentials;
3356
+ }
3357
+ });
3358
+ Object.defineProperty(exports, "terminalCredentials", {
3359
+ enumerable: true,
3360
+ get: function() {
3361
+ return terminalCredentials;
3362
+ }
3363
+ });
3364
+
3365
+ //# sourceMappingURL=deploy-BbJdgQ2b.cjs.map