@geekmidas/cli 10.0.0-alpha.141 → 10.0.0-alpha.143

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 (260) hide show
  1. package/dist/{EndpointGenerator-BMRL04ic.mjs → EndpointGenerator-CusLH-9S.mjs} +2 -2
  2. package/dist/{EndpointGenerator-BMRL04ic.mjs.map → EndpointGenerator-CusLH-9S.mjs.map} +1 -1
  3. package/dist/{EndpointGenerator-ePscnbwB.cjs → EndpointGenerator-DyLMYClE.cjs} +2 -2
  4. package/dist/{EndpointGenerator-ePscnbwB.cjs.map → EndpointGenerator-DyLMYClE.cjs.map} +1 -1
  5. package/dist/{GoDaddyProvider-DxFAueU4.mjs → GoDaddyProvider-BJddaEFo.mjs} +2 -3
  6. package/dist/{GoDaddyProvider-DxFAueU4.mjs.map → GoDaddyProvider-BJddaEFo.mjs.map} +1 -1
  7. package/dist/{GoDaddyProvider-hAc0q5s-.cjs → GoDaddyProvider-D-QrclQ0.cjs} +5 -6
  8. package/dist/{GoDaddyProvider-hAc0q5s-.cjs.map → GoDaddyProvider-D-QrclQ0.cjs.map} +1 -1
  9. package/dist/{HostingerProvider-DEqpvoiD.cjs → HostingerProvider-CUtGkwa8.cjs} +2 -2
  10. package/dist/{HostingerProvider-DEqpvoiD.cjs.map → HostingerProvider-CUtGkwa8.cjs.map} +1 -1
  11. package/dist/{HostingerProvider-CgMuKgO_.mjs → HostingerProvider-DilTLFtw.mjs} +2 -2
  12. package/dist/{HostingerProvider-CgMuKgO_.mjs.map → HostingerProvider-DilTLFtw.mjs.map} +1 -1
  13. package/dist/{LegacyStateStore-BPY8Acgs.mjs → LegacyStateStore-lZn6yeNb.mjs} +3 -3
  14. package/dist/{LegacyStateStore-BPY8Acgs.mjs.map → LegacyStateStore-lZn6yeNb.mjs.map} +1 -1
  15. package/dist/{LegacyStateStore-BqSVgWi1.cjs → LegacyStateStore-ohe95jlu.cjs} +3 -3
  16. package/dist/{LegacyStateStore-BqSVgWi1.cjs.map → LegacyStateStore-ohe95jlu.cjs.map} +1 -1
  17. package/dist/{LocalStateStore-Df4RyGi2.cjs → LocalStateStore-Bs2Yl8IB.cjs} +2 -2
  18. package/dist/{LocalStateStore-Df4RyGi2.cjs.map → LocalStateStore-Bs2Yl8IB.cjs.map} +1 -1
  19. package/dist/{LocalStateStore-5pVR26KA.mjs → LocalStateStore-CkpQ3sNu.mjs} +2 -2
  20. package/dist/{LocalStateStore-5pVR26KA.mjs.map → LocalStateStore-CkpQ3sNu.mjs.map} +1 -1
  21. package/dist/{OpenApiTsGenerator-B-PQLx8X.mjs → OpenApiTsGenerator-BTMuu1WS.mjs} +2 -2
  22. package/dist/{OpenApiTsGenerator-B-PQLx8X.mjs.map → OpenApiTsGenerator-BTMuu1WS.mjs.map} +1 -1
  23. package/dist/{OpenApiTsGenerator-BvacdbiG.cjs → OpenApiTsGenerator-CI-tceXV.cjs} +2 -2
  24. package/dist/{OpenApiTsGenerator-BvacdbiG.cjs.map → OpenApiTsGenerator-CI-tceXV.cjs.map} +1 -1
  25. package/dist/{S3StateStore-Do1DwEMX.mjs → S3StateStore-BO-TXIC9.mjs} +4 -4
  26. package/dist/{S3StateStore-Do1DwEMX.mjs.map → S3StateStore-BO-TXIC9.mjs.map} +1 -1
  27. package/dist/{S3StateStore-uykstvZI.cjs → S3StateStore-CsxqGwKX.cjs} +5 -5
  28. package/dist/{S3StateStore-uykstvZI.cjs.map → S3StateStore-CsxqGwKX.cjs.map} +1 -1
  29. package/dist/{SSMStateStore-DQXFWqkE.cjs → SSMStateStore-D85DzsxJ.cjs} +2 -2
  30. package/dist/{SSMStateStore-DQXFWqkE.cjs.map → SSMStateStore-D85DzsxJ.cjs.map} +1 -1
  31. package/dist/{SSMStateStore-xQ-Ce91W.mjs → SSMStateStore-DDNpIVIc.mjs} +2 -2
  32. package/dist/{SSMStateStore-xQ-Ce91W.mjs.map → SSMStateStore-DDNpIVIc.mjs.map} +1 -1
  33. package/dist/{SubscriberGenerator-DR4Y7ihK.cjs → SubscriberGenerator-BNJyPmXJ.cjs} +3 -3
  34. package/dist/{SubscriberGenerator-DR4Y7ihK.cjs.map → SubscriberGenerator-BNJyPmXJ.cjs.map} +1 -1
  35. package/dist/{SubscriberGenerator-DLPH-ynS.mjs → SubscriberGenerator-CzPrixYu.mjs} +3 -3
  36. package/dist/{SubscriberGenerator-DLPH-ynS.mjs.map → SubscriberGenerator-CzPrixYu.mjs.map} +1 -1
  37. package/dist/{add-DLkN488n.mjs → add-CRAhswLe.mjs} +8 -7
  38. package/dist/{add-DLkN488n.mjs.map → add-CRAhswLe.mjs.map} +1 -1
  39. package/dist/{add-Y_nPkjIf.cjs → add-DiFv_IWD.cjs} +18 -17
  40. package/dist/{add-Y_nPkjIf.cjs.map → add-DiFv_IWD.cjs.map} +1 -1
  41. package/dist/apps-CA-048eZ.cjs +5008 -0
  42. package/dist/apps-CA-048eZ.cjs.map +1 -0
  43. package/dist/apps-CZ0ydmPQ.mjs +4593 -0
  44. package/dist/apps-CZ0ydmPQ.mjs.map +1 -0
  45. package/dist/{bundler-DFyrGST-.mjs → bundler-BIsNVJnB.mjs} +6 -6
  46. package/dist/{bundler-DFyrGST-.mjs.map → bundler-BIsNVJnB.mjs.map} +1 -1
  47. package/dist/{bundler-COOvv27I.cjs → bundler-D6Y2bucc.cjs} +9 -9
  48. package/dist/{bundler-COOvv27I.cjs.map → bundler-D6Y2bucc.cjs.map} +1 -1
  49. package/dist/{cli-DKsV-Myw.cjs → cli-6xibALWU.cjs} +4 -4
  50. package/dist/{cli-DKsV-Myw.cjs.map → cli-6xibALWU.cjs.map} +1 -1
  51. package/dist/{cli-iAX4BQ3t.mjs → cli-QwhW-X12.mjs} +4 -4
  52. package/dist/{cli-iAX4BQ3t.mjs.map → cli-QwhW-X12.mjs.map} +1 -1
  53. package/dist/compose-BHsW5nDE.mjs +1554 -0
  54. package/dist/compose-BHsW5nDE.mjs.map +1 -0
  55. package/dist/compose-C4kCN2tl.cjs +1895 -0
  56. package/dist/compose-C4kCN2tl.cjs.map +1 -0
  57. package/dist/{compose-ofZIpp2q.mjs → compose-E4-ZiWev.mjs} +17 -1828
  58. package/dist/compose-E4-ZiWev.mjs.map +1 -0
  59. package/dist/{compose-CGXx22Wy.cjs → compose-S_MY__b2.cjs} +102 -1967
  60. package/dist/compose-S_MY__b2.cjs.map +1 -0
  61. package/dist/config-BKpzKP6W.mjs +659 -0
  62. package/dist/config-BKpzKP6W.mjs.map +1 -0
  63. package/dist/config-QAqAEgb0.cjs +772 -0
  64. package/dist/config-QAqAEgb0.cjs.map +1 -0
  65. package/dist/config.cjs +16 -419
  66. package/dist/config.mjs +2 -405
  67. package/dist/{credentialSchemas-DZ2Nh5li.cjs → credentialSchemas-BAklWDna.cjs} +4 -5
  68. package/dist/{credentialSchemas-DZ2Nh5li.cjs.map → credentialSchemas-BAklWDna.cjs.map} +1 -1
  69. package/dist/{credentialSchemas-DUCSYl9a.mjs → credentialSchemas-mz9QZTYh.mjs} +2 -3
  70. package/dist/{credentialSchemas-DUCSYl9a.mjs.map → credentialSchemas-mz9QZTYh.mjs.map} +1 -1
  71. package/dist/credentials-BnpIwWCS.cjs +2336 -0
  72. package/dist/credentials-BnpIwWCS.cjs.map +1 -0
  73. package/dist/credentials-zlJPxBWn.mjs +1851 -0
  74. package/dist/credentials-zlJPxBWn.mjs.map +1 -0
  75. package/dist/{databases-P824RTnx.cjs → databases-DawSdqBI.cjs} +2 -2
  76. package/dist/{databases-P824RTnx.cjs.map → databases-DawSdqBI.cjs.map} +1 -1
  77. package/dist/{databases-Db48ZIXL.mjs → databases-mzSUFBTw.mjs} +2 -2
  78. package/dist/{databases-Db48ZIXL.mjs.map → databases-mzSUFBTw.mjs.map} +1 -1
  79. package/dist/deploy/public.cjs +24 -24
  80. package/dist/deploy/public.cjs.map +1 -1
  81. package/dist/deploy/public.d.cts.map +1 -1
  82. package/dist/deploy/public.d.mts.map +1 -1
  83. package/dist/deploy/public.mjs +13 -13
  84. package/dist/{deploy-BibGpDAz.cjs → deploy-0XI_bemB.cjs} +73 -72
  85. package/dist/{deploy-BibGpDAz.cjs.map → deploy-0XI_bemB.cjs.map} +1 -1
  86. package/dist/{deploy-C4QQkHK7.mjs → deploy-DJcEAscO.mjs} +16 -15
  87. package/dist/{deploy-C4QQkHK7.mjs.map → deploy-DJcEAscO.mjs.map} +1 -1
  88. package/dist/{discover-yqeJ2Bx7.cjs → discover-CRywE7yc.cjs} +157 -6
  89. package/dist/discover-CRywE7yc.cjs.map +1 -0
  90. package/dist/{discover-B2m8ytyq.mjs → discover-DbDrCQ8h.mjs} +117 -8
  91. package/dist/discover-DbDrCQ8h.mjs.map +1 -0
  92. package/dist/docker-8gbw63RW.cjs +1514 -0
  93. package/dist/docker-8gbw63RW.cjs.map +1 -0
  94. package/dist/docker-C5w9_bWP.mjs +1407 -0
  95. package/dist/docker-C5w9_bWP.mjs.map +1 -0
  96. package/dist/{dokploy-pSrsileA.mjs → dokploy-BAjJ7MPB.mjs} +2 -2
  97. package/dist/{dokploy-pSrsileA.mjs.map → dokploy-BAjJ7MPB.mjs.map} +1 -1
  98. package/dist/{dokploy-B_VX3nLM.cjs → dokploy-DOYsnbiK.cjs} +2 -2
  99. package/dist/{dokploy-B_VX3nLM.cjs.map → dokploy-DOYsnbiK.cjs.map} +1 -1
  100. package/dist/{drivers-C47nm-wB.cjs → drivers-aM87NQJi.cjs} +4 -91
  101. package/dist/drivers-aM87NQJi.cjs.map +1 -0
  102. package/dist/{drivers-CDjpjakg.mjs → drivers-uxLBq3e3.mjs} +3 -60
  103. package/dist/drivers-uxLBq3e3.mjs.map +1 -0
  104. package/dist/{eas-cSSc8Lex.cjs → eas-Aaj9nbNp.cjs} +6 -6
  105. package/dist/{eas-cSSc8Lex.cjs.map → eas-Aaj9nbNp.cjs.map} +1 -1
  106. package/dist/{eas-Bou-_M76.mjs → eas-BpyYdquY.mjs} +3 -3
  107. package/dist/{eas-Bou-_M76.mjs.map → eas-BpyYdquY.mjs.map} +1 -1
  108. package/dist/{encryption-Bps9As2D.mjs → encryption-DYFTQaZ3.mjs} +3 -3
  109. package/dist/{encryption-Bps9As2D.mjs.map → encryption-DYFTQaZ3.mjs.map} +1 -1
  110. package/dist/{encryption-CElaAwJs.cjs → encryption-K2-9Ei8q.cjs} +6 -6
  111. package/dist/{encryption-CElaAwJs.cjs.map → encryption-K2-9Ei8q.cjs.map} +1 -1
  112. package/dist/{engine-CiG7Wfyc.cjs → engine-097i9gWA.cjs} +99 -97
  113. package/dist/{engine-CiG7Wfyc.cjs.map → engine-097i9gWA.cjs.map} +1 -1
  114. package/dist/{engine-CXE4UOHj.mjs → engine-CuFkswUS.mjs} +12 -10
  115. package/dist/{engine-CXE4UOHj.mjs.map → engine-CuFkswUS.mjs.map} +1 -1
  116. package/dist/{github-CvFJlFWA.mjs → github-DGaK_ulS.mjs} +9 -8
  117. package/dist/{github-CvFJlFWA.mjs.map → github-DGaK_ulS.mjs.map} +1 -1
  118. package/dist/{github-BzppIvpw.cjs → github-ZoKihAlP.cjs} +18 -17
  119. package/dist/{github-BzppIvpw.cjs.map → github-ZoKihAlP.cjs.map} +1 -1
  120. package/dist/{googlePlay-BJnMCWoa.cjs → googlePlay-BQ-62vre.cjs} +5 -5
  121. package/dist/{googlePlay-BJnMCWoa.cjs.map → googlePlay-BQ-62vre.cjs.map} +1 -1
  122. package/dist/{googlePlay-RSe9wOfZ.mjs → googlePlay-hw7Ej5yT.mjs} +5 -5
  123. package/dist/{googlePlay-RSe9wOfZ.mjs.map → googlePlay-hw7Ej5yT.mjs.map} +1 -1
  124. package/dist/index.cjs +196 -192
  125. package/dist/index.cjs.map +1 -1
  126. package/dist/index.mjs +70 -66
  127. package/dist/index.mjs.map +1 -1
  128. package/dist/{local-B7Zv1NoA.mjs → local-CiJfYdrA.mjs} +3 -3
  129. package/dist/{local-B7Zv1NoA.mjs.map → local-CiJfYdrA.mjs.map} +1 -1
  130. package/dist/{local-OPC9BCZt.cjs → local-iC7qJkPl.cjs} +6 -6
  131. package/dist/{local-OPC9BCZt.cjs.map → local-iC7qJkPl.cjs.map} +1 -1
  132. package/dist/{migrate-B0nQra2W.mjs → migrate-CbjB-uxl.mjs} +3 -3
  133. package/dist/{migrate-B0nQra2W.mjs.map → migrate-CbjB-uxl.mjs.map} +1 -1
  134. package/dist/{migrate-BPCJBL7_.mjs → migrate-DTTn8YcN.mjs} +7 -5
  135. package/dist/{migrate-BPCJBL7_.mjs.map → migrate-DTTn8YcN.mjs.map} +1 -1
  136. package/dist/{migrate-BCBs0BMn.cjs → migrate-p1R0CSRw.cjs} +6 -6
  137. package/dist/{migrate-BCBs0BMn.cjs.map → migrate-p1R0CSRw.cjs.map} +1 -1
  138. package/dist/{migrate-Dmh5Dbcr.cjs → migrate-wH1DmtjX.cjs} +15 -13
  139. package/dist/{migrate-Dmh5Dbcr.cjs.map → migrate-wH1DmtjX.cjs.map} +1 -1
  140. package/dist/notes-CedXKWnt.mjs +399 -0
  141. package/dist/notes-CedXKWnt.mjs.map +1 -0
  142. package/dist/notes-ChbE7v2l.cjs +500 -0
  143. package/dist/notes-ChbE7v2l.cjs.map +1 -0
  144. package/dist/openapi.cjs +4 -5
  145. package/dist/openapi.cjs.map +1 -1
  146. package/dist/openapi.mjs +3 -4
  147. package/dist/openapi.mjs.map +1 -1
  148. package/dist/{projectBucket-C_DN4WzF.mjs → projectBucket-2Bw-Qy8D.mjs} +2 -2
  149. package/dist/{projectBucket-C_DN4WzF.mjs.map → projectBucket-2Bw-Qy8D.mjs.map} +1 -1
  150. package/dist/{projectBucket-BBbQ1lHF.cjs → projectBucket-CUJYUmt2.cjs} +2 -2
  151. package/dist/{projectBucket-BBbQ1lHF.cjs.map → projectBucket-CUJYUmt2.cjs.map} +1 -1
  152. package/dist/{publish-DKy3hn8a.cjs → publish-Byi0cB2N.cjs} +2 -2
  153. package/dist/{publish-DKy3hn8a.cjs.map → publish-Byi0cB2N.cjs.map} +1 -1
  154. package/dist/{publish-cthyGGQt.mjs → publish-DDsmxwl-.mjs} +2 -2
  155. package/dist/{publish-cthyGGQt.mjs.map → publish-DDsmxwl-.mjs.map} +1 -1
  156. package/dist/{ready-DuU0FXSj.cjs → ready-BNh3zsSn.cjs} +6 -6
  157. package/dist/{ready-DuU0FXSj.cjs.map → ready-BNh3zsSn.cjs.map} +1 -1
  158. package/dist/{ready-CGqJ74Kt.mjs → ready-g25dcGzK.mjs} +6 -6
  159. package/dist/{ready-CGqJ74Kt.mjs.map → ready-g25dcGzK.mjs.map} +1 -1
  160. package/dist/reconcile/public.cjs +1 -1
  161. package/dist/reconcile/public.mjs +1 -1
  162. package/dist/{resolve-AYtMIgoq.cjs → resolve-CT6P86p3.cjs} +4 -4
  163. package/dist/{resolve-AYtMIgoq.cjs.map → resolve-CT6P86p3.cjs.map} +1 -1
  164. package/dist/{resolve-BaRqJlqV.mjs → resolve-zHOTcPk4.mjs} +4 -4
  165. package/dist/{resolve-BaRqJlqV.mjs.map → resolve-zHOTcPk4.mjs.map} +1 -1
  166. package/dist/{rollback-DqV6t9oo.mjs → rollback-CFowte36.mjs} +8 -8
  167. package/dist/{rollback-DqV6t9oo.mjs.map → rollback-CFowte36.mjs.map} +1 -1
  168. package/dist/{rollback-CQ184yFu.cjs → rollback-CYnroE_3.cjs} +11 -11
  169. package/dist/{rollback-CQ184yFu.cjs.map → rollback-CYnroE_3.cjs.map} +1 -1
  170. package/dist/{s3-BKnL6YGQ.cjs → s3-82kaV_R0.cjs} +2 -2
  171. package/dist/{s3-BKnL6YGQ.cjs.map → s3-82kaV_R0.cjs.map} +1 -1
  172. package/dist/{s3-DW7SLsb8.mjs → s3-D8u9j2C5.mjs} +2 -2
  173. package/dist/{s3-DW7SLsb8.mjs.map → s3-D8u9j2C5.mjs.map} +1 -1
  174. package/dist/sandbox/credentials-worker.cjs +3 -4
  175. package/dist/sandbox/credentials-worker.cjs.map +1 -1
  176. package/dist/sandbox/credentials-worker.mjs +2 -3
  177. package/dist/sandbox/credentials-worker.mjs.map +1 -1
  178. package/dist/sandbox/discover-worker.cjs +1 -1
  179. package/dist/sandbox/discover-worker.mjs +1 -1
  180. package/dist/sandbox/migrate-worker.cjs +3 -4
  181. package/dist/sandbox/migrate-worker.cjs.map +1 -1
  182. package/dist/sandbox/migrate-worker.mjs +2 -3
  183. package/dist/sandbox/migrate-worker.mjs.map +1 -1
  184. package/dist/seeds-B3xvUAQf.cjs +363 -0
  185. package/dist/seeds-B3xvUAQf.cjs.map +1 -0
  186. package/dist/seeds-BCC8vAXR.mjs +298 -0
  187. package/dist/seeds-BCC8vAXR.mjs.map +1 -0
  188. package/dist/{serverSetup-AfG0-at8.mjs → serverSetup-B621zgYj.mjs} +7 -6
  189. package/dist/{serverSetup-AfG0-at8.mjs.map → serverSetup-B621zgYj.mjs.map} +1 -1
  190. package/dist/{serverSetup-Dnw9Kdel.cjs → serverSetup-Cip3ZWdi.cjs} +9 -8
  191. package/dist/{serverSetup-Dnw9Kdel.cjs.map → serverSetup-Cip3ZWdi.cjs.map} +1 -1
  192. package/dist/{sniffer-BHhJ8DiC.mjs → sniffer-BO7tNCDc.mjs} +8 -9
  193. package/dist/{sniffer-BHhJ8DiC.mjs.map → sniffer-BO7tNCDc.mjs.map} +1 -1
  194. package/dist/{sniffer-taO-AXSk.cjs → sniffer-Dxwe2yS0.cjs} +9 -10
  195. package/dist/{sniffer-taO-AXSk.cjs.map → sniffer-Dxwe2yS0.cjs.map} +1 -1
  196. package/dist/{snsSubscriptions-D_IBKhni.mjs → snsSubscriptions-CZlHrll5.mjs} +4 -453
  197. package/dist/snsSubscriptions-CZlHrll5.mjs.map +1 -0
  198. package/dist/{snsSubscriptions-CC-WM1zC.cjs → snsSubscriptions-CgWY_alK.cjs} +12 -559
  199. package/dist/snsSubscriptions-CgWY_alK.cjs.map +1 -0
  200. package/dist/{sst-Bz2HJlqc.mjs → sst-CnSAHj6j.mjs} +27 -5
  201. package/dist/sst-CnSAHj6j.mjs.map +1 -0
  202. package/dist/{sst-lvCHdYsY.cjs → sst-CtOI68mi.cjs} +29 -7
  203. package/dist/sst-CtOI68mi.cjs.map +1 -0
  204. package/dist/stack-BCHFuiWH.cjs +2577 -0
  205. package/dist/stack-BCHFuiWH.cjs.map +1 -0
  206. package/dist/stack-BrcNDH_E.mjs +2348 -0
  207. package/dist/stack-BrcNDH_E.mjs.map +1 -0
  208. package/dist/{stage-dd9dtLfh.mjs → stage-BhjwFQrw.mjs} +7 -7
  209. package/dist/{stage-dd9dtLfh.mjs.map → stage-BhjwFQrw.mjs.map} +1 -1
  210. package/dist/{stage-CTibxcpA.cjs → stage-DzH_iWgO.cjs} +13 -13
  211. package/dist/{stage-CTibxcpA.cjs.map → stage-DzH_iWgO.cjs.map} +1 -1
  212. package/dist/{stages--icWbhPy.cjs → stages-CFI0OiLj.cjs} +2 -2
  213. package/dist/{stages--icWbhPy.cjs.map → stages-CFI0OiLj.cjs.map} +1 -1
  214. package/dist/{stages-CUwSy39f.mjs → stages-DoYa81kN.mjs} +2 -2
  215. package/dist/{stages-CUwSy39f.mjs.map → stages-DoYa81kN.mjs.map} +1 -1
  216. package/dist/target/public.cjs +1 -1
  217. package/dist/target/public.mjs +1 -1
  218. package/dist/{terminal-DURcYlVX.cjs → terminal-455ZtUjl.cjs} +3 -3
  219. package/dist/{terminal-DURcYlVX.cjs.map → terminal-455ZtUjl.cjs.map} +1 -1
  220. package/dist/{terminal-yOZ7kKF9.mjs → terminal-iEkwo0Bq.mjs} +3 -3
  221. package/dist/{terminal-yOZ7kKF9.mjs.map → terminal-iEkwo0Bq.mjs.map} +1 -1
  222. package/dist/types-Bl_CwZC9.cjs +90 -0
  223. package/dist/types-Bl_CwZC9.cjs.map +1 -0
  224. package/dist/types-Y1NfWlyG.mjs +61 -0
  225. package/dist/types-Y1NfWlyG.mjs.map +1 -0
  226. package/dist/vitest.cjs +1 -1
  227. package/dist/vitest.mjs +1 -1
  228. package/package.json +15 -15
  229. package/dist/compose-CGXx22Wy.cjs.map +0 -1
  230. package/dist/compose-ofZIpp2q.mjs.map +0 -1
  231. package/dist/config.cjs.map +0 -1
  232. package/dist/config.mjs.map +0 -1
  233. package/dist/credentials-D7XJypNd.cjs +0 -520
  234. package/dist/credentials-D7XJypNd.cjs.map +0 -1
  235. package/dist/credentials-DpfnUvIR.mjs +0 -395
  236. package/dist/credentials-DpfnUvIR.mjs.map +0 -1
  237. package/dist/derive-Cd7Hl3r2.mjs +0 -259
  238. package/dist/derive-Cd7Hl3r2.mjs.map +0 -1
  239. package/dist/derive-CgZfoBU2.cjs +0 -282
  240. package/dist/derive-CgZfoBU2.cjs.map +0 -1
  241. package/dist/discover-B2m8ytyq.mjs.map +0 -1
  242. package/dist/discover-yqeJ2Bx7.cjs.map +0 -1
  243. package/dist/drivers-C47nm-wB.cjs.map +0 -1
  244. package/dist/drivers-CDjpjakg.mjs.map +0 -1
  245. package/dist/identity-CBXr4wNi.mjs +0 -129
  246. package/dist/identity-CBXr4wNi.mjs.map +0 -1
  247. package/dist/identity-CbLfgQNT.cjs +0 -182
  248. package/dist/identity-CbLfgQNT.cjs.map +0 -1
  249. package/dist/sandbox-CHv3OYXg.cjs +0 -165
  250. package/dist/sandbox-CHv3OYXg.cjs.map +0 -1
  251. package/dist/sandbox-CbVB7uOD.mjs +0 -118
  252. package/dist/sandbox-CbVB7uOD.mjs.map +0 -1
  253. package/dist/seeds-DndMeyzm.cjs +0 -10669
  254. package/dist/seeds-DndMeyzm.cjs.map +0 -1
  255. package/dist/seeds-o6x6BTRo.mjs +0 -9534
  256. package/dist/seeds-o6x6BTRo.mjs.map +0 -1
  257. package/dist/snsSubscriptions-CC-WM1zC.cjs.map +0 -1
  258. package/dist/snsSubscriptions-D_IBKhni.mjs.map +0 -1
  259. package/dist/sst-Bz2HJlqc.mjs.map +0 -1
  260. package/dist/sst-lvCHdYsY.cjs.map +0 -1
