@geekmidas/cli 10.0.0-alpha.13 → 10.0.0-alpha.131

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