@@ -0,0 +1,2348 @@
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { D as originSecretKey, O as processorOriginHost, a as findRootDomain, o as normalizeDnsConfig, rt as imageRef, w as ORIGIN_VERIFY_HEADER } from "./credentials-zlJPxBWn.mjs";
3
+ import { B as LOGS_PORT, I as otlpTelemetryEnv, L as resolveStageTelemetry, ht as checkStageBackups, lt as certificateFor, ut as proxyFor, yt as isReservedStageKey, z as telemetryEnv } from "./workspace-BbfBFtjn.mjs";
4
+ import { $ as NoDomainForStage, B as portKeys, H as postgresImage, L as DEFAULT_IMAGES, M as EMULATOR_ACCESS_KEY_ID, S as redisService, Y as logsService, Z as stackLogs, b as REDIS_SERVICE, g as postgresSuperuser, h as postgresRoleSlug, j as watchedBuckets, k as minioWebhookEnv, n as composeFor, nt as resolveHost, p as LOCAL_RABBITMQ_USER, q as LOGS_SERVICE, tt as isMainFrontendApp, w as stackRedis, x as STACK_CACHE } from "./compose-BHsW5nDE.mjs";
5
+ import { C as TURBO_VERSION, H as workerUnits, J as bucketLifecycles, Q as quoteIdentifier, R as publicBuildValues, S as PROCESSOR_PORT, V as processorUnits, Y as bucketPolicies, a as workerEnvKeys, b as composeBuildPaths, ct as scopeTelemetryEnv, dt as telemetryOf, ft as usesTelemetry, i as processorEnvKeys, it as planFor, mt as hostFor, pt as LOCAL_TLD, r as networkEnv, st as isTelemetryKey, t as appEnvKeys, tt as localRolePassword, w as WORKER_PORT } from "./apps-CZ0ydmPQ.mjs";
6
+ import { a as SNS_SUBSCRIPTIONS_KEY, c as INBOX_RELAY_TOKEN_KEY, d as inboxWebhookUrl, o as objectsRoute, s as subscriberRoute, u as inboxRelayWorker } from "./SubscriberGenerator-CzPrixYu.mjs";
7
+ import { g as appKey } from "./config-BKpzKP6W.mjs";
8
+ import { n as DEFAULT_EVENTS } from "./types-Y1NfWlyG.mjs";
9
+ import { _ as suppliedOnly, f as devServicesUsed, g as stageServiceDeclarations, i as stageProviderNotes, p as externalServices } from "./notes-CedXKWnt.mjs";
10
+ import { o as processorDockerfile, r as appDockerfile, s as workerDockerfile, v as validateImageRef } from "./docker-C5w9_bWP.mjs";
11
+ import { createRequire } from "node:module";
12
+ import { dirname, join } from "node:path";
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { createHash } from "node:crypto";
15
+ import { CLIENT_IP_HEADER, DEFAULT_POSTGRES_VERSION, WILDCARD_SUBDOMAIN, isWildcardSite, kebabCase, provideKey, provisionOrder } from "@geekmidas/manifest";
16
+ import { fileURLToPath } from "node:url";
17
+ import { stringify } from "yaml";
18
+ import bcrypt from "bcryptjs";
19
+ //#region src/providers/dns.ts
20
+ /** Whether the workspace deploys through the compose target. */
21
+ function deploysWithCompose(workspace) {
22
+ return workspace.deploy?.default === "compose" || Object.values(workspace.apps).some((app) => app.resolvedDeployTarget === "compose");
23
+ }
24
+ //#endregion
25
+ //#region src/backups/config.ts
26
+ /**
27
+ * Which stages take backups, and where they are kept.
28
+ *
29
+ * A deployed compose stage whose stack runs Postgres is backed up by
30
+ * default — every day at 02:00 UTC, kept 30 days — unless
31
+ * `deploy.backups.<stage>` says otherwise. The local stage never is.
32
+ *
33
+ * Every backup is kept in the project bucket (`providers/projectBucket.ts`),
34
+ * beside the stage's deploy state, one folder per run and one file per
35
+ * database:
36
+ *
37
+ * ```
38
+ * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/database.sql.gz
39
+ * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/auth-database.sql.gz
40
+ * ```
41
+ *
42
+ * The file is named after the database's construct, the way its migrations
43
+ * folder is: `AuthDatabase` is `db/auth-database`, and `auth-database.sql.gz`.
44
+ */
45
+ /** Whether the stack runs Postgres: some construct is a database. */
46
+ function runsPostgres(manifest) {
47
+ return Object.values(manifest).some((d) => d.kind === "database");
48
+ }
49
+ /**
50
+ * What `stage`'s backups are: on — by its entry or the default — off by
51
+ * `false`, or none, for the local stage, a stage compose does not deploy,
52
+ * and a stack with no database.
53
+ */
54
+ function stageBackups(workspace, manifest, stage) {
55
+ if (stage === workspace.stages?.local) return {
56
+ mode: "none",
57
+ reason: "local"
58
+ };
59
+ if (!deploysWithCompose(workspace)) return {
60
+ mode: "none",
61
+ reason: "not-compose"
62
+ };
63
+ if (!runsPostgres(manifest)) return {
64
+ mode: "none",
65
+ reason: "no-postgres"
66
+ };
67
+ const value = (workspace.deploy?.backups)?.[stage];
68
+ const checked = checkStageBackups(stage, value ?? {});
69
+ if (checked === false) return { mode: "disabled" };
70
+ return {
71
+ mode: "on",
72
+ backups: checked,
73
+ source: value === void 0 ? "default" : "config"
74
+ };
75
+ }
76
+ /**
77
+ * Where a stage's backups are, in the project bucket — under the same
78
+ * `<prefix>/<project>/<stage>` its deploy state is: `gkm/shop/production/backups`.
79
+ */
80
+ function backupsPrefix(workspace, stage) {
81
+ const state = workspace.state;
82
+ const prefix = state?.provider === "s3" && state.prefix !== void 0 ? state.prefix.replace(/\/+$/, "") : "gkm";
83
+ return `${prefix ? `${prefix}/` : ""}${workspace.name}/${stage}/backups`;
84
+ }
85
+ /** A run folder's time back, or `undefined` for a key that is not one. */
86
+ function runTime(folder) {
87
+ const match = /^(\d{4}-\d{2}-\d{2})\/(\d{2})-(\d{2})-(\d{2})Z$/.exec(folder);
88
+ if (!match) return void 0;
89
+ const at = /* @__PURE__ */ new Date(`${match[1]}T${match[2]}:${match[3]}:${match[4]}Z`);
90
+ return Number.isNaN(at.getTime()) ? void 0 : at;
91
+ }
92
+ /** A database's file in a run's folder: `auth-database.sql.gz`. */
93
+ function backupFile(database) {
94
+ return `${database.file}.sql.gz`;
95
+ }
96
+ /** Each database the stack runs, by its construct and its name in Postgres. */
97
+ function backupDatabases(resources) {
98
+ return resources.filter((r) => r.kind === "database").map((r) => ({
99
+ id: r.id,
100
+ file: kebabCase(r.id),
101
+ name: r.name
102
+ })).sort((a, b) => a.file.localeCompare(b.file));
103
+ }
104
+ /**
105
+ * The expiry of every stage's backups, by each stage's own entry — what the
106
+ * project bucket's lifecycle carries beside its own rule.
107
+ *
108
+ * A put replaces a bucket's whole lifecycle, so this is built from every
109
+ * deployed stage each time, never from the stage being deployed alone: one
110
+ * stage's deploy keeps every other's rule. A stage set to `false` has none,
111
+ * and its backups are kept until someone deletes them.
112
+ */
113
+ function backupExpiries(workspace, manifest) {
114
+ const expiries = [];
115
+ for (const stage of [...workspace.stages?.deployed ?? []].sort()) {
116
+ const choice = stageBackups(workspace, manifest, stage);
117
+ if (choice.mode !== "on") continue;
118
+ expiries.push({
119
+ id: `gkm-backups-${stage}`,
120
+ prefix: `${backupsPrefix(workspace, stage)}/`,
121
+ days: choice.backups.keepDays,
122
+ abortIncompleteDays: 1
123
+ });
124
+ }
125
+ return expiries;
126
+ }
127
+ //#endregion
128
+ //#region src/backups/service.ts
129
+ /**
130
+ * The stack's `backups` service: what a deployed compose stage with Postgres
131
+ * runs beside its apps, unless `deploy.backups.<stage>` is `false`.
132
+ *
133
+ * - **The image** is built from the stack's own Postgres image —
134
+ * `postgres:<major>-alpine`, already on the server for the stack, and with
135
+ * the `pg_dump` that matches the server — with Node added and gkm's runner
136
+ * (`runner.ts`) copied in. Nothing is pulled that the stack does not have,
137
+ * and nothing is mounted from the host: the build context is two files.
138
+ * - **Its key** is `BACKUPS_URL`, from the stage's secrets, like any app's:
139
+ * allowed to put objects under the stage's backups prefix and nothing else.
140
+ * The server holds no AWS credentials of its own.
141
+ * - **Its login** is a role of its own, `<project>_backups`, granted
142
+ * `pg_read_all_data` — it can read every database and write none. Postgres
143
+ * before 14 has no such role, and there it signs in as the stack's
144
+ * superuser.
145
+ * - **Its health** is the last good run: unhealthy once that is more than
146
+ * twice the schedule's longest gap old, after a startup grace.
147
+ */
148
+ /** The service's name in the stack. */
149
+ const BACKUPS_SERVICE = "backups";
150
+ /** The secret its key is written to. */
151
+ const BACKUPS_URL_KEY = "BACKUPS_URL";
152
+ /** Where the runner is, in the image. */
153
+ const RUNNER_PATH = "/gkm/backup.mjs";
154
+ /** The first Postgres with `pg_read_all_data`. */
155
+ const READ_ALL_DATA_SINCE = 14;
156
+ /** A stage that backs up, and no key to back up with. */
157
+ var BackupsUrlMissing = class extends GkmError {
158
+ stage;
159
+ constructor(stage) {
160
+ super(`'${stage}' runs Postgres, so its stack backs it up, and its secrets hold no ${BACKUPS_URL_KEY} to back up with. The deploy writes it — the IAM user and key it creates in the stage's AWS account — so run the deploy with the account's credentials. To take no backups on this stage, set deploy.backups.${stage}: false.`);
161
+ this.stage = stage;
162
+ this.name = "BackupsUrlMissing";
163
+ }
164
+ };
165
+ /** The backups role: `<project>_backups`, as the superuser is `<project>_admin`. */
166
+ function backupsRole(project) {
167
+ return `${postgresRoleSlug(project)}_backups`;
168
+ }
169
+ /**
170
+ * The runner's source, as JavaScript: the built `backups/runner.mjs` beside
171
+ * the CLI's bundle, or — run from source — `runner.ts`, with its types
172
+ * stripped by esbuild.
173
+ */
174
+ function runnerSource() {
175
+ const here = dirname(fileURLToPath(import.meta.url));
176
+ for (const path of [
177
+ join(here, "backups", "runner.mjs"),
178
+ join(here, "runner.mjs"),
179
+ join(here, "..", "backups", "runner.mjs")
180
+ ]) if (existsSync(path)) return readFileSync(path, "utf-8");
181
+ const { transformSync } = createRequire(import.meta.url)("esbuild");
182
+ return transformSync(readFileSync(join(here, "runner.ts"), "utf-8"), {
183
+ loader: "ts",
184
+ format: "esm",
185
+ target: "node22"
186
+ }).code;
187
+ }
188
+ /** The image's Dockerfile: the stack's Postgres, Node, and the runner. */
189
+ function backupsDockerfile(from) {
190
+ return `# Generated by gkm — the stage's backups: pg_dump from ${from}, and gkm's uploader.
191
+ FROM ${from}
192
+ RUN apk add --no-cache nodejs
193
+ COPY backup.mjs ${RUNNER_PATH}
194
+ USER postgres
195
+ ENTRYPOINT []
196
+ CMD ["node", "${RUNNER_PATH}", "serve"]
197
+ `;
198
+ }
199
+ /**
200
+ * The stack's backups service, for a stage whose backups are on.
201
+ *
202
+ * @throws {BackupsUrlMissing} when the stage's secrets hold no key
203
+ */
204
+ function stackBackups(input) {
205
+ const { plan, stage } = input;
206
+ const version = plan.resources.find((r) => r.version)?.version ?? DEFAULT_POSTGRES_VERSION;
207
+ const from = postgresImage(version);
208
+ const script = runnerSource();
209
+ const dockerfile = backupsDockerfile(from);
210
+ const hash = createHash("sha256").update(dockerfile).update(script).digest("hex").slice(0, 12);
211
+ const readOnly = version >= READ_ALL_DATA_SINCE;
212
+ const role = backupsRole(input.workspace.name);
213
+ const login = readOnly ? {
214
+ user: role,
215
+ password: localRolePassword(input.workspace.name, plan, role, input.seed)
216
+ } : input.superuser;
217
+ const databases = backupDatabases(plan.resources);
218
+ const prefix = backupsPrefix(input.workspace, stage);
219
+ const { kind, ...schedule } = input.backups.schedule;
220
+ let env = {};
221
+ if (!input.buildOnly) {
222
+ const url = input.custom[BACKUPS_URL_KEY];
223
+ if (!url) throw new BackupsUrlMissing(stage);
224
+ env = {
225
+ BACKUPS_URL: url,
226
+ BACKUPS_PREFIX: prefix,
227
+ BACKUPS_DATABASES: JSON.stringify(databases.map(({ file, name }) => ({
228
+ file,
229
+ name
230
+ }))),
231
+ BACKUPS_SCHEDULE: JSON.stringify(kind === "cron" ? {
232
+ kind,
233
+ minutes: input.backups.schedule.minutes,
234
+ hours: input.backups.schedule.hours,
235
+ days: input.backups.schedule.days,
236
+ months: input.backups.schedule.months,
237
+ weekdays: input.backups.schedule.weekdays
238
+ } : {
239
+ kind,
240
+ ...schedule
241
+ }),
242
+ BACKUPS_MAX_GAP_SECONDS: String(input.backups.maxGapSeconds),
243
+ PGHOST: "postgres",
244
+ PGPORT: "5432",
245
+ PGUSER: login.user,
246
+ PGPASSWORD: login.password,
247
+ ...input.telemetry?.OTEL_EXPORTER_OTLP_ENDPOINT ? {
248
+ OTEL_EXPORTER_OTLP_ENDPOINT: input.telemetry.OTEL_EXPORTER_OTLP_ENDPOINT,
249
+ ...input.telemetry.OTEL_EXPORTER_OTLP_HEADERS ? { OTEL_EXPORTER_OTLP_HEADERS: input.telemetry.OTEL_EXPORTER_OTLP_HEADERS } : {},
250
+ OTEL_SERVICE_NAME: BACKUPS_SERVICE
251
+ } : {}
252
+ };
253
+ }
254
+ return {
255
+ backups: input.backups,
256
+ databases,
257
+ prefix,
258
+ from,
259
+ image: `${input.project}-backups:pg${version}-${hash}`,
260
+ files: {
261
+ Dockerfile: dockerfile,
262
+ "backup.mjs": script
263
+ },
264
+ login,
265
+ readOnly,
266
+ env
267
+ };
268
+ }
269
+ /** The service in the stack's compose file. */
270
+ function backupsService(backups, envFiles) {
271
+ return {
272
+ image: backups.image,
273
+ build: {
274
+ context: `./${BACKUPS_SERVICE}`,
275
+ dockerfile: "Dockerfile"
276
+ },
277
+ pull_policy: "build",
278
+ restart: "unless-stopped",
279
+ ...envFiles ? { env_file: [{
280
+ path: `./${BACKUPS_SERVICE}.env`,
281
+ format: "raw"
282
+ }] } : {},
283
+ depends_on: { postgres: { condition: "service_healthy" } },
284
+ healthcheck: {
285
+ test: [
286
+ "CMD",
287
+ "node",
288
+ RUNNER_PATH,
289
+ "health"
290
+ ],
291
+ interval: "1m",
292
+ timeout: "10s",
293
+ retries: 3,
294
+ start_period: "30s"
295
+ }
296
+ };
297
+ }
298
+ /**
299
+ * The backups role, created and kept: able to sign in and read every
300
+ * database, and nothing else. None when it signs in as the superuser.
301
+ */
302
+ function backupsRoleStatements(backups) {
303
+ if (!backups.readOnly) return [];
304
+ const role = quoteIdentifier(backups.login.user);
305
+ const password = `'${backups.login.password.replace(/'/g, "''")}'`;
306
+ return [
307
+ {
308
+ id: BACKUPS_SERVICE,
309
+ describe: `role ${backups.login.user}`,
310
+ exists: {
311
+ sql: "SELECT 1 FROM pg_roles WHERE rolname = $1",
312
+ values: [backups.login.user]
313
+ },
314
+ create: `CREATE ROLE ${role} LOGIN PASSWORD ${password}`
315
+ },
316
+ {
317
+ id: BACKUPS_SERVICE,
318
+ describe: `role ${backups.login.user}: its password`,
319
+ create: `ALTER ROLE ${role} WITH LOGIN PASSWORD ${password}`
320
+ },
321
+ {
322
+ id: BACKUPS_SERVICE,
323
+ describe: `role ${backups.login.user}: read every database`,
324
+ create: `GRANT pg_read_all_data TO ${role}`
325
+ }
326
+ ];
327
+ }
328
+ //#endregion
329
+ //#region src/compose/routes.ts
330
+ /** A route with handlers and a check that would have to hold for each of them. */
331
+ var EdgeRouteConflict = class extends Error {
332
+ route;
333
+ constructor(route) {
334
+ super(`The edge route '${route}' sends some paths to other upstreams and also restricts who or what it answers. The two are not combined: give the restricted paths a host of their own.`);
335
+ this.route = route;
336
+ this.name = "EdgeRouteConflict";
337
+ }
338
+ };
339
+ /** @throws {EdgeRouteConflict} */
340
+ function assertRouteRenderable(route) {
341
+ if (route.handlers?.length && (route.allow || route.paths || route.prefixes || route.requireHeader)) throw new EdgeRouteConflict(route.name);
342
+ }
343
+ /** File descriptors a process holding sockets may open. */
344
+ const NOFILE = {
345
+ soft: 1048576,
346
+ hard: 1048576
347
+ };
348
+ /**
349
+ * What the edge runs with: a descriptor per socket, twice — the client's and
350
+ * the upstream's — and every local port for those upstream connections. One
351
+ * edge address to one upstream has only the ephemeral range to open
352
+ * connections from, ~28k by Linux's default; widened, ~64k per replica.
353
+ */
354
+ const EDGE_LIMITS = {
355
+ sysctls: { "net.ipv4.ip_local_port_range": "1024 65535" },
356
+ ulimits: { nofile: NOFILE }
357
+ };
358
+ //#endregion
359
+ //#region src/compose/caddyfile.ts
360
+ /**
361
+ * The stack's own edge, rendered for Caddy: one site block per route.
362
+ *
363
+ * Deployed, each host is the stage's real domain and Caddy gets it a
364
+ * certificate from Let's Encrypt on first request — the same automatic HTTPS
365
+ * it does anywhere, with nothing to configure but the name — or serves the
366
+ * stage's own certificate (`deploy.compose.tls`). Locally the hosts are
367
+ * `*.localhost` and the certificates come from Caddy's own CA, as the `gkm
368
+ * dev` edge does, so a local stack is `https://` like a deployed one.
369
+ *
370
+ * Pure: the routes are data (`routes.ts`), and rendering them is one string.
371
+ */
372
+ /** Where Caddy reads a stage's own certificate, inside its container. */
373
+ const CADDY_TLS_DIR = "/etc/caddy/tls";
374
+ /** An upstream on the stack's own network: its service name. */
375
+ function address({ service, port }) {
376
+ return `${service}:${port}`;
377
+ }
378
+ /** The Caddyfile for a stack's edge. */
379
+ function edgeCaddyfile(routes, options) {
380
+ const { tls } = options;
381
+ const ask = routes.find((route) => route.wildcard?.tls.kind === "on-demand")?.wildcard?.tls;
382
+ const onDemand = ask?.kind === "on-demand" ? `
383
+ on_demand_tls {
384
+ ask ${ask.ask}
385
+ }` : "";
386
+ const global = tls.kind === "internal" ? `{
387
+ # No ACME and no public DNS: the CA is Caddy's own and the names resolve
388
+ # to this machine.
389
+ local_certs
390
+ auto_https disable_redirects
391
+ }` : options.email || onDemand ? `{${options.email ? `\n\temail ${options.email}` : ""}${onDemand}
392
+ }` : "";
393
+ const certificate = tls.kind === "internal" ? `
394
+ tls internal
395
+ ` : tls.kind === "files" ? `
396
+ tls ${tls.certFile} ${tls.keyFile}
397
+ ` : "";
398
+ const blocks = [...routes.filter((route) => !route.wildcard), ...routes.filter((route) => route.wildcard)].map((route) => siteBlock(route, route.wildcard?.tls.kind === "on-demand" ? `
399
+ tls {
400
+ on_demand
401
+ }
402
+ ` : certificate));
403
+ return `${HEADER}${global ? `${global}\n\n` : ""}${blocks.join("\n\n")}\n`;
404
+ }
405
+ /** One route's site block. */
406
+ function siteBlock(route, certificate) {
407
+ assertRouteRenderable(route);
408
+ const { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;
409
+ const allowed = [...paths ?? [], ...(prefixes ?? []).map((prefix) => `${prefix}*`)];
410
+ const except = route.wildcard?.except ?? [];
411
+ const checks = `${except.length ? `
412
+ # Labels no tenant may take, although nothing in this stack answers them.
413
+ @protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(" ")}
414
+ respond @protected 404
415
+ ` : ""}${allow ? `
416
+ # Only these addresses — the peer Caddy sees, never a header a client
417
+ # could set. Everything else is refused before it reaches the upstream.
418
+ @denied not remote_ip ${allow.join(" ")}
419
+ respond @denied 403
420
+ ` : ""}${requireHeader ? `
421
+ # Only what the CDN sends: it adds this header to every request, and this
422
+ # host would be reached around the CDN otherwise.
423
+ @forged not header ${requireHeader.name} "${requireHeader.value}"
424
+ respond @forged 403
425
+ ` : ""}${auth ? `
426
+ # The stage's login, asked for before anything reaches the upstream.
427
+ basic_auth {
428
+ ${auth.user} ${auth.hash}
429
+ }
430
+ ` : ""}${allowed.length ? `
431
+ # Only these paths answer. Everything else on this host is refused before
432
+ # it reaches the upstream.
433
+ @elsewhere not path ${allowed.join(" ")}
434
+ respond @elsewhere 404
435
+ ` : ""}`;
436
+ const proxy = proxyBlock(route);
437
+ const body = handlers?.length ? `${handlers.map((handler, index) => `
438
+ # Answered by another service: ${handler.name}.
439
+ @handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(" ")}
440
+ handle @handler${index} {
441
+ reverse_proxy ${handler.upstreams.map(address).join(" ")}
442
+ }
443
+ `).join("")}
444
+ handle {${proxy.replace(/\n/g, "\n ")}
445
+ }` : proxy;
446
+ return `https://${host} {${certificate}
447
+ # gkm's own header, which only a service of this stack may send: the auth
448
+ # server rate-limits by the client address it carries.
449
+ request_header -${CLIENT_IP_HEADER}
450
+ ${checks}${body}
451
+ }`;
452
+ }
453
+ /** Where a route's requests go, when no handler took them. */
454
+ function proxyBlock({ upstreams, prefix, streaming }) {
455
+ return prefix ? `
456
+ # A bucket, served at a host of its own: the bucket is a prefix on MinIO,
457
+ # which routes and signs on the Host header — so it is sent the upstream's.
458
+ reverse_proxy ${upstreams.map(address).join(" ")} {
459
+ rewrite ${prefix}{uri}
460
+ header_up Host {upstream_hostport}
461
+ }` : `
462
+ # Host and X-Forwarded-* are passed through as Caddy does by default, so
463
+ # an app builds redirects, cookies and links on the address a caller used.
464
+ reverse_proxy ${upstreams.map(address).join(" ")}${streaming ? ` {
465
+ # Never buffer: a streamed response — server-sent events, a Next.js
466
+ # RSC payload — reaches the client as each chunk is written.
467
+ flush_interval -1
468
+ }` : ""}`;
469
+ }
470
+ const HEADER = `# Generated by gkm compose from the construct manifest — do not edit.
471
+ #
472
+ # One host per API and site, each in front of its own container, one per
473
+ # file server in front of the stack's MinIO — its processors' paths sent to
474
+ # their own service — one per worker SNS pushes to and per processor unit a
475
+ # CDN reaches, answering only those paths, and — when its logs are served
476
+ # publicly — one for OpenObserve, to the addresses it allows. A site the
477
+ # stage puts behind a password asks for its login first.
478
+ `;
479
+ //#endregion
480
+ //#region src/compose/images.ts
481
+ /**
482
+ * Which image each app runs — and, for a tag, whether every one exists.
483
+ *
484
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
485
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
486
+ * image is asked of the registry before anything is pulled or the running
487
+ * stack is touched, and one missing image stops the whole run naming every
488
+ * one that is missing. Nor is a missing image quietly built instead — a build
489
+ * of whatever is checked out here is not the release the tag names.
490
+ */
491
+ /**
492
+ * The tag a site's image carries for a release.
493
+ *
494
+ * A site's public URLs are inlined when it is built, so one bundle serves one
495
+ * stage: `v1.4.0-production` and `v1.4.0-staging` are two images of the same
496
+ * commit. A backend reads its URLs at runtime, so one image serves every stage
497
+ * and its tag is the release's alone.
498
+ */
499
+ function siteTag(tag, stage) {
500
+ return `${tag}-${stage}`;
501
+ }
502
+ /** Images a tag names that the registry does not have. */
503
+ var ImageTagNotFound = class extends GkmError {
504
+ tag;
505
+ refs;
506
+ constructor(tag, refs) {
507
+ super(`The registry has no image for ${refs.length === 1 ? "this app" : `${refs.length} apps`} at '${tag}':\n` + refs.map((ref) => ` - ${ref}`).join("\n") + `\nNothing was pulled or started. Push '${tag}' for every app from CI, pick a tag that exists, or run without --tag to build from this checkout.`);
508
+ this.tag = tag;
509
+ this.refs = refs;
510
+ this.name = "ImageTagNotFound";
511
+ }
512
+ };
513
+ /** The registry did not answer, or did not let this machine in. */
514
+ var RegistryUnreachable = class extends GkmError {
515
+ ref;
516
+ detail;
517
+ constructor(ref, detail) {
518
+ super(`Could not ask the registry about ${ref}: ${detail || "no answer"}\nNothing was pulled or started. Check the registry is reachable and that this machine is logged in to it (\`docker login <registry>\`).`);
519
+ this.ref = ref;
520
+ this.detail = detail;
521
+ this.name = "RegistryUnreachable";
522
+ }
523
+ };
524
+ /**
525
+ * Assert every image exists, before anything else happens.
526
+ *
527
+ * Asked all at once and reported all at once: a release missing two images is
528
+ * one problem with two names, and finding the second only after fixing the
529
+ * first is a slower way to learn the same thing.
530
+ *
531
+ * @throws {RegistryUnreachable} when the registry cannot say
532
+ * @throws {ImageTagNotFound} listing every missing image
533
+ */
534
+ async function assertImagesExist(docker, tag, images) {
535
+ const lookups = await Promise.all(images.map((image) => docker.lookup(image.ref)));
536
+ const unreachable = lookups.find((lookup) => lookup.status === "unreachable");
537
+ if (unreachable?.status === "unreachable") throw new RegistryUnreachable(unreachable.ref, unreachable.detail);
538
+ const missing = lookups.filter((lookup) => lookup.status === "missing").map((lookup) => lookup.ref);
539
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
540
+ }
541
+ /**
542
+ * A push or a pull with no `deploy.registry` to push to or pull from.
543
+ *
544
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
545
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
546
+ * from, somebody else's account. It is never a fallback.
547
+ */
548
+ var RegistryRequired = class extends GkmError {
549
+ operation;
550
+ ref;
551
+ constructor(operation, ref) {
552
+ super(`${operation === "push" ? "Pushing" : "Pulling"} images needs a registry, and gkm.config.ts sets no deploy.registry: '${ref}' would be ${operation === "push" ? "pushed to" : "pulled from"} Docker Hub. Set deploy.registry (e.g. registry: 'ghcr.io/acme') in gkm.config.ts.` + (operation === "pull" ? " To run images built here instead, pass --build." : ""));
553
+ this.operation = operation;
554
+ this.ref = ref;
555
+ this.name = "RegistryRequired";
556
+ }
557
+ };
558
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
559
+ function pinnedRef(ref, digest) {
560
+ return `${ref.split("@")[0]}@${digest}`;
561
+ }
562
+ /** A digests file with no entry for an app the stack runs. */
563
+ var ImageDigestMissing = class extends GkmError {
564
+ file;
565
+ apps;
566
+ constructor(file, apps) {
567
+ super(`${file} pins no digest for ${apps.join(", ")}. Use the file the same release's \`gkm compose --build --push --digests-file\` wrote, or run without --digests-file to pull by tag.`);
568
+ this.file = file;
569
+ this.apps = apps;
570
+ this.name = "ImageDigestMissing";
571
+ }
572
+ };
573
+ /** A digests file entry that is not this app's image. */
574
+ var ImageDigestMismatch = class extends GkmError {
575
+ app;
576
+ expected;
577
+ found;
578
+ constructor(app, expected, found) {
579
+ super(`The digests file pins '${app}' to ${found}, but this release runs ${expected}. It was written for another registry, project, stage or tag; use the file this stage's push of this tag wrote.`);
580
+ this.app = app;
581
+ this.expected = expected;
582
+ this.found = found;
583
+ this.name = "ImageDigestMismatch";
584
+ }
585
+ };
586
+ /** A digests file that is not a JSON object of app to pinned ref. */
587
+ var ImageDigestsInvalid = class extends GkmError {
588
+ file;
589
+ detail;
590
+ constructor(file, detail) {
591
+ super(`${file} is not a digests file (${detail}). It should be the JSON object \`gkm compose --build --push --digests-file\` writes: { "api": "<registry>/<image>:<tag>@sha256:…" }.`);
592
+ this.file = file;
593
+ this.detail = detail;
594
+ this.name = "ImageDigestsInvalid";
595
+ }
596
+ };
597
+ /** Parse a digests file's content, checking its shape. */
598
+ function parseDigests(file, content) {
599
+ let parsed;
600
+ try {
601
+ parsed = JSON.parse(content);
602
+ } catch (error) {
603
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
604
+ }
605
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
606
+ for (const [app, value] of Object.entries(parsed)) if (typeof value !== "string" || !/@sha256:[0-9a-f]{64}$/.test(value)) throw new ImageDigestsInvalid(file, `'${app}' is not an <image>:<tag>@sha256:… ref`);
607
+ return parsed;
608
+ }
609
+ /**
610
+ * Each image pinned to the digest the file names for it.
611
+ *
612
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
613
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
614
+ */
615
+ function pinImages(file, digests, images) {
616
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
617
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
618
+ return images.map((image) => {
619
+ const pinned = digests[image.app];
620
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
621
+ return {
622
+ ...image,
623
+ ref: pinned
624
+ };
625
+ });
626
+ }
627
+ //#endregion
628
+ //#region src/compose/sitePassword.ts
629
+ /**
630
+ * A site served behind a password on some deployed stages — a `StaticSite`'s
631
+ * `password`, naming a `RandomPassword` — so a staging build is not public
632
+ * while it is being tried.
633
+ *
634
+ * The edge asks for it with HTTP basic auth, before a request reaches the
635
+ * site: the browser prompts, and nothing of the site loads until the stage's
636
+ * login is given. The user is the stage's name; the password is the
637
+ * `RandomPassword`'s value on the stage, generated and kept like any other.
638
+ * Only its bcrypt hash reaches the edge's config.
639
+ *
640
+ * Pure.
641
+ */
642
+ /** A site's `password` names a `RandomPassword` the manifest does not hold. */
643
+ var SitePasswordNotDeclared = class extends GkmError {
644
+ site;
645
+ secret;
646
+ constructor(site, secret) {
647
+ super(`'${site}' is served behind the password '${secret}', and no RandomPassword '${secret}' was found. Export it from a constructs file, as any construct is: export const ${secret[0].toLowerCase()}${secret.slice(1)} = new RandomPassword('${secret}');`);
648
+ this.site = site;
649
+ this.secret = secret;
650
+ this.name = "SitePasswordNotDeclared";
651
+ }
652
+ };
653
+ /** A site's `password` names a stage the workspace does not deploy. */
654
+ var UnknownPasswordStage = class extends GkmError {
655
+ site;
656
+ stage;
657
+ deployed;
658
+ constructor(site, stage, deployed) {
659
+ super(`'${site}' is served behind a password on '${stage}', which is not one of the workspace's deployed stages (${deployed.map((s) => `'${s}'`).join(", ")}). Name one of them in its password's stages.`);
660
+ this.site = site;
661
+ this.stage = stage;
662
+ this.deployed = deployed;
663
+ this.name = "UnknownPasswordStage";
664
+ }
665
+ };
666
+ /** A site behind a password, with none in the stage's secrets. */
667
+ var SitePasswordMissing = class extends GkmError {
668
+ stage;
669
+ key;
670
+ constructor(stage, key) {
671
+ super(`A site of '${stage}' is served behind a password, and the stage has no ${key} in its secrets. Run gkm compose --stage ${stage} once to generate it, or set one: gkm secrets:set ${key} '…' --stage ${stage}`);
672
+ this.stage = stage;
673
+ this.key = key;
674
+ this.name = "SitePasswordMissing";
675
+ }
676
+ };
677
+ /**
678
+ * A site behind a password on a stage it deploys through a target that cannot
679
+ * ask for a login. Refused rather than ignored: ignored, the site would be
680
+ * public while its construct says it is not.
681
+ */
682
+ var SitePasswordNeedsCompose = class extends GkmError {
683
+ site;
684
+ stage;
685
+ target;
686
+ constructor(site, stage, target) {
687
+ super(`'${site}' is served behind a password on '${stage}', and it deploys through '${target}', which cannot ask for one yet — only compose does. Remove ${stage} from its password's stages, or deploy it with compose.`);
688
+ this.site = site;
689
+ this.stage = stage;
690
+ this.target = target;
691
+ this.name = "SitePasswordNeedsCompose";
692
+ }
693
+ };
694
+ /**
695
+ * The `RandomPassword` a site is served behind on `stage`, by its key —
696
+ * `SITE_PASSWORD` — or `undefined` where the stage asks for none.
697
+ *
698
+ * @throws {SitePasswordNotDeclared} where the password is not in the manifest
699
+ */
700
+ function sitePasswordKey(manifest, site, stage) {
701
+ const password = site.password;
702
+ if (!password?.stages.includes(stage)) return void 0;
703
+ const secret = manifest[password.secret];
704
+ const key = secret?.kind === "secret" ? secret.provides?.[0] : void 0;
705
+ if (!key) throw new SitePasswordNotDeclared(site.id, password.secret);
706
+ return key;
707
+ }
708
+ /**
709
+ * Before anything is deployed: every site behind a password names a deployed
710
+ * stage and a declared `RandomPassword`, and one of `apps` behind it on
711
+ * `stage` deploys through compose.
712
+ *
713
+ * @throws {UnknownPasswordStage}, {SitePasswordNotDeclared},
714
+ * {SitePasswordNeedsCompose}
715
+ */
716
+ function assertSitePasswords(workspace, manifest, stage, apps, target) {
717
+ for (const site of Object.values(manifest)) {
718
+ if (site.kind !== "site" || !site.password) continue;
719
+ for (const named of site.password.stages) if (!workspace.stages.deployed.includes(named)) throw new UnknownPasswordStage(site.id, named, workspace.stages.deployed);
720
+ if (sitePasswordKey(manifest, site, stage) && target !== "compose" && apps.includes(appKey(site.id))) throw new SitePasswordNeedsCompose(site.id, stage, target);
721
+ }
722
+ }
723
+ /**
724
+ * The login a site is served behind on `stage`, from the password kept under
725
+ * `key`.
726
+ *
727
+ * The hash's salt is derived from the password, so the same password always
728
+ * renders the same edge config: a deploy that changed nothing rewrites
729
+ * nothing, and the proxy is not reloaded for it. A per-hash random salt
730
+ * guards against a precomputed table of common passwords; a generated one is
731
+ * 43 random characters, which no table holds.
732
+ *
733
+ * @throws {SitePasswordMissing} where the stage's secrets hold none
734
+ */
735
+ function siteAuth(stage, key, custom) {
736
+ const password = custom[key];
737
+ if (!password) throw new SitePasswordMissing(stage, key);
738
+ return {
739
+ user: stage,
740
+ password,
741
+ hash: bcrypt.hashSync(password, saltFor(password)),
742
+ key
743
+ };
744
+ }
745
+ /** bcrypt's own base-64 alphabet, in which a salt is written. */
746
+ const BCRYPT_ALPHABET = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
747
+ /**
748
+ * A bcrypt salt — `$2a$`, which Caddy and Traefik both read, at cost 10 —
749
+ * derived from the password.
750
+ */
751
+ function saltFor(password) {
752
+ const digest = createHash("sha256").update(password).digest();
753
+ let salt = "";
754
+ for (let i = 0; i < 22; i++) salt += BCRYPT_ALPHABET[digest[i] % 64];
755
+ return `$2a$10$${salt}`;
756
+ }
757
+ //#endregion
758
+ //#region src/compose/traefik.ts
759
+ /**
760
+ * The server's shared edge, rendered for Traefik: what the edge itself runs
761
+ * with, and what one stack registers with it.
762
+ *
763
+ * One Traefik per server owns 80 and 443, the ACME state and the redirect to
764
+ * HTTPS. It is configured through its file provider alone: each stack writes
765
+ * one file — its routers, services and middlewares, every name prefixed with
766
+ * its compose project — into a directory the edge watches, and removes it
767
+ * when it stops. There is no Docker socket: the edge never learns what runs
768
+ * on the server except from those files.
769
+ *
770
+ * The edge and the stacks meet on one external Docker network. Only a
771
+ * stack's public services join it, each under an alias prefixed with its
772
+ * project (`<project>-api`), because the network is shared: a bare service
773
+ * name there would be answered by every stack's `api`.
774
+ *
775
+ * Pure: the documents are data, and the edge's side effects are `edge.ts`'s.
776
+ */
777
+ /**
778
+ * The image, pinned: the edge is every stack's way in, so a new version is a
779
+ * change to this line, not whatever `latest` is on the day a server starts.
780
+ */
781
+ const TRAEFIK_IMAGE = "traefik:v3.7.13";
782
+ /** The edge's compose project, one per server. */
783
+ const EDGE_PROJECT = "gkm-edge";
784
+ /** The external network the edge and every stack's public services share. */
785
+ const EDGE_NETWORK = "gkm-edge";
786
+ /** The edge's compose service. */
787
+ const EDGE_SERVICE = "traefik";
788
+ /** Inside the edge's container: what it watches, and where certificates are. */
789
+ const EDGE_DYNAMIC_DIR = "/etc/gkm-edge/dynamic";
790
+ const EDGE_CERTS_DIR = "/etc/gkm-edge/certs";
791
+ /** The certificate resolver every deployed route without its own certificate uses. */
792
+ const ACME_RESOLVER = "letsencrypt";
793
+ /**
794
+ * The resolver a wildcard site's `*.<domain>` certificate comes from: Let's
795
+ * Encrypt issues a wildcard only over the DNS challenge, which the edge
796
+ * answers by writing an `_acme-challenge` TXT record through Route 53.
797
+ */
798
+ const ACME_DNS_RESOLVER = "letsencrypt-dns";
799
+ /**
800
+ * The key the edge writes those records with, inside its container: written
801
+ * by the deploy of a stage with a wildcard site, and allowed nothing but
802
+ * each such stage's `_acme-challenge` record (see `acmeDns.ts`).
803
+ */
804
+ const EDGE_AWS_CREDENTIALS = `${EDGE_CERTS_DIR}/aws-credentials`;
805
+ /** The internal entrypoint the edge's health check asks; never published. */
806
+ const PING_PORT = 8082;
807
+ /** A stack's service, as the edge — and the stack itself — reach it. */
808
+ function edgeAlias(project, service) {
809
+ return `${project}-${service}`;
810
+ }
811
+ /** A stack's certificate, as the edge's container reads it. */
812
+ function edgeCertificatePaths(project) {
813
+ return {
814
+ certFile: `${EDGE_CERTS_DIR}/${project}.crt`,
815
+ keyFile: `${EDGE_CERTS_DIR}/${project}.key`
816
+ };
817
+ }
818
+ /**
819
+ * The edge's static configuration: the entrypoints, the redirect, ACME, and
820
+ * the directory it watches. No API and no dashboard — nothing about the edge
821
+ * is reachable but the routes stacks register.
822
+ */
823
+ function traefikStatic(ports) {
824
+ return {
825
+ global: {
826
+ checkNewVersion: false,
827
+ sendAnonymousUsage: false
828
+ },
829
+ entryPoints: {
830
+ web: {
831
+ address: ":80",
832
+ http: { redirections: { entryPoint: {
833
+ to: ports.https === 443 ? "websecure" : `:${ports.https}`,
834
+ scheme: "https",
835
+ permanent: true
836
+ } } }
837
+ },
838
+ websecure: { address: ":443" },
839
+ ping: { address: `:${PING_PORT}` }
840
+ },
841
+ ping: { entryPoint: "ping" },
842
+ providers: { file: {
843
+ directory: EDGE_DYNAMIC_DIR,
844
+ watch: true
845
+ } },
846
+ certificatesResolvers: {
847
+ [ACME_RESOLVER]: { acme: {
848
+ storage: "/acme/acme.json",
849
+ httpChallenge: { entryPoint: "web" }
850
+ } },
851
+ [ACME_DNS_RESOLVER]: { acme: {
852
+ storage: "/acme/acme-dns.json",
853
+ dnsChallenge: {
854
+ provider: "route53",
855
+ resolvers: ["1.1.1.1:53", "8.8.8.8:53"]
856
+ }
857
+ } }
858
+ },
859
+ log: { level: "INFO" }
860
+ };
861
+ }
862
+ /** The edge's compose document. */
863
+ function edgeCompose(options) {
864
+ const { ports } = options;
865
+ return {
866
+ name: EDGE_PROJECT,
867
+ services: { [EDGE_SERVICE]: {
868
+ image: TRAEFIK_IMAGE,
869
+ restart: "unless-stopped",
870
+ ports: [`${ports.https}:443`, `${ports.http}:80`],
871
+ configs: [{
872
+ source: "traefik",
873
+ target: "/etc/traefik/traefik.yml"
874
+ }],
875
+ volumes: [
876
+ `dynamic:${EDGE_DYNAMIC_DIR}`,
877
+ `certs:${EDGE_CERTS_DIR}`,
878
+ "acme:/acme"
879
+ ],
880
+ labels: { "dev.geekmidas.edge.config": createHash("sha256").update(options.staticConfig).digest("hex").slice(0, 16) },
881
+ environment: {
882
+ AWS_SHARED_CREDENTIALS_FILE: EDGE_AWS_CREDENTIALS,
883
+ AWS_REGION: "us-east-1"
884
+ },
885
+ networks: ["edge"],
886
+ ...EDGE_LIMITS,
887
+ healthcheck: {
888
+ test: [
889
+ "CMD",
890
+ "traefik",
891
+ "healthcheck",
892
+ "--ping"
893
+ ],
894
+ interval: "10s",
895
+ timeout: "5s",
896
+ retries: 5
897
+ },
898
+ logging: options.logging
899
+ } },
900
+ configs: { traefik: { content: options.staticConfig } },
901
+ volumes: {
902
+ acme: {},
903
+ dynamic: {},
904
+ certs: {}
905
+ },
906
+ networks: { edge: {
907
+ name: EDGE_NETWORK,
908
+ external: true
909
+ } }
910
+ };
911
+ }
912
+ /** A stack's dynamic configuration, as an object. */
913
+ function traefikDynamic(routes, options) {
914
+ const { project, tls } = options;
915
+ const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
916
+ const url = ({ service, port }) => `http://${edgeAlias(project, service)}:${port}`;
917
+ const routers = {};
918
+ const services = {};
919
+ const middlewares = {};
920
+ const strip = `${project}-strip-gkm-headers`;
921
+ if (routes.length > 0) middlewares[strip] = { headers: { customRequestHeaders: { [CLIENT_IP_HEADER]: "" } } };
922
+ for (const route of routes) {
923
+ const chain = [strip];
924
+ if (route.allow) {
925
+ middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
926
+ chain.push(name(route, "allow"));
927
+ }
928
+ if (route.auth) {
929
+ middlewares[name(route, "auth")] = { basicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] } };
930
+ chain.push(name(route, "auth"));
931
+ }
932
+ if (route.prefix) {
933
+ middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
934
+ chain.push(name(route, "prefix"));
935
+ }
936
+ assertRouteRenderable(route);
937
+ const allowed = [...(route.paths ?? []).map((path) => `Path(\`${path}\`)`), ...(route.prefixes ?? []).map((prefix) => `PathPrefix(\`${prefix}\`)`)];
938
+ const paths = allowed.length ? ` && (${allowed.join(" || ")})` : "";
939
+ const header = route.requireHeader ? ` && Header(\`${route.requireHeader.name}\`, \`${route.requireHeader.value}\`)` : "";
940
+ const certificate = () => route.wildcard?.tls.kind === "dns" ? {
941
+ certResolver: ACME_DNS_RESOLVER,
942
+ domains: [{ main: `*.${route.wildcard.domain}` }]
943
+ } : tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {};
944
+ for (const handler of route.handlers ?? []) {
945
+ const handlerName = name(route, handler.name);
946
+ routers[handlerName] = {
947
+ rule: `Host(\`${route.host}\`) && (${handler.prefixes.map((prefix) => `PathPrefix(\`${prefix}\`)`).join(" || ")})`,
948
+ priority: 1e4,
949
+ entryPoints: ["websecure"],
950
+ service: handlerName,
951
+ middlewares: [strip],
952
+ tls: certificate()
953
+ };
954
+ services[handlerName] = { loadBalancer: { servers: handler.upstreams.map((upstream) => ({ url: url(upstream) })) } };
955
+ }
956
+ routers[name(route)] = {
957
+ rule: `${hostRule(route)}${paths}${header}`,
958
+ ...route.wildcard ? { priority: 1 } : {},
959
+ entryPoints: ["websecure"],
960
+ service: name(route),
961
+ middlewares: chain,
962
+ tls: certificate()
963
+ };
964
+ services[name(route)] = { loadBalancer: {
965
+ servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
966
+ ...route.prefix ? { passHostHeader: false } : {},
967
+ ...route.streaming ? { responseForwarding: { flushInterval: "-1ms" } } : {},
968
+ ...route.health ? { healthCheck: {
969
+ path: route.health,
970
+ interval: "5s",
971
+ timeout: "3s"
972
+ } } : {}
973
+ } };
974
+ }
975
+ return {
976
+ http: {
977
+ routers,
978
+ services,
979
+ ...Object.keys(middlewares).length > 0 ? { middlewares } : {}
980
+ },
981
+ ...tls.kind === "files" ? { tls: { certificates: [{
982
+ certFile: tls.certFile,
983
+ keyFile: tls.keyFile
984
+ }] } } : {}
985
+ };
986
+ }
987
+ /**
988
+ * The hosts a route answers, as a Traefik rule: its own, or — for a wildcard
989
+ * site — exactly one label under its domain, but the ones it never takes.
990
+ * One label, as a wildcard certificate covers: a stage at
991
+ * `staging.example.com` is never reached through `example.com`'s wildcard.
992
+ */
993
+ function hostRule(route) {
994
+ if (!route.wildcard) return `Host(\`${route.host}\`)`;
995
+ const { domain, except } = route.wildcard;
996
+ return [`HostRegexp(\`${`^[a-z0-9-]+\\.${domain.replace(/\./g, "\\.")}$`}\`)`, ...except.map((label) => `!Host(\`${label}.${domain}\`)`)].join(" && ");
997
+ }
998
+ /** A stack's dynamic configuration file, as written to the edge's directory. */
999
+ function traefikDynamicFile(routes, options) {
1000
+ return `# Generated by gkm compose for ${options.project} — do not edit.
1001
+ # The shared edge (${EDGE_PROJECT}) reads every file in this directory; this
1002
+ # one is removed by gkm compose --down.
1003
+ ${yaml(traefikDynamic(routes, options))}`;
1004
+ }
1005
+ /** The edge's static configuration file. */
1006
+ function traefikStaticFile(ports) {
1007
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1008
+ ${yaml(traefikStatic(ports))}`;
1009
+ }
1010
+ /** The edge's compose file. */
1011
+ function edgeComposeFile(options) {
1012
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1013
+ #
1014
+ # Started by the first stack that runs with proxy: 'traefik', and left
1015
+ # running by gkm compose --down. Stop it, once nothing uses it, with:
1016
+ #
1017
+ # docker compose -p ${EDGE_PROJECT} down
1018
+ ${yaml(edgeCompose(options))}`;
1019
+ }
1020
+ function yaml(value) {
1021
+ return stringify(value, {
1022
+ lineWidth: 0,
1023
+ aliasDuplicateObjects: false
1024
+ });
1025
+ }
1026
+ //#endregion
1027
+ //#region src/compose/stack.ts
1028
+ /**
1029
+ * The stack a workspace runs as for one stage — pure.
1030
+ *
1031
+ * Everything `gkm compose` writes is decided here, as data: the compose file,
1032
+ * the Caddyfile, one env file per backend, and the image each app runs. The
1033
+ * command around it reads the workspace, asks the registry, writes the files
1034
+ * and starts Docker; none of those decide anything, so all of it can be
1035
+ * asserted without a daemon.
1036
+ *
1037
+ * The values come from the same derivations every other target uses. The
1038
+ * plan is reconcile's `planFor`, the keys an app reads are `appEnvKeys`, and
1039
+ * every URL is `envFor`'s — asked twice, once with each app at its public
1040
+ * address and once on the compose network, because a browser and a sibling
1041
+ * service reach the same API by different names.
1042
+ */
1043
+ /** Where a stack's files are written, relative to the workspace root. */
1044
+ function stackDir(stage) {
1045
+ return `.gkm/compose/${stage}`;
1046
+ }
1047
+ /**
1048
+ * The compose project a stage's stack runs as.
1049
+ *
1050
+ * The deploy identity's scope, so two workspaces with one name in different
1051
+ * namespaces never share containers or volumes — and the stage, so a
1052
+ * machine can run two stages side by side.
1053
+ */
1054
+ function composeProject(identity) {
1055
+ return `${identity.scope}-${identity.stage}`;
1056
+ }
1057
+ /** The ports the edge is published on, and the variables that move them. */
1058
+ const EDGE_PORT_ENV = {
1059
+ https: "GKM_COMPOSE_HTTPS_PORT",
1060
+ http: "GKM_COMPOSE_HTTP_PORT"
1061
+ };
1062
+ /**
1063
+ * The variable that moves the local stage's OpenObserve off its loopback
1064
+ * port, 5080 — which the local stage takes from nowhere else, since it
1065
+ * ignores `deploy.telemetry`. Another stack, or another tool, may hold 5080.
1066
+ */
1067
+ const LOGS_PORT_ENV = "GKM_COMPOSE_LOGS_PORT";
1068
+ /**
1069
+ * Containers this target does not run.
1070
+ *
1071
+ * The AWS emulator never applies: a stack is a server target, whose events
1072
+ * are pg-boss. Reconcile's Caddy fronts `gkm dev`'s host processes; the stack
1073
+ * brings its own edge.
1074
+ *
1075
+ * MinIO and Mailpit run on the local stage always, and on a deployed stage
1076
+ * only where `--allow-dev-services` allowed them and its secrets configure no
1077
+ * real bucket or mail server — see `devServices.ts`.
1078
+ */
1079
+ const NOT_RUN = {
1080
+ localstack: true,
1081
+ caddy: true
1082
+ };
1083
+ /** The kinds a deployed stage takes from its secrets, or a dev service. */
1084
+ const SERVICE_KINDS = {
1085
+ email: "email",
1086
+ objects: "objects",
1087
+ "file-server": "file-server"
1088
+ };
1089
+ /** The region MinIO is addressed with. It has no regions; the SDK wants one. */
1090
+ const MINIO_REGION = "us-east-1";
1091
+ /** The S3 client's credentials, read beside a bucket's URL when it has them. */
1092
+ const STORAGE_KEYS = [
1093
+ "AWS_ACCESS_KEY_ID",
1094
+ "AWS_SECRET_ACCESS_KEY",
1095
+ "AWS_REGION"
1096
+ ];
1097
+ /**
1098
+ * Every service's Docker logs, rotated. The json-file driver keeps a
1099
+ * container's output in one file that grows until the disk is full — on a
1100
+ * small server, in weeks. Three files of 10 MB each per container is enough
1101
+ * to see what happened and never fills anything. A project's own override
1102
+ * file that sets `logging` wins over it.
1103
+ */
1104
+ const LOG_ROTATION = {
1105
+ driver: "json-file",
1106
+ options: {
1107
+ "max-size": "10m",
1108
+ "max-file": "3"
1109
+ }
1110
+ };
1111
+ /** A CDN serves the bucket, and the secret it sends the processors is not in the stage. */
1112
+ var ProcessorOriginSecretMissing = class extends GkmError {
1113
+ fileServer;
1114
+ key;
1115
+ stage;
1116
+ constructor(fileServer, key, stage) {
1117
+ super(`'${fileServer}' has processors, and its bucket is not the stack's MinIO, so they are reached through the CDN in front of it — which sends ${key}, and stage '${stage}' has none. It is written by the deploy that creates the CDN (\`deploy.objects.${stage}\` on s3, cdn on): run gkm deploy --stage ${stage}.`);
1118
+ this.fileServer = fileServer;
1119
+ this.key = key;
1120
+ this.stage = stage;
1121
+ this.name = "ProcessorOriginSecretMissing";
1122
+ }
1123
+ };
1124
+ /**
1125
+ * The stack with Caddy's files inline: its Caddyfile and, where the stage has
1126
+ * one, its own certificate — `configs` with their `content`, which compose
1127
+ * copies into the container through the engine's API. Nothing is mounted from
1128
+ * a path, so the stack runs the same on a server's engine, over SSH, as on
1129
+ * this machine's. Their hash is a label: a changed file is a changed service,
1130
+ * which `up` recreates (compose does not, for a config's content alone).
1131
+ */
1132
+ function withCaddyConfigs(compose, files) {
1133
+ const caddy = compose.services.caddy;
1134
+ if (!caddy) return compose;
1135
+ const configs = {
1136
+ caddyfile: { content: files.caddyfile },
1137
+ ...files.tls ? {
1138
+ "tls-cert": { content: files.tls.cert },
1139
+ "tls-key": { content: files.tls.key }
1140
+ } : {}
1141
+ };
1142
+ const hash = createHash("sha256");
1143
+ for (const [name, { content }] of Object.entries(configs)) hash.update(`${name}\0${content}\0`);
1144
+ return {
1145
+ ...compose,
1146
+ services: {
1147
+ ...compose.services,
1148
+ caddy: {
1149
+ ...caddy,
1150
+ configs: [{
1151
+ source: "caddyfile",
1152
+ target: "/etc/caddy/Caddyfile"
1153
+ }, ...files.tls ? [{
1154
+ source: "tls-cert",
1155
+ target: `${CADDY_TLS_DIR}/cert.pem`
1156
+ }, {
1157
+ source: "tls-key",
1158
+ target: `${CADDY_TLS_DIR}/key.pem`,
1159
+ mode: 256
1160
+ }] : []],
1161
+ labels: {
1162
+ ...caddy.labels,
1163
+ "dev.geekmidas.caddy.config": hash.digest("hex").slice(0, 16)
1164
+ }
1165
+ }
1166
+ },
1167
+ configs: {
1168
+ ...compose.configs,
1169
+ ...configs
1170
+ }
1171
+ };
1172
+ }
1173
+ /** The label the local stage's Mailpit inbox answers on. */
1174
+ const MAIL_INBOX_LABEL = "mail";
1175
+ /** Mailpit's web UI and API, inside the stack's network. */
1176
+ const MAILPIT_WEB_PORT = 8025;
1177
+ /** An app of the local stage on the host its Mailpit inbox is served at. */
1178
+ var MailInboxHostTaken = class extends GkmError {
1179
+ host;
1180
+ app;
1181
+ constructor(host, app) {
1182
+ super(`'${app}' answers on ${host}, which the local stage serves its Mailpit inbox at. Give '${app}' another subdomain — '${MAIL_INBOX_LABEL}' is reserved for the inbox on the local stage.`);
1183
+ this.host = host;
1184
+ this.app = app;
1185
+ this.name = "MailInboxHostTaken";
1186
+ }
1187
+ };
1188
+ /**
1189
+ * The services a stack publishes on its engine's loopback, and the port each
1190
+ * answers on inside — what gkm reaches from this machine to provision the
1191
+ * stack and run its migrations and seeds. Everything else is reached only on
1192
+ * the stack's network.
1193
+ */
1194
+ const LOOPBACK_SERVICES = {
1195
+ postgres: 5432,
1196
+ minio: 9e3
1197
+ };
1198
+ /** The local stage's stack, without the logins `gkm dev` generates. */
1199
+ var LocalCredentialsMissing = class extends GkmError {
1200
+ stage;
1201
+ constructor(stage) {
1202
+ super(`The local stage '${stage}' runs with this machine's generated logins, and none were passed. Load them with loadLocalCredentials(workspace) and pass them as localCredentials.`);
1203
+ this.stage = stage;
1204
+ this.name = "LocalCredentialsMissing";
1205
+ }
1206
+ };
1207
+ /**
1208
+ * A deployed stage's container logins, derived from its seed like its role
1209
+ * passwords — so every deploy of the stage computes the same ones, and no one
1210
+ * reading the repo can.
1211
+ */
1212
+ function derivedCredentials(project, plan, seed) {
1213
+ const derive = (purpose) => localRolePassword(project, plan, purpose, seed);
1214
+ return {
1215
+ postgres: {
1216
+ user: postgresSuperuser(project),
1217
+ password: derive("master")
1218
+ },
1219
+ minio: {
1220
+ user: `${project}-minio`,
1221
+ password: derive("minio")
1222
+ },
1223
+ rabbitmq: {
1224
+ user: LOCAL_RABBITMQ_USER,
1225
+ password: derive("rabbitmq")
1226
+ },
1227
+ redis: { password: derive("redis") },
1228
+ cacheToken: derive("cache-token"),
1229
+ emulator: {
1230
+ accessKeyId: EMULATOR_ACCESS_KEY_ID,
1231
+ secretAccessKey: derive("emulator")
1232
+ },
1233
+ logs: {
1234
+ email: `admin@${project}`,
1235
+ password: derive("logs")
1236
+ }
1237
+ };
1238
+ }
1239
+ /** A value only the stage's secrets can hold, and they do not. */
1240
+ var StageSecretMissing = class extends GkmError {
1241
+ app;
1242
+ key;
1243
+ stage;
1244
+ constructor(app, key, stage) {
1245
+ super(`'${app}' reads ${key}, and the stage '${stage}' has none. Nothing in the stack can derive it; set it in the stage's secrets: gkm secrets:set ${key} '…' --stage ${stage}`);
1246
+ this.app = app;
1247
+ this.key = key;
1248
+ this.stage = stage;
1249
+ this.name = "StageSecretMissing";
1250
+ }
1251
+ };
1252
+ /**
1253
+ * One key of a deployed inbox — the one rule every target reads it by.
1254
+ *
1255
+ * Its domain is the stage's, which mail is addressed to. Everything else (where
1256
+ * its raw messages are read, its topic's publisher string) is what its
1257
+ * provider made and wrote to the stage's secrets; nothing can derive it.
1258
+ *
1259
+ * @throws {NoDomainForStage} for its domain when the stage has none.
1260
+ * @throws {StageSecretMissing} when the provider has not written the key.
1261
+ */
1262
+ function deployedInboxValue(inbox, key, sources) {
1263
+ if (key === provideKey(inbox, "domain")) {
1264
+ if (!sources.domain) throw new NoDomainForStage(sources.stage);
1265
+ return sources.domain;
1266
+ }
1267
+ const value = sources.secrets[key];
1268
+ if (value === void 0) throw new StageSecretMissing(sources.reader, key, sources.stage);
1269
+ return value;
1270
+ }
1271
+ /**
1272
+ * Every deployed inbox's keys, and its topic's publisher string, by key: what
1273
+ * a target that provisions nothing of the inbox's (SST) is handed, read by
1274
+ * {@link deployedInboxValue} as the compose stack reads each.
1275
+ */
1276
+ function deployedInboxEnv(manifest, sources) {
1277
+ const env = {};
1278
+ for (const declaration of Object.values(manifest)) {
1279
+ if (declaration.kind !== "inbox") continue;
1280
+ const keys = [...declaration.provides ?? [], provideKey(declaration.topic, "publisherConnectionString")];
1281
+ for (const key of keys) env[key] = deployedInboxValue(declaration.id, key, sources);
1282
+ }
1283
+ return env;
1284
+ }
1285
+ /** A deployed stage's secrets with no seed to derive its passwords from. */
1286
+ var StageSeedMissing = class extends GkmError {
1287
+ stage;
1288
+ constructor(stage) {
1289
+ super(`The stage '${stage}' has no seed in its secrets, and a deployed stage's database passwords are derived from it. Run gkm compose --stage ${stage} without --dry-run once, or gkm deploy, to generate it.`);
1290
+ this.stage = stage;
1291
+ this.name = "StageSeedMissing";
1292
+ }
1293
+ };
1294
+ /** A workspace with no API and no site to run. */
1295
+ var NothingToCompose = class extends GkmError {
1296
+ root;
1297
+ constructor(root) {
1298
+ super(`${root} declares no RestApi, no site and no Worker with work to do, so a stack would run nothing. Mobile apps ship through their own toolchain.`);
1299
+ this.root = root;
1300
+ this.name = "NothingToCompose";
1301
+ }
1302
+ };
1303
+ /** A value that cannot be written to an env file a line at a time. */
1304
+ var EnvValueMultiline = class extends GkmError {
1305
+ app;
1306
+ key;
1307
+ constructor(app, key) {
1308
+ super(`${key} for '${app}' spans more than one line, and an env file holds one value per line. Store it on one line — base64, or JSON — and decode it where it is read.`);
1309
+ this.app = app;
1310
+ this.key = key;
1311
+ this.name = "EnvValueMultiline";
1312
+ }
1313
+ };
1314
+ /** The services a stack's apps wait on and the edge waits on in turn. */
1315
+ const HEALTHY = { condition: "service_healthy" };
1316
+ /**
1317
+ * An app's health check: its own server, asked on 127.0.0.1 — not
1318
+ * `localhost`, which resolves to `::1` first in an Alpine container while a
1319
+ * server may listen on IPv4 alone.
1320
+ */
1321
+ function probe(port, path) {
1322
+ return {
1323
+ test: [
1324
+ "CMD",
1325
+ "wget",
1326
+ "-q",
1327
+ "-O",
1328
+ "/dev/null",
1329
+ `http://127.0.0.1:${port}${path}`
1330
+ ],
1331
+ interval: "5s",
1332
+ timeout: "3s",
1333
+ retries: 20,
1334
+ start_period: "10s"
1335
+ };
1336
+ }
1337
+ /**
1338
+ * What a stage's stack provisions: reconcile's plan, with a server target's
1339
+ * backends whatever `deploy.default` says — the stack is one machine running
1340
+ * containers, so events are pg-boss beside the declared database, and every
1341
+ * cache, one declared from that database included, is in the stack's own
1342
+ * Redis.
1343
+ */
1344
+ function stackPlan(workspace, manifest, stage) {
1345
+ const protectedSubdomains = [...workspace.protectedSubdomains ?? [], ...nestedStageLabels(workspace.domains, stage)];
1346
+ return planFor(manifest, stage, provisionOrder(manifest), {
1347
+ localStage: workspace.stages.local,
1348
+ ...protectedSubdomains.length > 0 ? { protectedSubdomains } : {},
1349
+ events: DEFAULT_EVENTS.server,
1350
+ cache: STACK_CACHE,
1351
+ edge: false
1352
+ });
1353
+ }
1354
+ /** The stack for one stage. */
1355
+ function composeStack(input) {
1356
+ const { workspace, manifest, stage, identity } = input;
1357
+ const local = stage === workspace.stages.local;
1358
+ const project = composeProject(identity);
1359
+ const custom = input.secrets?.custom ?? {};
1360
+ const https = input.ports?.https ?? 443;
1361
+ const http = input.ports?.http ?? 80;
1362
+ const proxy = proxyFor(workspace.deploy?.compose, stage, local);
1363
+ const certificate = local ? void 0 : certificateFor(workspace.deploy?.compose, stage, workspace.root);
1364
+ const plan = stackPlan(workspace, manifest, stage);
1365
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
1366
+ if (local && !input.localCredentials) throw new LocalCredentialsMissing(stage);
1367
+ const seed = local ? input.localCredentials.seed : input.secrets?.seed;
1368
+ if (!seed) throw new StageSeedMissing(stage);
1369
+ const containers = local ? input.localCredentials : derivedCredentials(workspace.name, plan, seed);
1370
+ const credential = {
1371
+ containers: {
1372
+ ...containers,
1373
+ minio: {
1374
+ user: custom.AWS_ACCESS_KEY_ID ?? containers.minio.user,
1375
+ password: custom.AWS_SECRET_ACCESS_KEY ?? containers.minio.password
1376
+ }
1377
+ },
1378
+ seed
1379
+ };
1380
+ const apps = stackApps(workspace, manifest, plan, {
1381
+ local,
1382
+ stage,
1383
+ https,
1384
+ identity,
1385
+ images: input.images
1386
+ });
1387
+ const workers = stackWorkers(workerUnits(workspace, manifest, input.background ?? {}), {
1388
+ stage,
1389
+ identity,
1390
+ images: input.images
1391
+ });
1392
+ const processors = stackProcessors(processorUnits(workspace, manifest), {
1393
+ manifest,
1394
+ stage,
1395
+ identity,
1396
+ images: input.images
1397
+ });
1398
+ if (apps.length === 0 && workers.length === 0 && processors.length === 0) throw new NothingToCompose(workspace.root);
1399
+ const owners = /* @__PURE__ */ new Map();
1400
+ for (const resource of plan.resources) {
1401
+ owners.set(resource.envKey, resource);
1402
+ if (resource.kind === "email") {
1403
+ owners.set(provideKey(resource.id, "from"), resource);
1404
+ owners.set(provideKey(resource.id, "inboxUrl"), resource);
1405
+ }
1406
+ if (resource.kind === "external-api") owners.set(provideKey(resource.id, "credentials"), resource);
1407
+ if (resource.kind === "inbox") owners.set(provideKey(resource.id, "domain"), resource);
1408
+ if (resource.kind === "websocket-api") owners.set(provideKey(resource.id, "publisherConnectionString"), resource);
1409
+ }
1410
+ const domain = workspace.domains?.[stage];
1411
+ const telemetry = resolveStageTelemetry({
1412
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
1413
+ stage,
1414
+ local,
1415
+ target: "compose",
1416
+ runtime: "server",
1417
+ selfHosted: true,
1418
+ used: usesTelemetry(manifest)
1419
+ });
1420
+ const logsBase = telemetry?.provider === "self-hosted" ? stackLogs({
1421
+ config: local && input.ports?.logs ? {
1422
+ ...telemetry.selfHosted,
1423
+ port: input.ports.logs
1424
+ } : telemetry.selfHosted,
1425
+ stage,
1426
+ local,
1427
+ project: workspace.name,
1428
+ ...domain ? { domain } : {},
1429
+ custom,
1430
+ https,
1431
+ ...local ? { localLogin: input.localCredentials.logs } : {}
1432
+ }) : void 0;
1433
+ const services = local ? {
1434
+ missing: [],
1435
+ minio: plan.resources.filter((r) => r.kind === "objects").map((r) => r.id),
1436
+ mailpit: plan.resources.filter((r) => r.kind === "email" || r.kind === "inbox").map((r) => r.id)
1437
+ } : externalServices({
1438
+ stage,
1439
+ declarations: stageServiceDeclarations({ manifest }),
1440
+ supplied: custom,
1441
+ allow: input.allowDevServices === true,
1442
+ ...domain ? { domain } : {},
1443
+ providers: stageProviderNotes(workspace, stage)
1444
+ });
1445
+ const redis = stackRedis({
1446
+ plan,
1447
+ stage,
1448
+ local,
1449
+ custom,
1450
+ ...local ? { localPassword: input.localCredentials.redis.password } : {}
1451
+ });
1452
+ const infra = [...plan.containers.filter((c) => !NOT_RUN[c]).filter((c) => c !== LOGS_SERVICE).filter((c) => c !== "minio" || services.minio.length > 0).filter((c) => c !== "mailpit" || services.mailpit.length > 0).filter((c) => c !== "redis" || redis !== void 0), ...logsBase ? [LOGS_SERVICE] : []].sort();
1453
+ const mailInbox = local && infra.includes("mailpit") ? (() => {
1454
+ const host = [
1455
+ MAIL_INBOX_LABEL,
1456
+ workspace.name,
1457
+ LOCAL_TLD
1458
+ ].filter(Boolean).join(".");
1459
+ return {
1460
+ host,
1461
+ url: `https://${host}${https !== 443 ? `:${https}` : ""}`
1462
+ };
1463
+ })() : void 0;
1464
+ const storage = infra.includes("minio") ? (() => {
1465
+ const buckets = services.minio.map((id) => byId.get(id)?.name).filter((name) => Boolean(name)).sort();
1466
+ return {
1467
+ ...credential.containers.minio,
1468
+ buckets,
1469
+ policies: bucketPolicies(plan).filter((p) => buckets.includes(p.bucket)),
1470
+ objects: services.minio.map((id) => ({
1471
+ id,
1472
+ name: byId.get(id)?.name
1473
+ })).filter((b) => Boolean(b.name)).sort((a, b) => a.name.localeCompare(b.name)),
1474
+ webhooks: [],
1475
+ lifecycles: bucketLifecycles(plan).filter((l) => buckets.includes(l.bucket))
1476
+ };
1477
+ })() : void 0;
1478
+ const bucketEventKeys = /* @__PURE__ */ new Map();
1479
+ for (const resource of plan.resources) {
1480
+ if (resource.kind !== "objects") continue;
1481
+ bucketEventKeys.set(provideKey(resource.id, "eventsConnectionString"), resource.id);
1482
+ bucketEventKeys.set(provideKey(resource.id, "eventsToken"), resource.id);
1483
+ }
1484
+ const fileServers = /* @__PURE__ */ new Map();
1485
+ if (storage) for (const resource of plan.resources) {
1486
+ if (resource.kind !== "file-server" || !resource.of) continue;
1487
+ if (!services.minio.includes(resource.of)) continue;
1488
+ if (custom[resource.envKey] !== void 0) continue;
1489
+ const bucket = byId.get(resource.of);
1490
+ if (!bucket) continue;
1491
+ let host;
1492
+ if (local) host = hostFor(resource, workspace.name);
1493
+ else {
1494
+ if (!domain) throw new NoDomainForStage(stage);
1495
+ host = `${resource.subdomain ?? appKey(resource.id)}.${domain}`;
1496
+ }
1497
+ fileServers.set(resource.id, {
1498
+ url: `https://${host}${local && https !== 443 ? `:${https}` : ""}`,
1499
+ route: {
1500
+ name: `files-${appKey(resource.id)}`,
1501
+ host,
1502
+ upstreams: [{
1503
+ service: "minio",
1504
+ port: 9e3
1505
+ }],
1506
+ streaming: false,
1507
+ prefix: `/${bucket.name}`
1508
+ }
1509
+ });
1510
+ }
1511
+ const edgeServices = new Set(proxy === "traefik" ? [
1512
+ ...apps.flatMap(replicaNames),
1513
+ ...fileServers.size > 0 ? ["minio"] : [],
1514
+ ...logsBase?.host && logsBase.public ? [LOGS_SERVICE] : [],
1515
+ ...mailInbox ? ["mailpit"] : []
1516
+ ] : []);
1517
+ const hostOf = (service) => edgeServices.has(service) ? edgeAlias(project, service) : service;
1518
+ const logs = logsBase && {
1519
+ ...logsBase,
1520
+ appEnv: {
1521
+ ...logsBase.appEnv,
1522
+ OTEL_EXPORTER_OTLP_ENDPOINT: logsBase.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT.replace(`//openobserve:`, `//${hostOf("openobserve")}:`)
1523
+ }
1524
+ };
1525
+ const derivation = {
1526
+ project: workspace.name,
1527
+ credentials: credential.containers,
1528
+ seed: credential.seed,
1529
+ ...!local && domain ? { mailFrom: `noreply@${domain}` } : {},
1530
+ relayedBuckets: [...watchedBuckets(manifest, input.subscribers ?? {}).keys()].filter((bucket) => services.minio.includes(bucket))
1531
+ };
1532
+ const publicAddresses = Object.fromEntries(apps.map((app) => [app.id, app.url]));
1533
+ const outside = networkEnv(plan, {
1534
+ ...derivation,
1535
+ addresses: publicAddresses
1536
+ }, hostOf);
1537
+ const inside = networkEnv(plan, {
1538
+ ...derivation,
1539
+ addresses: Object.fromEntries(apps.map((app) => [app.id, `${app.kind === "websocket-api" ? "ws" : "http"}://${hostOf(app.name)}:${app.port}`]))
1540
+ }, hostOf);
1541
+ const surfaceUrls = new Map(plan.resources.filter((r) => r.kind === "rest-api" || r.kind === "websocket-api" || r.kind === "site").map((r) => [r.envKey, r.id]));
1542
+ const appById = new Map(apps.map((app) => [app.id, app]));
1543
+ /**
1544
+ * What a key resolves to for one app, from the stage's secrets where only
1545
+ * they can hold it, and the derivations otherwise.
1546
+ */
1547
+ const valueFor = (app, key, owner) => {
1548
+ if (isReservedStageKey(key)) return void 0;
1549
+ const watching = bucketEventKeys.get(key);
1550
+ if (watching) {
1551
+ if (custom[key] !== void 0) return custom[key];
1552
+ return services.minio.includes(watching) ? outside[key] : void 0;
1553
+ }
1554
+ if (owner?.kind === "inbox") {
1555
+ if (local) return outside[key];
1556
+ return deployedInboxValue(owner.id, key, {
1557
+ reader: app.name,
1558
+ stage,
1559
+ domain,
1560
+ secrets: custom
1561
+ });
1562
+ }
1563
+ if (!local && owner?.kind === "email" && key.endsWith("_INBOX_URL")) return;
1564
+ if (owner && SERVICE_KINDS[owner.kind]) {
1565
+ if (custom[key] !== void 0) return custom[key];
1566
+ if (owner.kind === "file-server") return fileServers.get(owner.id)?.url;
1567
+ return outside[key];
1568
+ }
1569
+ if (owner && suppliedOnly(owner.kind, owner.id, key, local)) {
1570
+ const value = custom[key];
1571
+ if (value === void 0) throw new StageSecretMissing(app.name, key, stage);
1572
+ return value;
1573
+ }
1574
+ if (custom[key] !== void 0) return custom[key];
1575
+ if (owner?.kind === "cache") return redis?.urls[key];
1576
+ if (owner?.kind === "websocket-api" && key === provideKey(owner.id, "publisherConnectionString")) return redis?.urls[key];
1577
+ const surface = surfaceUrls.get(key);
1578
+ if ((app.kind === "rest-api" || app.kind === "websocket-api") && surface && surface !== app.id) return inside[key];
1579
+ return outside[key];
1580
+ };
1581
+ const telemetryValues = logs ? telemetryEnv({
1582
+ endpoint: logs.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT,
1583
+ headers: logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS
1584
+ }, telemetry?.sampleRate ?? 1) : telemetry?.provider === "otlp" ? otlpTelemetryEnv(telemetry) : void 0;
1585
+ /** Each key one backend process reads, resolved for this stage. */
1586
+ const valuesFor = (app, keys) => {
1587
+ const values = {};
1588
+ for (const key of [...keys].sort()) {
1589
+ if (isTelemetryKey(key)) continue;
1590
+ const owner = owners.get(key) ?? storageOwner(key, plan);
1591
+ if (STORAGE_KEYS.includes(key)) {
1592
+ const value = custom[key] ?? storageValue(key, storage);
1593
+ if (value !== void 0) values[key] = value;
1594
+ continue;
1595
+ }
1596
+ const value = valueFor(app, key, owner);
1597
+ if (value !== void 0) values[key] = value;
1598
+ }
1599
+ return values;
1600
+ };
1601
+ for (const app of apps) {
1602
+ if (app.kind === "site") {
1603
+ const site = manifest[app.id];
1604
+ if (site?.kind !== "site") continue;
1605
+ const args = publicBuildValues(site, manifest, (key) => valueFor(app, key, owners.get(key)), custom);
1606
+ if (app.build && Object.keys(args).length > 0) app.build.args = args;
1607
+ continue;
1608
+ }
1609
+ if (input.buildOnly) continue;
1610
+ const keys = appEnvKeys(manifest, app.name) ?? /* @__PURE__ */ new Set();
1611
+ const values = valuesFor(app, keys);
1612
+ const trusted = provideKey(app.id, "trustedOrigins");
1613
+ if (keys.has(trusted)) {
1614
+ const internal = (byId.get(app.id)?.callers ?? []).map((caller) => appById.get(caller)).filter((caller) => caller?.kind === "rest-api" || caller?.kind === "websocket-api").map((caller) => `http://${hostOf(caller.name)}:${caller.port}`);
1615
+ const origins = [...(values[trusted] ?? "").split(",").filter(Boolean), ...internal];
1616
+ values[trusted] = [...new Set(origins)].join(",");
1617
+ }
1618
+ app.env = {
1619
+ ...scopeTelemetryEnv(values, {
1620
+ uses: telemetryOf(manifest, app.id) !== void 0,
1621
+ serviceName: app.name,
1622
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1623
+ }),
1624
+ NODE_ENV: "production",
1625
+ PORT: String(app.port),
1626
+ STAGE: stage
1627
+ };
1628
+ for (const [key, value] of Object.entries(app.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(app.name, key);
1629
+ }
1630
+ const mobileApps = [];
1631
+ for (const declaration of Object.values(manifest)) {
1632
+ if (declaration.kind !== "mobile-app") continue;
1633
+ const app = {
1634
+ name: appKey(declaration.id),
1635
+ id: declaration.id,
1636
+ kind: "site"
1637
+ };
1638
+ mobileApps.push({
1639
+ name: app.name,
1640
+ id: app.id,
1641
+ values: publicBuildValues(declaration, manifest, (key) => valueFor(app, key, owners.get(key)), custom)
1642
+ });
1643
+ }
1644
+ for (const worker of input.buildOnly ? [] : workers) {
1645
+ const keys = workerEnvKeys(manifest, worker.id) ?? /* @__PURE__ */ new Set();
1646
+ const resolved = valuesFor({
1647
+ name: worker.name,
1648
+ id: worker.id,
1649
+ kind: "rest-api"
1650
+ }, keys);
1651
+ const push = local ? void 0 : workerPush(worker, input.subscribers?.[worker.id] ?? [], resolved, {
1652
+ stage,
1653
+ ...domain ? { domain } : {}
1654
+ });
1655
+ if (push) {
1656
+ worker.push = push;
1657
+ if (proxy === "traefik") edgeServices.add(worker.name);
1658
+ }
1659
+ worker.env = {
1660
+ ...scopeTelemetryEnv(resolved, {
1661
+ uses: telemetryOf(manifest, worker.id) !== void 0,
1662
+ serviceName: worker.name,
1663
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1664
+ }),
1665
+ ...push && !input.recordingSubscriptions ? { [SNS_SUBSCRIPTIONS_KEY]: recordedSubscriptions(worker, push, input.pushSubscriptions?.[worker.id]) } : {},
1666
+ NODE_ENV: "production",
1667
+ PORT: String(worker.port),
1668
+ STAGE: stage
1669
+ };
1670
+ for (const [key, value] of Object.entries(worker.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(worker.name, key);
1671
+ }
1672
+ for (const unit of processors) {
1673
+ const served = fileServers.get(unit.id);
1674
+ if (served) served.route = {
1675
+ ...served.route,
1676
+ handlers: [{
1677
+ name: unit.name,
1678
+ prefixes: unit.prefixes,
1679
+ upstreams: [{
1680
+ service: unit.name,
1681
+ port: unit.port
1682
+ }]
1683
+ }]
1684
+ };
1685
+ else if (!local && !input.buildOnly) {
1686
+ if (!domain) throw new NoDomainForStage(stage);
1687
+ const key = originSecretKey(unit.id);
1688
+ const secret = custom[key];
1689
+ if (!secret) throw new ProcessorOriginSecretMissing(unit.id, key, stage);
1690
+ unit.origin = {
1691
+ host: processorOriginHost(unit.id, domain),
1692
+ secret
1693
+ };
1694
+ }
1695
+ if (proxy === "traefik" && (served || unit.origin)) edgeServices.add(unit.name);
1696
+ if (input.buildOnly) continue;
1697
+ const keys = processorEnvKeys(manifest, unit.id) ?? /* @__PURE__ */ new Set();
1698
+ unit.env = {
1699
+ ...scopeTelemetryEnv(valuesFor({
1700
+ name: unit.name,
1701
+ id: unit.id,
1702
+ kind: "rest-api"
1703
+ }, keys), {
1704
+ uses: telemetryOf(manifest, unit.id) !== void 0,
1705
+ serviceName: unit.name,
1706
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1707
+ }),
1708
+ NODE_ENV: "production",
1709
+ PORT: String(unit.port),
1710
+ STAGE: stage
1711
+ };
1712
+ for (const [key, value] of Object.entries(unit.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(unit.name, key);
1713
+ }
1714
+ if (storage && !input.buildOnly) {
1715
+ const watched = watchedBuckets(manifest, input.subscribers ?? {});
1716
+ for (const [bucket, workerId] of watched) {
1717
+ if (!services.minio.includes(bucket)) continue;
1718
+ const worker = workers.find((w) => w.id === workerId);
1719
+ const relay = worker?.env?.[provideKey(bucket, "eventsConnectionString")];
1720
+ const token = worker?.env?.[provideKey(bucket, "eventsToken")];
1721
+ if (!worker || !relay || relay.startsWith("sns:") || !token) continue;
1722
+ storage.webhooks.push({
1723
+ bucket,
1724
+ endpoint: `http://${hostOf(worker.name)}:${worker.port}${objectsRoute(bucket)}`,
1725
+ token
1726
+ });
1727
+ }
1728
+ }
1729
+ let inboxRelay;
1730
+ if (local && infra.includes("mailpit") && !input.buildOnly) {
1731
+ const relayId = inboxRelayWorker(manifest, input.subscribers ?? {});
1732
+ const relay = workers.find((w) => w.id === relayId);
1733
+ const token = relay?.env?.[INBOX_RELAY_TOKEN_KEY];
1734
+ if (relay && token) inboxRelay = inboxWebhookUrl(`http://${hostOf(relay.name)}:${relay.port}`, token);
1735
+ }
1736
+ const deployedTls = certificate ? {
1737
+ kind: "files",
1738
+ ...proxy === "caddy" ? {
1739
+ certFile: `${CADDY_TLS_DIR}/cert.pem`,
1740
+ keyFile: `${CADDY_TLS_DIR}/key.pem`
1741
+ } : edgeCertificatePaths(project)
1742
+ } : { kind: "acme" };
1743
+ const tls = local ? { kind: "internal" } : deployedTls;
1744
+ const backupsChoice = input.buildOnly ? void 0 : stageBackups(workspace, manifest, stage);
1745
+ const backups = backupsChoice?.mode === "on" && infra.includes("postgres") ? stackBackups({
1746
+ workspace,
1747
+ stage,
1748
+ project,
1749
+ plan,
1750
+ backups: backupsChoice.backups,
1751
+ custom,
1752
+ seed,
1753
+ superuser: credential.containers.postgres,
1754
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1755
+ }) : void 0;
1756
+ const layout = input.layout ?? defaultLayout(workspace.root);
1757
+ const compose = stackFile({
1758
+ project,
1759
+ plan,
1760
+ infra,
1761
+ apps,
1762
+ workers,
1763
+ processors,
1764
+ credentials: credential.containers,
1765
+ ...storage ? { storage } : {},
1766
+ ...inboxRelay ? { inboxRelay } : {},
1767
+ ...logs ? { logs } : {},
1768
+ ...redis ? { redis } : {},
1769
+ ...backups ? { backups } : {},
1770
+ https,
1771
+ http,
1772
+ composeDir: join(workspace.root, stackDir(stage)),
1773
+ buildRoot: layout.buildRoot,
1774
+ workspaceRoot: workspace.root,
1775
+ envFiles: !input.buildOnly,
1776
+ proxy,
1777
+ edge: new Map([...edgeServices].map((service) => [service, hostOf(service)]))
1778
+ });
1779
+ if (!local) for (const app of apps) {
1780
+ const site = manifest[app.id];
1781
+ if (site?.kind !== "site") continue;
1782
+ const key = sitePasswordKey(manifest, site, stage);
1783
+ if (key) app.auth = siteAuth(stage, key, custom);
1784
+ }
1785
+ const wildcard = local ? void 0 : stackWildcard(apps, {
1786
+ manifest,
1787
+ byId,
1788
+ workspace,
1789
+ stage,
1790
+ proxy,
1791
+ certificate: certificate !== void 0,
1792
+ hostOf
1793
+ });
1794
+ const routes = [
1795
+ ...apps.map((app) => ({
1796
+ name: app.name,
1797
+ host: app.host,
1798
+ ...wildcard?.site === app.id ? { wildcard: wildcard.edge } : {},
1799
+ upstreams: replicaNames(app).map((service) => ({
1800
+ service,
1801
+ port: app.port
1802
+ })),
1803
+ streaming: true,
1804
+ ...app.auth ? { auth: {
1805
+ user: app.auth.user,
1806
+ hash: app.auth.hash
1807
+ } } : {},
1808
+ health: app.kind === "site" ? "/" : "/health"
1809
+ })),
1810
+ ...[...fileServers.values()].map(({ route }) => route),
1811
+ ...processors.flatMap(({ name, port, prefixes, origin }) => origin ? [{
1812
+ name,
1813
+ host: origin.host,
1814
+ upstreams: [{
1815
+ service: name,
1816
+ port
1817
+ }],
1818
+ streaming: false,
1819
+ prefixes,
1820
+ requireHeader: {
1821
+ name: ORIGIN_VERIFY_HEADER,
1822
+ value: origin.secret
1823
+ },
1824
+ health: "/health"
1825
+ }] : []),
1826
+ ...workers.flatMap(({ name, port, push }) => push ? [{
1827
+ name,
1828
+ host: push.host,
1829
+ upstreams: [{
1830
+ service: name,
1831
+ port
1832
+ }],
1833
+ streaming: false,
1834
+ paths: push.paths,
1835
+ health: "/health"
1836
+ }] : []),
1837
+ ...logs?.host && logs.public ? [{
1838
+ name: LOGS_SERVICE,
1839
+ host: logs.host,
1840
+ upstreams: [{
1841
+ service: LOGS_SERVICE,
1842
+ port: LOGS_PORT
1843
+ }],
1844
+ streaming: true,
1845
+ allow: logs.public.allow
1846
+ }] : []
1847
+ ];
1848
+ if (mailInbox) {
1849
+ const taken = routes.find((route) => route.host === mailInbox.host);
1850
+ if (taken) throw new MailInboxHostTaken(mailInbox.host, taken.name);
1851
+ routes.push({
1852
+ name: "mailpit",
1853
+ host: mailInbox.host,
1854
+ upstreams: [{
1855
+ service: "mailpit",
1856
+ port: MAILPIT_WEB_PORT
1857
+ }],
1858
+ streaming: true
1859
+ });
1860
+ }
1861
+ assertHostsUnique(routes);
1862
+ const dockerfiles = {};
1863
+ for (const app of apps) {
1864
+ if (!app.build) continue;
1865
+ dockerfiles[app.build.dockerfile] = appDockerfile(app.name, workspace.apps[app.name], {
1866
+ layout,
1867
+ workspaceRoot: workspace.root,
1868
+ apps: workspace.apps,
1869
+ manifest,
1870
+ cache: STACK_CACHE,
1871
+ workspace,
1872
+ stage,
1873
+ ...app.kind === "site" && app.build.args ? { publicUrlArgs: Object.keys(app.build.args) } : {}
1874
+ });
1875
+ }
1876
+ for (const worker of workers) {
1877
+ if (!worker.build) continue;
1878
+ dockerfiles[worker.build.dockerfile] = workerDockerfile({
1879
+ id: worker.id,
1880
+ name: worker.name,
1881
+ app: worker.host
1882
+ }, workspace.apps[worker.host], {
1883
+ layout,
1884
+ workspaceRoot: workspace.root,
1885
+ cache: STACK_CACHE
1886
+ });
1887
+ }
1888
+ for (const unit of processors) {
1889
+ if (!unit.build) continue;
1890
+ dockerfiles[unit.build.dockerfile] = processorDockerfile({
1891
+ id: unit.id,
1892
+ name: unit.name,
1893
+ app: unit.host
1894
+ }, workspace.apps[unit.host], {
1895
+ layout,
1896
+ workspaceRoot: workspace.root,
1897
+ cache: STACK_CACHE
1898
+ });
1899
+ }
1900
+ return {
1901
+ project,
1902
+ stage,
1903
+ local,
1904
+ apps,
1905
+ workers,
1906
+ processors,
1907
+ mobileApps,
1908
+ infra,
1909
+ compose,
1910
+ proxy,
1911
+ routes,
1912
+ ...wildcard ? { wildcard: {
1913
+ site: wildcard.site,
1914
+ host: `*.${wildcard.edge.domain}`,
1915
+ tls: wildcard.edge.tls.kind
1916
+ } } : {},
1917
+ ...proxy === "caddy" ? { caddyfile: edgeCaddyfile(routes, { tls }) } : { traefik: traefikDynamicFile(routes, {
1918
+ project,
1919
+ tls: deployedTls
1920
+ }) },
1921
+ ...certificate ? { tls: certificate } : {},
1922
+ dockerfiles,
1923
+ plan,
1924
+ credential,
1925
+ resolution: {
1926
+ ...derivation,
1927
+ addresses: {
1928
+ ...publicAddresses,
1929
+ ...Object.fromEntries([...fileServers].map(([id, { url }]) => [id, url]))
1930
+ }
1931
+ },
1932
+ ...storage ? { storage } : {},
1933
+ devServices: local ? [] : devServicesUsed(services),
1934
+ ...logs ? { logs } : {},
1935
+ ...telemetry ? { telemetry } : {},
1936
+ ...redis ? { redis } : {},
1937
+ ...backups ? { backups } : {},
1938
+ ...mailInbox ? { mailInbox } : {}
1939
+ };
1940
+ }
1941
+ /** The stack's MinIO's value for one of the S3 client's keys. */
1942
+ function storageValue(key, storage) {
1943
+ if (!storage) return void 0;
1944
+ if (key === "AWS_ACCESS_KEY_ID") return storage.user;
1945
+ if (key === "AWS_SECRET_ACCESS_KEY") return storage.password;
1946
+ if (key === "AWS_REGION") return MINIO_REGION;
1947
+ }
1948
+ /** Which bucket an S3 credential key belongs to — the first one declared. */
1949
+ function storageOwner(key, plan) {
1950
+ if (!STORAGE_KEYS.includes(key)) return void 0;
1951
+ return plan.resources.find((r) => r.kind === "objects");
1952
+ }
1953
+ /** The apps a stack runs: every API and every site, at its stage address. */
1954
+ function stackApps(workspace, manifest, plan, options) {
1955
+ const apps = [];
1956
+ const resources = new Map(plan.resources.map((r) => [r.id, r]));
1957
+ for (const [id, declaration] of Object.entries(manifest)) {
1958
+ if (declaration.kind !== "rest-api" && declaration.kind !== "websocket-api" && declaration.kind !== "site") continue;
1959
+ const name = appKey(id);
1960
+ const app = workspace.apps[name];
1961
+ const resource = resources.get(id);
1962
+ if (!app || !resource || !app.port) continue;
1963
+ const host = hostOf(name, app, workspace, resource, options);
1964
+ const tag = declaration.kind === "site" ? siteTag(options.images.tag, options.stage) : options.images.tag;
1965
+ const ref = validateImageRef(imageRef(options.identity, name, options.images.registry, tag));
1966
+ apps.push({
1967
+ app: name,
1968
+ name,
1969
+ id,
1970
+ kind: declaration.kind,
1971
+ replicas: declaration.kind === "websocket-api" ? declaration.replicas ?? 1 : 1,
1972
+ path: app.path,
1973
+ port: app.port,
1974
+ host,
1975
+ url: `${declaration.kind === "websocket-api" ? "wss" : "https"}://${host}${options.local && options.https !== 443 ? `:${options.https}` : ""}`,
1976
+ ref,
1977
+ tag,
1978
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${name}` } } : {}
1979
+ });
1980
+ }
1981
+ return apps.sort((a, b) => a.name.localeCompare(b.name));
1982
+ }
1983
+ /**
1984
+ * Where SNS pushes to a worker on a deployed stage, or nothing when it pushes
1985
+ * to none of its subscribers.
1986
+ *
1987
+ * A subscriber is pushed to when the connection string its deliveries come
1988
+ * from — its topic's, or its bucket's events — as this stage resolved it for
1989
+ * the worker, is an SNS one — the same test the worker's own
1990
+ * startup makes, so the edge exposes a route exactly when the worker mounts
1991
+ * it. Each such route, and nothing else the worker serves, answers on
1992
+ * `<worker>.<domain>`.
1993
+ */
1994
+ function workerPush(worker, subscribers, env, options) {
1995
+ const pushed = subscribers.filter(({ connectionKey }) => env[connectionKey]?.startsWith("sns:")).filter((subscriber, index, all) => all.findIndex((s) => s.name === subscriber.name) === index).sort((a, b) => a.name.localeCompare(b.name));
1996
+ if (pushed.length === 0) return void 0;
1997
+ if (!options.domain) throw new NoDomainForStage(options.stage);
1998
+ const host = `${worker.name}.${options.domain}`;
1999
+ const url = `https://${host}`;
2000
+ return {
2001
+ host,
2002
+ url,
2003
+ paths: pushed.map(({ name }) => subscriberRoute(name)),
2004
+ subscribers: pushed.map(({ name, connectionKey, events }) => ({
2005
+ name,
2006
+ connectionKey,
2007
+ endpoint: `${url}${subscriberRoute(name)}`,
2008
+ ...events ? { events } : {}
2009
+ }))
2010
+ };
2011
+ }
2012
+ /** A pushed subscriber the deploy recorded no SNS subscription for. */
2013
+ var PushSubscriptionMissing = class extends GkmError {
2014
+ worker;
2015
+ subscriber;
2016
+ constructor(worker, subscriber) {
2017
+ super(`SNS pushes to '${subscriber}' on the worker '${worker}', and the deploy recorded no subscription for it, so the worker would mount no route and SNS would deliver nowhere. Deploy the stage, which subscribes each pushed subscriber and records its ARN.`);
2018
+ this.worker = worker;
2019
+ this.subscriber = subscriber;
2020
+ this.name = "PushSubscriptionMissing";
2021
+ }
2022
+ };
2023
+ /**
2024
+ * The worker's `GKM_SNS_SUBSCRIPTIONS`: each pushed subscriber's recorded
2025
+ * subscription ARN, and nothing for a subscriber it does not run.
2026
+ *
2027
+ * @throws {PushSubscriptionMissing} when one has none
2028
+ */
2029
+ function recordedSubscriptions(worker, push, recorded = {}) {
2030
+ const arns = {};
2031
+ for (const { name } of push.subscribers) {
2032
+ const arn = recorded[name];
2033
+ if (!arn) throw new PushSubscriptionMissing(worker.name, name);
2034
+ arns[name] = arn;
2035
+ }
2036
+ return JSON.stringify(arns);
2037
+ }
2038
+ /**
2039
+ * A wildcard site on a deployed stage with nowhere to get a certificate for
2040
+ * its tenants' hosts from. Let's Encrypt issues a wildcard certificate only
2041
+ * over the DNS challenge, so the stage either brings its own or gives the
2042
+ * proxy a way to get one.
2043
+ */
2044
+ var WildcardSiteCertificateMissing = class extends GkmError {
2045
+ site;
2046
+ stage;
2047
+ proxy;
2048
+ domain;
2049
+ constructor(site, stage, proxy, domain) {
2050
+ super(proxy === "traefik" ? `'${site}' answers on every subdomain of ${domain}, and '${stage}' has no certificate for them. Set deploy.compose.tls for '${stage}' to a *.${domain} certificate, or manage ${domain} with dns: { '<root domain>': { provider: 'route53' } } so the shared edge gets one over the DNS challenge.` : `'${site}' answers on every subdomain of ${domain}, and '${stage}' has no certificate for them. Set deploy.compose.tls for '${stage}' to a *.${domain} certificate, or give the site \`hosts\` so Caddy gets one per tenant, on demand.`);
2051
+ this.site = site;
2052
+ this.stage = stage;
2053
+ this.proxy = proxy;
2054
+ this.domain = domain;
2055
+ this.name = "WildcardSiteCertificateMissing";
2056
+ }
2057
+ };
2058
+ /**
2059
+ * A deployed stage's wildcard site, as its edge serves it: the labels it
2060
+ * never takes, and its certificate — the stage's own (`deploy.compose.tls`)
2061
+ * first; then, on the shared Traefik edge, a `*.<domain>` one over the DNS
2062
+ * challenge when Route 53 manages the domain; on the stack's own Caddy, one
2063
+ * per host on demand, asked of the site's `hosts` route.
2064
+ *
2065
+ * @throws {WildcardSiteCertificateMissing} when neither applies
2066
+ */
2067
+ function stackWildcard(apps, options) {
2068
+ const { manifest, workspace, stage, proxy } = options;
2069
+ const app = apps.find((a) => isWildcardSite(manifest[a.id]));
2070
+ if (!app) return void 0;
2071
+ const declaration = manifest[app.id];
2072
+ if (!isWildcardSite(declaration)) return void 0;
2073
+ const domain = workspace.domains?.[stage];
2074
+ if (!domain) throw new NoDomainForStage(stage);
2075
+ const except = options.byId.get(app.id)?.protectedSubdomains ?? [];
2076
+ const tls = (() => {
2077
+ if (options.certificate) return { kind: "stage" };
2078
+ if (proxy === "traefik") {
2079
+ const dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};
2080
+ const root = findRootDomain(domain, dns);
2081
+ if (root && dns[root]?.provider === "route53") return { kind: "dns" };
2082
+ } else if (declaration.hosts) {
2083
+ const surface = apps.find((a) => a.id === declaration.hosts?.surface);
2084
+ if (surface) return {
2085
+ kind: "on-demand",
2086
+ ask: `http://${options.hostOf(surface.name)}:${surface.port}${declaration.hosts.path}`
2087
+ };
2088
+ }
2089
+ throw new WildcardSiteCertificateMissing(app.id, stage, proxy, domain);
2090
+ })();
2091
+ return {
2092
+ site: app.id,
2093
+ edge: {
2094
+ domain,
2095
+ except,
2096
+ tls
2097
+ }
2098
+ };
2099
+ }
2100
+ /**
2101
+ * The first label under `stage`'s domain of every other stage's domain that
2102
+ * sits beneath it — `staging` for `staging.example.com` (or
2103
+ * `a.staging.example.com`) under `example.com`.
2104
+ */
2105
+ function nestedStageLabels(domains, stage) {
2106
+ const own = domains?.[stage]?.toLowerCase();
2107
+ if (!own) return [];
2108
+ const labels = /* @__PURE__ */ new Set();
2109
+ for (const [other, domain] of Object.entries(domains ?? {})) {
2110
+ if (other === stage || !domain) continue;
2111
+ const lower = domain.toLowerCase();
2112
+ if (!lower.endsWith(`.${own}`)) continue;
2113
+ const rest = lower.slice(0, -(own.length + 1)).split(".");
2114
+ labels.add(rest.at(-1));
2115
+ }
2116
+ return [...labels].sort();
2117
+ }
2118
+ /** Two constructs the edge would answer on one host. */
2119
+ var EdgeHostTaken = class extends GkmError {
2120
+ host;
2121
+ first;
2122
+ second;
2123
+ constructor(host, first, second) {
2124
+ super(`'${first}' and '${second}' would both answer on ${host}, and the edge can send a host to only one of them. Give one a subdomain of its own, or rename it.`);
2125
+ this.host = host;
2126
+ this.first = first;
2127
+ this.second = second;
2128
+ this.name = "EdgeHostTaken";
2129
+ }
2130
+ };
2131
+ /** Refuse a stack where one host would be routed to two services. */
2132
+ function assertHostsUnique(routes) {
2133
+ const claimed = /* @__PURE__ */ new Map();
2134
+ for (const { host, name } of routes) {
2135
+ const first = claimed.get(host);
2136
+ if (first !== void 0) throw new EdgeHostTaken(host, first, name);
2137
+ claimed.set(host, name);
2138
+ }
2139
+ }
2140
+ /** Each processor unit's image, and where it is built from. */
2141
+ function stackProcessors(units, options) {
2142
+ return units.map((unit) => {
2143
+ const server = options.manifest[unit.id];
2144
+ const processors = server?.kind === "file-server" ? server.processors ?? [] : [];
2145
+ return {
2146
+ app: unit.name,
2147
+ name: unit.name,
2148
+ id: unit.id,
2149
+ host: unit.app,
2150
+ port: PROCESSOR_PORT,
2151
+ prefixes: [...new Set(processors.map((p) => p.prefix))].sort(),
2152
+ ref: validateImageRef(imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
2153
+ tag: options.images.tag,
2154
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
2155
+ };
2156
+ });
2157
+ }
2158
+ /** Each worker's image, and where it is built from. */
2159
+ function stackWorkers(units, options) {
2160
+ return units.map((unit) => ({
2161
+ app: unit.name,
2162
+ name: unit.name,
2163
+ id: unit.id,
2164
+ host: unit.app,
2165
+ port: WORKER_PORT,
2166
+ ref: validateImageRef(imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
2167
+ tag: options.images.tag,
2168
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
2169
+ }));
2170
+ }
2171
+ /**
2172
+ * The host an app answers on for a stage: the `gkm dev` edge's
2173
+ * `*.localhost` names for the local stage, and the stage's domain — by the
2174
+ * same rule a deploy follows — for any other.
2175
+ */
2176
+ function hostOf(name, app, workspace, resource, options) {
2177
+ if (options.local) return hostFor(resource, workspace.name);
2178
+ if (resource.subdomain === WILDCARD_SUBDOMAIN) {
2179
+ const domain = workspace.domains?.[options.stage];
2180
+ if (!domain) throw new NoDomainForStage(options.stage);
2181
+ return `${WILDCARD_SUBDOMAIN}.${domain}`;
2182
+ }
2183
+ return resolveHost(name, app, options.stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
2184
+ }
2185
+ /** An app's compose services, one per replica: `api`, `api-2`, `api-3`. */
2186
+ function replicaNames(app) {
2187
+ return [app.name, ...Array.from({ length: app.replicas - 1 }, (_, i) => `${app.name}-${i + 2}`)];
2188
+ }
2189
+ /** The compose document: the infrastructure, the apps, and the edge. */
2190
+ function stackFile(options) {
2191
+ const { project, plan, apps } = options;
2192
+ const infra = options.infra.filter((name) => name !== LOGS_SERVICE);
2193
+ const derived = composeFor({
2194
+ ...plan,
2195
+ containers: [...infra]
2196
+ }, {
2197
+ project,
2198
+ ports: Object.fromEntries(portKeys(infra, plan.fakes).map((key) => [key, 0])),
2199
+ credentials: options.credentials
2200
+ });
2201
+ const services = {};
2202
+ const volumes = {
2203
+ ...derived.volumes,
2204
+ ...options.proxy === "caddy" ? {
2205
+ "caddy-data": {},
2206
+ "caddy-config": {}
2207
+ } : {},
2208
+ ...options.logs ? { "openobserve-data": {} } : {}
2209
+ };
2210
+ for (const name of infra) {
2211
+ const { ports: _ports, depends_on, profiles: _profiles, ...service } = derived.services[name];
2212
+ services[name] = {
2213
+ ...service,
2214
+ ...depends_on?.length ? { depends_on: Object.fromEntries(depends_on.map((dep) => [dep, HEALTHY])) } : {}
2215
+ };
2216
+ }
2217
+ const postgres = services.postgres;
2218
+ if (postgres) postgres.ports = [`127.0.0.1::${LOOPBACK_SERVICES.postgres}`];
2219
+ const minio = services.minio;
2220
+ if (minio && options.storage) {
2221
+ minio.environment = {
2222
+ ...minio.environment,
2223
+ MINIO_ROOT_USER: options.storage.user,
2224
+ MINIO_ROOT_PASSWORD: options.storage.password,
2225
+ ...minioWebhookEnv(options.storage.webhooks)
2226
+ };
2227
+ minio.ports = [`127.0.0.1::${LOOPBACK_SERVICES.minio}`];
2228
+ }
2229
+ const mailpit = services.mailpit;
2230
+ if (mailpit && options.inboxRelay) mailpit.environment = {
2231
+ ...mailpit.environment,
2232
+ MP_WEBHOOK_URL: options.inboxRelay
2233
+ };
2234
+ if (services["redis"] && options.redis) services[REDIS_SERVICE] = redisService(options.redis);
2235
+ if (options.logs) services[LOGS_SERVICE] = logsService(options.logs);
2236
+ if (options.backups) services[BACKUPS_SERVICE] = backupsService(options.backups, options.envFiles);
2237
+ for (const app of apps) {
2238
+ const definition = {
2239
+ image: app.ref,
2240
+ ...app.build ? { build: {
2241
+ ...composeBuildPaths({
2242
+ composeDir: options.composeDir,
2243
+ buildRoot: options.buildRoot,
2244
+ workspaceRoot: options.workspaceRoot,
2245
+ dockerfile: app.build.dockerfile
2246
+ }),
2247
+ ...app.build.args ? { args: app.build.args } : {}
2248
+ } } : {},
2249
+ restart: "unless-stopped",
2250
+ ...app.kind !== "site" ? {
2251
+ env_file: [{
2252
+ path: `./${app.name}.env`,
2253
+ format: "raw"
2254
+ }],
2255
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {}
2256
+ } : {},
2257
+ healthcheck: probe(app.port, app.kind === "site" ? "/" : "/health"),
2258
+ ...app.kind === "websocket-api" ? { ulimits: { nofile: NOFILE } } : {}
2259
+ };
2260
+ for (const name of replicaNames(app)) services[name] = { ...definition };
2261
+ }
2262
+ for (const worker of [...options.workers, ...options.processors]) services[worker.name] = {
2263
+ image: worker.ref,
2264
+ ...worker.build ? { build: composeBuildPaths({
2265
+ composeDir: options.composeDir,
2266
+ buildRoot: options.buildRoot,
2267
+ workspaceRoot: options.workspaceRoot,
2268
+ dockerfile: worker.build.dockerfile
2269
+ }) } : {},
2270
+ restart: "unless-stopped",
2271
+ env_file: [{
2272
+ path: `./${worker.name}.env`,
2273
+ format: "raw"
2274
+ }],
2275
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {},
2276
+ healthcheck: probe(worker.port, "/health")
2277
+ };
2278
+ if (options.proxy === "caddy") services.caddy = {
2279
+ image: DEFAULT_IMAGES.caddy,
2280
+ restart: "unless-stopped",
2281
+ ports: [`${options.https}:443`, `${options.http}:80`],
2282
+ volumes: ["caddy-data:/data", "caddy-config:/config"],
2283
+ ...EDGE_LIMITS,
2284
+ depends_on: Object.fromEntries([
2285
+ ...apps.flatMap(replicaNames),
2286
+ ...options.workers.filter((w) => w.push).map((w) => w.name),
2287
+ ...options.processors.map((p) => p.name)
2288
+ ].map((name) => [name, HEALTHY])),
2289
+ healthcheck: {
2290
+ test: [
2291
+ "CMD",
2292
+ "caddy",
2293
+ "version"
2294
+ ],
2295
+ interval: "10s",
2296
+ timeout: "5s",
2297
+ retries: 5
2298
+ }
2299
+ };
2300
+ for (const [service, alias] of options.edge) {
2301
+ const definition = services[service];
2302
+ if (!definition) continue;
2303
+ definition.networks = {
2304
+ default: { aliases: [alias] },
2305
+ edge: { aliases: [alias] }
2306
+ };
2307
+ }
2308
+ for (const service of Object.values(services)) {
2309
+ if (!options.envFiles) delete service.env_file;
2310
+ service.logging = {
2311
+ driver: LOG_ROTATION.driver,
2312
+ options: { ...LOG_ROTATION.options }
2313
+ };
2314
+ }
2315
+ return {
2316
+ name: project,
2317
+ services,
2318
+ volumes,
2319
+ ...options.edge.size > 0 ? { networks: { edge: {
2320
+ name: EDGE_NETWORK,
2321
+ external: true
2322
+ } } } : {}
2323
+ };
2324
+ }
2325
+ /**
2326
+ * A build without a layout: the workspace is the build root, with pnpm.
2327
+ * What a caller that never looked at the filesystem gets.
2328
+ */
2329
+ function defaultLayout(root) {
2330
+ return {
2331
+ buildRoot: root,
2332
+ gkmRoot: ".",
2333
+ tools: {
2334
+ packageManager: "pnpm",
2335
+ turboVersion: TURBO_VERSION,
2336
+ monorepo: true
2337
+ },
2338
+ gkmPaths: ["gkm.config.*"]
2339
+ };
2340
+ }
2341
+ /** Render an app's env file: one `KEY=value` per line, read raw by compose. */
2342
+ function envFile(env) {
2343
+ return `${Object.entries(env).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("\n")}\n`;
2344
+ }
2345
+ //#endregion
2346
+ export { RUNNER_PATH as A, RegistryRequired as C, pinnedRef as D, pinImages as E, backupsPrefix as F, runTime as I, stageBackups as L, backupDatabases as M, backupExpiries as N, BACKUPS_SERVICE as O, backupFile as P, deploysWithCompose as R, assertSitePasswords as S, parseDigests as T, EDGE_PROJECT as _, composeProject as a, edgeComposeFile as b, derivedCredentials as c, stackPlan as d, withCaddyConfigs as f, EDGE_NETWORK as g, EDGE_DYNAMIC_DIR as h, LOOPBACK_SERVICES as i, backupsRoleStatements as j, BACKUPS_URL_KEY as k, envFile as l, EDGE_CERTS_DIR as m, LOGS_PORT_ENV as n, composeStack as o, EDGE_AWS_CREDENTIALS as p, LOG_ROTATION as r, deployedInboxEnv as s, EDGE_PORT_ENV as t, stackDir as u, EDGE_SERVICE as v, assertImagesExist as w, traefikStaticFile as x, edgeAlias as y };
2347
+
2348
+ //# sourceMappingURL=stack-BrcNDH_E.mjs.map