@geekmidas/cli 10.0.0-alpha.183 → 10.0.0-alpha.185

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 (245) hide show
  1. package/dist/{LegacyStateStore-BFCqFyEq.cjs → LegacyStateStore-BtN83gfS.cjs} +2 -2
  2. package/dist/{LegacyStateStore-BFCqFyEq.cjs.map → LegacyStateStore-BtN83gfS.cjs.map} +1 -1
  3. package/dist/{LegacyStateStore-FOUMZXuF.mjs → LegacyStateStore-DKyEAWGI.mjs} +2 -2
  4. package/dist/{LegacyStateStore-FOUMZXuF.mjs.map → LegacyStateStore-DKyEAWGI.mjs.map} +1 -1
  5. package/dist/{LocalStateStore-B5DZh9J2.cjs → LocalStateStore-BFh6rPhX.cjs} +2 -2
  6. package/dist/{LocalStateStore-B5DZh9J2.cjs.map → LocalStateStore-BFh6rPhX.cjs.map} +1 -1
  7. package/dist/{LocalStateStore-B7qZNPNd.mjs → LocalStateStore-Dc3aGvQi.mjs} +2 -2
  8. package/dist/{LocalStateStore-B7qZNPNd.mjs.map → LocalStateStore-Dc3aGvQi.mjs.map} +1 -1
  9. package/dist/{S3StateStore-BSh1asHJ.cjs → S3StateStore-DZMpqbvD.cjs} +5 -5
  10. package/dist/{S3StateStore-BSh1asHJ.cjs.map → S3StateStore-DZMpqbvD.cjs.map} +1 -1
  11. package/dist/{S3StateStore-Dy9-O_Ix.mjs → S3StateStore-p6DyuAFZ.mjs} +4 -4
  12. package/dist/{S3StateStore-Dy9-O_Ix.mjs.map → S3StateStore-p6DyuAFZ.mjs.map} +1 -1
  13. package/dist/{SSMStateStore-DQw29x9F.mjs → SSMStateStore-BvH8XX4O.mjs} +2 -2
  14. package/dist/{SSMStateStore-DQw29x9F.mjs.map → SSMStateStore-BvH8XX4O.mjs.map} +1 -1
  15. package/dist/{SSMStateStore-Clw-dnjN.cjs → SSMStateStore-sbaLlCmj.cjs} +2 -2
  16. package/dist/{SSMStateStore-Clw-dnjN.cjs.map → SSMStateStore-sbaLlCmj.cjs.map} +1 -1
  17. package/dist/{add-BbAyKWsD.cjs → add-CdVGxiKW.cjs} +13 -14
  18. package/dist/{add-BbAyKWsD.cjs.map → add-CdVGxiKW.cjs.map} +1 -1
  19. package/dist/{add-BewI_NWg.mjs → add-dOvgsAU6.mjs} +4 -5
  20. package/dist/{add-BewI_NWg.mjs.map → add-dOvgsAU6.mjs.map} +1 -1
  21. package/dist/backups/runner.cjs +501 -13
  22. package/dist/backups/runner.cjs.map +1 -1
  23. package/dist/backups/runner.d.cts +87 -2
  24. package/dist/backups/runner.d.cts.map +1 -1
  25. package/dist/backups/runner.d.mts +87 -2
  26. package/dist/backups/runner.d.mts.map +1 -1
  27. package/dist/backups/runner.mjs +493 -15
  28. package/dist/backups/runner.mjs.map +1 -1
  29. package/dist/{bundler-CKKMaAnQ.cjs → bundler-B5ioF-1Q.cjs} +9 -9
  30. package/dist/{bundler-CKKMaAnQ.cjs.map → bundler-B5ioF-1Q.cjs.map} +1 -1
  31. package/dist/{bundler-FUhPSv3Y.mjs → bundler-Cvx6Bt3e.mjs} +6 -6
  32. package/dist/{bundler-FUhPSv3Y.mjs.map → bundler-Cvx6Bt3e.mjs.map} +1 -1
  33. package/dist/{cli-F4EvxZgK.mjs → cli-BjapgcXG.mjs} +4 -4
  34. package/dist/{cli-F4EvxZgK.mjs.map → cli-BjapgcXG.mjs.map} +1 -1
  35. package/dist/{cli-DBdR2Hqf.cjs → cli-PLhqvPOC.cjs} +6 -6
  36. package/dist/{cli-DBdR2Hqf.cjs.map → cli-PLhqvPOC.cjs.map} +1 -1
  37. package/dist/{clientTelemetry-BAwj6MOf.d.cts → clientTelemetry-Bzc4KXz5.d.mts} +2 -2
  38. package/dist/clientTelemetry-Bzc4KXz5.d.mts.map +1 -0
  39. package/dist/{clientTelemetry-CvamPJj_.d.mts → clientTelemetry-N8NAguGI.d.cts} +2 -2
  40. package/dist/clientTelemetry-N8NAguGI.d.cts.map +1 -0
  41. package/dist/{compose-BWqyiF3p.cjs → compose-BEVBxf4w.cjs} +87 -948
  42. package/dist/compose-BEVBxf4w.cjs.map +1 -0
  43. package/dist/{compose-FHcdMtju.mjs → compose-Dx_nSZYU.mjs} +23 -842
  44. package/dist/compose-Dx_nSZYU.mjs.map +1 -0
  45. package/dist/{config-C3U5HulX.d.cts → config-CTrfNKYd.d.mts} +3 -3
  46. package/dist/{config-BODxZemw.d.mts.map → config-CTrfNKYd.d.mts.map} +1 -1
  47. package/dist/{config-BODxZemw.d.mts → config-D9g_nYIu.d.cts} +3 -3
  48. package/dist/{config-C3U5HulX.d.cts.map → config-D9g_nYIu.d.cts.map} +1 -1
  49. package/dist/config.cjs +1 -1
  50. package/dist/config.d.cts +3 -3
  51. package/dist/config.d.mts +3 -3
  52. package/dist/config.mjs +1 -1
  53. package/dist/{compose-Dx1qWkqA.mjs → credentials-DW5MvS4A.mjs} +1148 -1261
  54. package/dist/credentials-DW5MvS4A.mjs.map +1 -0
  55. package/dist/{compose-uWAls-tD.cjs → credentials-Eyx2tM7B.cjs} +1175 -1288
  56. package/dist/credentials-Eyx2tM7B.cjs.map +1 -0
  57. package/dist/{dns-zWyF3BB0.cjs → credentials-n2abUWwJ.cjs} +6 -847
  58. package/dist/credentials-n2abUWwJ.cjs.map +1 -0
  59. package/dist/{dns-w28G3uDJ.mjs → credentials-ztezRtR4.mjs} +5 -708
  60. package/dist/credentials-ztezRtR4.mjs.map +1 -0
  61. package/dist/{dbTunnel-dzS96iTb.cjs → dbTunnel-DVohSZJQ.cjs} +8 -9
  62. package/dist/{dbTunnel-dzS96iTb.cjs.map → dbTunnel-DVohSZJQ.cjs.map} +1 -1
  63. package/dist/{dbTunnel-DVgW5GGr.mjs → dbTunnel-bV1CPWUv.mjs} +5 -6
  64. package/dist/{dbTunnel-DVgW5GGr.mjs.map → dbTunnel-bV1CPWUv.mjs.map} +1 -1
  65. package/dist/deploy/public.cjs +25 -26
  66. package/dist/deploy/public.cjs.map +1 -1
  67. package/dist/deploy/public.d.cts +5 -5
  68. package/dist/deploy/public.d.mts +5 -5
  69. package/dist/deploy/public.mjs +10 -11
  70. package/dist/deploy/public.mjs.map +1 -1
  71. package/dist/{deploy-B1n2hPbI.cjs → deploy-CDUWcl58.cjs} +72 -62
  72. package/dist/deploy-CDUWcl58.cjs.map +1 -0
  73. package/dist/{deploy-SsifvmBB.mjs → deploy-Cpz5sKbh.mjs} +25 -15
  74. package/dist/deploy-Cpz5sKbh.mjs.map +1 -0
  75. package/dist/{destroy-CHigTrDO.mjs → destroy-DRlcWJwm.mjs} +9 -9
  76. package/dist/{destroy-CHigTrDO.mjs.map → destroy-DRlcWJwm.mjs.map} +1 -1
  77. package/dist/{destroy-Bn6d47rP.cjs → destroy-DzeV0EdY.cjs} +21 -21
  78. package/dist/{destroy-Bn6d47rP.cjs.map → destroy-DzeV0EdY.cjs.map} +1 -1
  79. package/dist/{dokploy-CnnrFOBH.cjs → dokploy-BTNfj3Zt.cjs} +2 -2
  80. package/dist/{dokploy-CnnrFOBH.cjs.map → dokploy-BTNfj3Zt.cjs.map} +1 -1
  81. package/dist/{dokploy-BzfI7ZE0.mjs → dokploy-BveqiW2h.mjs} +2 -2
  82. package/dist/{dokploy-BzfI7ZE0.mjs.map → dokploy-BveqiW2h.mjs.map} +1 -1
  83. package/dist/{eas-CZ3ZuWTs.mjs → eas-BmYTfjY6.mjs} +3 -3
  84. package/dist/{eas-CZ3ZuWTs.mjs.map → eas-BmYTfjY6.mjs.map} +1 -1
  85. package/dist/{eas-BTOGceIO.cjs → eas-Dt_vRzb4.cjs} +3 -3
  86. package/dist/{eas-BTOGceIO.cjs.map → eas-Dt_vRzb4.cjs.map} +1 -1
  87. package/dist/{encryption-BHGCfu6X.cjs → encryption-BE2wxfyH.cjs} +6 -6
  88. package/dist/{encryption-BHGCfu6X.cjs.map → encryption-BE2wxfyH.cjs.map} +1 -1
  89. package/dist/{encryption-CocJ18w4.mjs → encryption-DqoQltP8.mjs} +3 -3
  90. package/dist/{encryption-CocJ18w4.mjs.map → encryption-DqoQltP8.mjs.map} +1 -1
  91. package/dist/{engine-B0AwceAI.mjs → engine-B72vyrO8.mjs} +7 -9
  92. package/dist/{engine-B0AwceAI.mjs.map → engine-B72vyrO8.mjs.map} +1 -1
  93. package/dist/{engine-3460tLKl.cjs → engine-BevpkNZe.cjs} +100 -102
  94. package/dist/{engine-3460tLKl.cjs.map → engine-BevpkNZe.cjs.map} +1 -1
  95. package/dist/{github-DMQSq0Jm.cjs → github-DoHdtsDX.cjs} +18 -18
  96. package/dist/{github-DMQSq0Jm.cjs.map → github-DoHdtsDX.cjs.map} +1 -1
  97. package/dist/{github-BqYhgU8Y.mjs → github-hxvid6J3.mjs} +7 -7
  98. package/dist/{github-BqYhgU8Y.mjs.map → github-hxvid6J3.mjs.map} +1 -1
  99. package/dist/{googlePlay-DTQ_epbl.cjs → googlePlay-CYney-Of.cjs} +5 -5
  100. package/dist/{googlePlay-DTQ_epbl.cjs.map → googlePlay-CYney-Of.cjs.map} +1 -1
  101. package/dist/{googlePlay-y4fWdG2Z.mjs → googlePlay-DsvZTWgP.mjs} +4 -4
  102. package/dist/{googlePlay-y4fWdG2Z.mjs.map → googlePlay-DsvZTWgP.mjs.map} +1 -1
  103. package/dist/{iam-BzFyFf7T.mjs → iam-DloEBLXZ.mjs} +2 -2
  104. package/dist/{iam-BzFyFf7T.mjs.map → iam-DloEBLXZ.mjs.map} +1 -1
  105. package/dist/{iam-WIoKnLBp.cjs → iam-SxPKYCI_.cjs} +2 -2
  106. package/dist/{iam-WIoKnLBp.cjs.map → iam-SxPKYCI_.cjs.map} +1 -1
  107. package/dist/{index-zPzigXh-.d.cts → index-BThTZV8T.d.mts} +2 -2
  108. package/dist/{index-BKgOlfK2.d.mts.map → index-BThTZV8T.d.mts.map} +1 -1
  109. package/dist/{index-BKgOlfK2.d.mts → index-Cgd-ouyI.d.cts} +2 -2
  110. package/dist/{index-zPzigXh-.d.cts.map → index-Cgd-ouyI.d.cts.map} +1 -1
  111. package/dist/index.cjs +590 -246
  112. package/dist/index.cjs.map +1 -1
  113. package/dist/index.mjs +443 -99
  114. package/dist/index.mjs.map +1 -1
  115. package/dist/{local-CZbNAWuZ.cjs → local-BuR4fIW6.cjs} +3 -3
  116. package/dist/{local-CZbNAWuZ.cjs.map → local-BuR4fIW6.cjs.map} +1 -1
  117. package/dist/{local-DJuonm2r.mjs → local-Cmq75U_o.mjs} +2 -2
  118. package/dist/{local-DJuonm2r.mjs.map → local-Cmq75U_o.mjs.map} +1 -1
  119. package/dist/{migrate-DU4G7xbh.mjs → migrate-Bf-EG8Fj.mjs} +5 -5
  120. package/dist/{migrate-DU4G7xbh.mjs.map → migrate-Bf-EG8Fj.mjs.map} +1 -1
  121. package/dist/{migrate-CJNgQxYs.cjs → migrate-CDMdrniJ.cjs} +13 -13
  122. package/dist/{migrate-CJNgQxYs.cjs.map → migrate-CDMdrniJ.cjs.map} +1 -1
  123. package/dist/{migrate-DXLhzkls.cjs → migrate-CuTQha4s.cjs} +6 -6
  124. package/dist/{migrate-DXLhzkls.cjs.map → migrate-CuTQha4s.cjs.map} +1 -1
  125. package/dist/{migrate-D79KnjFu.mjs → migrate-DYJffHOm.mjs} +3 -3
  126. package/dist/{migrate-D79KnjFu.mjs.map → migrate-DYJffHOm.mjs.map} +1 -1
  127. package/dist/openapi.cjs +1 -1
  128. package/dist/openapi.d.cts +2 -2
  129. package/dist/openapi.d.mts +2 -2
  130. package/dist/openapi.mjs +1 -1
  131. package/dist/{projectBucket-rVF15Mu-.mjs → projectBucket-B5YkuSVr.mjs} +2 -2
  132. package/dist/{projectBucket-rVF15Mu-.mjs.map → projectBucket-B5YkuSVr.mjs.map} +1 -1
  133. package/dist/{projectBucket-BoH-BJPI.cjs → projectBucket-NcgqleyH.cjs} +2 -2
  134. package/dist/{projectBucket-BoH-BJPI.cjs.map → projectBucket-NcgqleyH.cjs.map} +1 -1
  135. package/dist/{publish-DBDdm5Dz.cjs → publish--EQ4Tw3F.cjs} +2 -2
  136. package/dist/{publish-DBDdm5Dz.cjs.map → publish--EQ4Tw3F.cjs.map} +1 -1
  137. package/dist/{publish-EaWW1vhe.mjs → publish-YL8WZHSo.mjs} +2 -2
  138. package/dist/{publish-EaWW1vhe.mjs.map → publish-YL8WZHSo.mjs.map} +1 -1
  139. package/dist/{ready--_hMxbUX.cjs → ready-DCvnFZnJ.cjs} +2 -2
  140. package/dist/{ready--_hMxbUX.cjs.map → ready-DCvnFZnJ.cjs.map} +1 -1
  141. package/dist/{ready-CjIqXFXe.mjs → ready-sSPuiZ7N.mjs} +2 -2
  142. package/dist/{ready-CjIqXFXe.mjs.map → ready-sSPuiZ7N.mjs.map} +1 -1
  143. package/dist/reconcile/public.d.cts +1 -1
  144. package/dist/reconcile/public.d.mts +1 -1
  145. package/dist/{resolve-De0Dw9wI.cjs → resolve-Ced8-gj4.cjs} +4 -4
  146. package/dist/{resolve-De0Dw9wI.cjs.map → resolve-Ced8-gj4.cjs.map} +1 -1
  147. package/dist/{resolve-DLUOV7Tt.mjs → resolve-DcG10_JV.mjs} +4 -4
  148. package/dist/{resolve-DLUOV7Tt.mjs.map → resolve-DcG10_JV.mjs.map} +1 -1
  149. package/dist/{rollback-bDh-dBGa.mjs → rollback-BxI2p53H.mjs} +7 -6
  150. package/dist/{rollback-bDh-dBGa.mjs.map → rollback-BxI2p53H.mjs.map} +1 -1
  151. package/dist/{rollback-61Be6ASD.cjs → rollback-C6bCANv7.cjs} +10 -9
  152. package/dist/{rollback-61Be6ASD.cjs.map → rollback-C6bCANv7.cjs.map} +1 -1
  153. package/dist/{runtime-CaejlcZt.d.mts → runtime-BtoiRP5G.d.cts} +2 -2
  154. package/dist/{runtime-CaejlcZt.d.mts.map → runtime-BtoiRP5G.d.cts.map} +1 -1
  155. package/dist/{runtime-D3jD4Dvn.d.cts → runtime-Ct41f0tN.d.mts} +2 -2
  156. package/dist/{runtime-D3jD4Dvn.d.cts.map → runtime-Ct41f0tN.d.mts.map} +1 -1
  157. package/dist/{s3-CRLJjozN.mjs → s3-BAI0ELtE.mjs} +3 -3
  158. package/dist/{s3-CRLJjozN.mjs.map → s3-BAI0ELtE.mjs.map} +1 -1
  159. package/dist/{s3-Bw-Cpb0k.cjs → s3-DucPHZAn.cjs} +3 -3
  160. package/dist/{s3-Bw-Cpb0k.cjs.map → s3-DucPHZAn.cjs.map} +1 -1
  161. package/dist/{serverSetup-DkKFG--v.cjs → serverSetup-D3-FE7Dj.cjs} +9 -8
  162. package/dist/{serverSetup-DkKFG--v.cjs.map → serverSetup-D3-FE7Dj.cjs.map} +1 -1
  163. package/dist/{serverSetup-9BMKflju.mjs → serverSetup-DS9tW50_.mjs} +7 -6
  164. package/dist/{serverSetup-9BMKflju.mjs.map → serverSetup-DS9tW50_.mjs.map} +1 -1
  165. package/dist/{sniffer-PDjJ-6ki.mjs → sniffer-CX8sI8Cu.mjs} +7 -7
  166. package/dist/{sniffer-PDjJ-6ki.mjs.map → sniffer-CX8sI8Cu.mjs.map} +1 -1
  167. package/dist/{sniffer-Dss2_3q7.cjs → sniffer-XlvJLrhZ.cjs} +7 -7
  168. package/dist/{sniffer-Dss2_3q7.cjs.map → sniffer-XlvJLrhZ.cjs.map} +1 -1
  169. package/dist/{snsSubscriptions-BA4UEQDb.cjs → snsSubscriptions-CJAOhWq9.cjs} +11 -12
  170. package/dist/{snsSubscriptions-BA4UEQDb.cjs.map → snsSubscriptions-CJAOhWq9.cjs.map} +1 -1
  171. package/dist/{snsSubscriptions-BwwRq60H.mjs → snsSubscriptions-DDrra9rN.mjs} +3 -4
  172. package/dist/{snsSubscriptions-BwwRq60H.mjs.map → snsSubscriptions-DDrra9rN.mjs.map} +1 -1
  173. package/dist/{sst-xWQPl_tB.mjs → sst-CdHflajE.mjs} +6 -6
  174. package/dist/{sst-xWQPl_tB.mjs.map → sst-CdHflajE.mjs.map} +1 -1
  175. package/dist/{sst-Dy-LThkf.cjs → sst-CsEjVFtz.cjs} +8 -8
  176. package/dist/{sst-Dy-LThkf.cjs.map → sst-CsEjVFtz.cjs.map} +1 -1
  177. package/dist/stack-BYhtz-bE.cjs +11449 -0
  178. package/dist/stack-BYhtz-bE.cjs.map +1 -0
  179. package/dist/stack-CLHY-_2m.mjs +10474 -0
  180. package/dist/stack-CLHY-_2m.mjs.map +1 -0
  181. package/dist/{stage-BsdW3fQh.cjs → stage-Bc_BtQeG.cjs} +11 -12
  182. package/dist/stage-Bc_BtQeG.cjs.map +1 -0
  183. package/dist/{stage-ZBO62mNs.mjs → stage-C7aYyDMr.mjs} +5 -6
  184. package/dist/stage-C7aYyDMr.mjs.map +1 -0
  185. package/dist/{stages-DjFKQv08.mjs → stages-DFvE7iEO.mjs} +2 -2
  186. package/dist/{stages-DjFKQv08.mjs.map → stages-DFvE7iEO.mjs.map} +1 -1
  187. package/dist/{stages-BeSQQQ4z.cjs → stages-Dk6Lv7DY.cjs} +2 -2
  188. package/dist/{stages-BeSQQQ4z.cjs.map → stages-Dk6Lv7DY.cjs.map} +1 -1
  189. package/dist/target/public.cjs +1 -1
  190. package/dist/target/public.d.cts +2 -2
  191. package/dist/target/public.d.mts +2 -2
  192. package/dist/target/public.mjs +1 -1
  193. package/dist/{terminal-DUQ0yaZQ.mjs → terminal-BZzK69T9.mjs} +2 -2
  194. package/dist/{terminal-DUQ0yaZQ.mjs.map → terminal-BZzK69T9.mjs.map} +1 -1
  195. package/dist/{terminal-DhPb_CKf.cjs → terminal-DXUXlqrO.cjs} +5 -5
  196. package/dist/{terminal-DhPb_CKf.cjs.map → terminal-DXUXlqrO.cjs.map} +1 -1
  197. package/dist/{types-CLxsw-QY.d.cts → types-BVDaaLas.d.cts} +26 -7
  198. package/dist/{types-CLxsw-QY.d.cts.map → types-BVDaaLas.d.cts.map} +1 -1
  199. package/dist/{types-wLlwkSib.d.mts → types-CJTKWLkK.d.mts} +26 -7
  200. package/dist/{types-wLlwkSib.d.mts.map → types-CJTKWLkK.d.mts.map} +1 -1
  201. package/dist/{utils-D_fxUqvU.mjs → utils-CdKxD8Lt.mjs} +2 -2
  202. package/dist/{utils-D_fxUqvU.mjs.map → utils-CdKxD8Lt.mjs.map} +1 -1
  203. package/dist/{utils-D2Nk1Nv2.cjs → utils-DBqXbB8P.cjs} +2 -2
  204. package/dist/{utils-D2Nk1Nv2.cjs.map → utils-DBqXbB8P.cjs.map} +1 -1
  205. package/dist/vitest.cjs +1 -1
  206. package/dist/vitest.mjs +1 -1
  207. package/dist/workspace/index.cjs +1 -1
  208. package/dist/workspace/index.d.cts +2 -2
  209. package/dist/workspace/index.d.mts +2 -2
  210. package/dist/workspace/index.mjs +1 -1
  211. package/dist/{workspace-wTLnc1Ef.cjs → workspace-CTspddnJ.cjs} +62 -22
  212. package/dist/workspace-CTspddnJ.cjs.map +1 -0
  213. package/dist/{workspace-DJjhfAGf.mjs → workspace-CdiCMRap.mjs} +62 -22
  214. package/dist/workspace-CdiCMRap.mjs.map +1 -0
  215. package/package.json +16 -16
  216. package/dist/apps-CQqhCjg4.mjs +0 -4650
  217. package/dist/apps-CQqhCjg4.mjs.map +0 -1
  218. package/dist/apps-DWq98qHY.cjs +0 -5174
  219. package/dist/apps-DWq98qHY.cjs.map +0 -1
  220. package/dist/clientTelemetry-BAwj6MOf.d.cts.map +0 -1
  221. package/dist/clientTelemetry-CvamPJj_.d.mts.map +0 -1
  222. package/dist/compose-BWqyiF3p.cjs.map +0 -1
  223. package/dist/compose-Dx1qWkqA.mjs.map +0 -1
  224. package/dist/compose-FHcdMtju.mjs.map +0 -1
  225. package/dist/compose-uWAls-tD.cjs.map +0 -1
  226. package/dist/deploy-B1n2hPbI.cjs.map +0 -1
  227. package/dist/deploy-SsifvmBB.mjs.map +0 -1
  228. package/dist/dns-w28G3uDJ.mjs.map +0 -1
  229. package/dist/dns-zWyF3BB0.cjs.map +0 -1
  230. package/dist/docker-DDiEfZox.mjs +0 -1649
  231. package/dist/docker-DDiEfZox.mjs.map +0 -1
  232. package/dist/docker-Dox4VZcA.cjs +0 -1798
  233. package/dist/docker-Dox4VZcA.cjs.map +0 -1
  234. package/dist/notes-CF_NOgxM.cjs +0 -510
  235. package/dist/notes-CF_NOgxM.cjs.map +0 -1
  236. package/dist/notes-Dwc9WLvg.mjs +0 -409
  237. package/dist/notes-Dwc9WLvg.mjs.map +0 -1
  238. package/dist/stack-BQKXw0dX.cjs +0 -1887
  239. package/dist/stack-BQKXw0dX.cjs.map +0 -1
  240. package/dist/stack-pftB9Sqp.mjs +0 -1777
  241. package/dist/stack-pftB9Sqp.mjs.map +0 -1
  242. package/dist/stage-BsdW3fQh.cjs.map +0 -1
  243. package/dist/stage-ZBO62mNs.mjs.map +0 -1
  244. package/dist/workspace-DJjhfAGf.mjs.map +0 -1
  245. package/dist/workspace-wTLnc1Ef.cjs.map +0 -1
@@ -1,1649 +0,0 @@
1
- import { t as GkmError } from "./errors-C9uIyIDt.mjs";
2
- import { it as run } from "./dns-w28G3uDJ.mjs";
3
- import { ot as appKey } from "./workspace-DJjhfAGf.mjs";
4
- import { A as imageLayout, B as generateEntryDockerfile, C as PROCESSOR_ORIGIN_SECRET_ENV, D as appImageOptions, F as WORKER_PORT, G as generateWorkerDockerfile, H as generateNodeWebDockerfile, N as PROCESSOR_PORT, R as generateBackendDockerfile, S as ORIGIN_VERIFY_HEADER, U as generateProcessorDockerfile, V as generateNextjsDockerfile, W as generateViteStaticDockerfile, g as COMPOSE_PATH, i as dockerfileOf, it as workerUnits, m as reconcileWorkspace, nt as processorUnitName, q as resolveDockerConfig, rt as processorUnits, z as generateDockerignore } from "./apps-CQqhCjg4.mjs";
5
- import { Et as getPublicUrlArgNames, P as siteClientTelemetry, rt as PROCESSORS_DEV_PREFIX } from "./compose-Dx1qWkqA.mjs";
6
- import { t as SubscriberGenerator } from "./SubscriberGenerator-Cfoz8uTY.mjs";
7
- import { a as handlerEventsBackends, c as publishesToApiGateway, l as readsObjects, n as driversFor, r as driversOf, s as opensKmsKeys, t as cacheBackendsIn } from "./drivers-BQRb3KsL.mjs";
8
- import { a as startTelemetryCode, n as runtimeFor, s as writeTelemetryModule } from "./EndpointGenerator-CBKH87_b.mjs";
9
- import { r as consumedBy, v as ConstructGenerator, y as output } from "./discover-Dfmn6HQ7.mjs";
10
- import { loadWorkspaceConfig } from "./config.mjs";
11
- import { dirname, join, relative, resolve } from "node:path";
12
- import { existsSync } from "node:fs";
13
- import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
14
- import { canonicalId, dependenciesOf, imageOriginsFor, providedKeyFor, publicEnvFor } from "@geekmidas/manifest";
15
- import { Cron } from "@geekmidas/constructs/crons";
16
- import { Processor } from "@geekmidas/constructs/processors";
17
- import { Queue } from "@geekmidas/constructs/queue";
18
- //#region src/docker/imageRef.ts
19
- /**
20
- * An image reference, checked before it reaches `docker`.
21
- *
22
- * The parts come from the workspace — a registry in `gkm.config.ts`, an image
23
- * name from the project, a tag from `--tag` — and an argument array already
24
- * keeps them out of a shell. What it cannot do is stop `docker` reading a value
25
- * that starts with `-` as one of its own flags, so a ref is held to Docker's
26
- * own grammar (distribution/reference) and anything else is refused by name
27
- * before a build starts.
28
- */
29
- const DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
30
- const DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
31
- const PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
32
- const REFERENCE = new RegExp(`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::[\\w][\\w.-]{0,127})?(?:@[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,})?$`);
33
- /** Docker refuses a repository name longer than this. */
34
- const MAX_NAME_LENGTH = 255;
35
- /** A value that is not an image reference was about to be built or pushed. */
36
- var ImageRefInvalid = class extends GkmError {
37
- ref;
38
- constructor(ref) {
39
- super(`'${ref}' is not a valid image reference. An image is \`[registry/]name[:tag]\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`);
40
- this.ref = ref;
41
- this.name = "ImageRefInvalid";
42
- }
43
- };
44
- /** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */
45
- function validateImageRef(ref) {
46
- const name = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
47
- if (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) throw new ImageRefInvalid(ref);
48
- return ref;
49
- }
50
- //#endregion
51
- //#region src/build/types.ts
52
- /**
53
- * Where `gkm dev` serves the database's read-only JSON API
54
- * (`@geekmidas/db/introspect`). Under `/__gkm` with the rest of what the dev
55
- * server adds, so it cannot collide with an application route.
56
- */
57
- const DEV_DATABASE_API_PATH = "/__gkm/db";
58
- //#endregion
59
- //#region src/build/owners.ts
60
- /**
61
- * What a generated entry imports its runtime from, read off the discovered
62
- * constructs: the surface it serves, every construct a runnable can be built
63
- * from, and the database the dev server's JSON API reads.
64
- *
65
- * `gkm build` and `gkm dev` both write entries that import the surface for its
66
- * logger and environment parser, so both ask here. A dev server that skipped it
67
- * had nothing to import them from.
68
- */
69
- function ownersContext(options) {
70
- const { declared, sources, workspaceRoot, appRoot, app, databaseApi } = options;
71
- const surfaces = restApis(declared);
72
- const primary = servedSurface(declared, workspaceRoot, appRoot, app) ?? surfaces.find((d) => !d.servesItself) ?? surfaces[0];
73
- const browsable = Object.entries(declared).find(([, d]) => d.kind === "database");
74
- const browsableSource = browsable ? sources[browsable[0]] : void 0;
75
- const owners = {};
76
- for (const [id, declaration] of Object.entries(declared)) {
77
- if (declaration.kind !== "rest-api" && declaration.kind !== "worker") continue;
78
- const source = sources[id];
79
- if (!source) continue;
80
- owners[id] = {
81
- specifier: source.file,
82
- exportName: source.exportName
83
- };
84
- }
85
- const primarySource = primary ? sources[primary.id] : void 0;
86
- return {
87
- owners,
88
- ...primary ? { surface: {
89
- id: primary.id,
90
- trustedOriginsKey: providedKeyFor(primary.id, "rest-api", "trustedOrigins"),
91
- ...primary.cors ? { cors: primary.cors } : {},
92
- ...primarySource ? { module: {
93
- specifier: primarySource.file,
94
- exportName: primarySource.exportName
95
- } } : {}
96
- } } : {},
97
- ...databaseApi && browsableSource ? { databaseApi: {
98
- path: DEV_DATABASE_API_PATH,
99
- database: {
100
- specifier: browsableSource.file,
101
- exportName: browsableSource.exportName
102
- }
103
- } } : {}
104
- };
105
- }
106
- /**
107
- * The endpoints one surface serves.
108
- *
109
- * One glob finds every surface's endpoints, wherever their files live. A build
110
- * keeps the ones built from the surface it serves; one built from no surface at
111
- * all has nowhere else to go.
112
- */
113
- function servedBy(endpoints, surface) {
114
- if (!surface) return endpoints;
115
- return endpoints.filter(({ construct }) => !construct.surface || construct.surface.id === surface.id);
116
- }
117
- function restApis(declared) {
118
- return Object.values(declared).filter((d) => d.kind === "rest-api");
119
- }
120
- /**
121
- * The surface whose declared `path` is the directory being built — asked of
122
- * every surface, because a workspace has several and each app's build serves
123
- * exactly one.
124
- *
125
- * Two surfaces can share a directory — an API and its webhooks, both
126
- * `apps/api` — so the folder alone does not say which is being built. The app
127
- * does: each surface is the app its id names, `Webhooks` is `webhooks`. A
128
- * directory holding one surface needs no name, and a build that gives none
129
- * gets the first, as it always did.
130
- *
131
- * Undefined when the named app is another kind of surface in the same
132
- * directory — a WebSocket API beside a RestApi is not the RestApi.
133
- */
134
- function servedSurface(declared, workspaceRoot, appRoot, app) {
135
- const served = surfaceAt(declared, workspaceRoot, appRoot, app);
136
- return served?.kind === "rest-api" ? served : void 0;
137
- }
138
- /**
139
- * The surface — a RestApi, or a WebSocket API — an app's build serves: the
140
- * one in its directory that the app is named for, else the first RestApi
141
- * there, else the first WebSocket API.
142
- */
143
- function surfaceAt(declared, workspaceRoot, appRoot, app) {
144
- const here = Object.values(declared).filter((d) => (d.kind === "rest-api" || d.kind === "websocket-api") && resolve(workspaceRoot, d.path) === resolve(appRoot));
145
- return (app !== void 0 ? here.find((d) => appKey(d.id) === app) : void 0) ?? here.find((d) => d.kind === "rest-api") ?? here.find((d) => d.kind === "websocket-api");
146
- }
147
- /**
148
- * The declarations one process reaches: the constructs it runs as — a surface,
149
- * a worker — what each declared an edge to, and what each runnable it runs
150
- * depends on or consumes.
151
- *
152
- * What decides which drivers its entry registers: a process that reaches no
153
- * cache never resolves a cache client because another process in the
154
- * workspace does.
155
- */
156
- function reachedBy(declared, processes, runnables) {
157
- const reached = /* @__PURE__ */ new Set();
158
- for (const id of processes) {
159
- const declaration = declared[id];
160
- if (!declaration) continue;
161
- reached.add(id);
162
- for (const edge of dependenciesOf(declaration)) reached.add(edge.target);
163
- }
164
- for (const { construct } of runnables) {
165
- for (const id of construct.constructs ?? []) reached.add(canonicalId(id));
166
- for (const id of consumedBy(construct)) reached.add(id);
167
- }
168
- return Object.fromEntries(Object.entries(declared).filter(([id]) => reached.has(id)));
169
- }
170
- /**
171
- * The declarations one Lambda handler reaches: its owner — the surface or
172
- * worker it was built from — with that owner's own edges, and what the
173
- * runnable itself depends on or consumes. The same reach `reachedBy` gives a
174
- * process, for a process that runs exactly one construct.
175
- *
176
- * A surface's own edges, not its routes': `dependenciesOf` folds every
177
- * endpoint's edges into its surface's, which is right for a server running
178
- * them all and wrong for a Lambda running one — a handler that reaches no
179
- * topic would register a broker because a sibling route publishes.
180
- *
181
- * Undefined where the owner is unknown — a construct from a free-standing
182
- * builder, or one whose owner was not discovered — so the caller can fall
183
- * back to the drivers of the whole app rather than guess.
184
- */
185
- function reachedByHandler(declared, construct) {
186
- if (!construct.owner) return void 0;
187
- const ownerId = declared[construct.owner] ? construct.owner : canonicalId(construct.owner);
188
- const owner = declared[ownerId];
189
- if (!owner) return void 0;
190
- const own = owner.kind === "rest-api" ? {
191
- ...owner,
192
- endpoints: []
193
- } : owner.kind === "websocket-api" ? {
194
- ...owner,
195
- routes: []
196
- } : owner;
197
- const processes = owner.kind === "file-server" ? [ownerId, owner.of] : [ownerId];
198
- return reachedBy({
199
- ...declared,
200
- [ownerId]: own
201
- }, processes, [{ construct }]);
202
- }
203
- /**
204
- * The drivers each AWS handler registers, from {@link reachedByHandler}: the
205
- * cache's, the broker's, the KMS cipher, the API Gateway sink and S3, each
206
- * only where the construct reaches what needs it.
207
- *
208
- * Undefined for a construct whose reach is unknown, so the generator falls
209
- * back to the app's whole set — the safe answer, and the old one.
210
- */
211
- function handlerDriversFor(options) {
212
- return (construct) => {
213
- const reach = reachedByHandler(options.declared, construct);
214
- if (!reach) return void 0;
215
- return driversFor({
216
- appRoot: options.appRoot,
217
- cache: cacheBackendsIn(reach, options.cacheBackend),
218
- events: handlerEventsBackends(reach, options.eventsBackend),
219
- kms: opensKmsKeys(reach, "aws"),
220
- apiGatewayWebSockets: publishesToApiGateway(reach, "aws"),
221
- storage: readsObjects(reach)
222
- });
223
- };
224
- }
225
- //#endregion
226
- //#region src/build/outputDir.ts
227
- /**
228
- * The name of the tree an app's build writes under, when its directory holds
229
- * more than one surface — the app key of the surface it serves, `webhooks` —
230
- * or undefined for a directory with one.
231
- *
232
- * Two surfaces can name one folder — an API and its webhooks, `path:
233
- * 'apps/api'` both — and each is an app of its own, with its own endpoints.
234
- * Their builds cannot share one output tree: an AWS build empties its tree
235
- * first, so the second app's would delete the first's handlers, and a server
236
- * build would overwrite the first's entry with its own.
237
- *
238
- * Counted from the declared surfaces rather than the workspace's apps: a
239
- * single-app config's `api` sits at `.` beside the app its surface derives, and
240
- * that is one app, not two.
241
- */
242
- function sharedDirectoryTree(declared, workspaceRoot, appRoot, app) {
243
- if (Object.values(declared).filter((d) => (d.kind === "rest-api" || d.kind === "websocket-api") && resolve(workspaceRoot, d.path) === resolve(appRoot)).length < 2) return void 0;
244
- const served = surfaceAt(declared, workspaceRoot, appRoot, app);
245
- return served ? appKey(served.id) : void 0;
246
- }
247
- /**
248
- * Where one app's build writes for a target: `<app>/.gkm/<target>`.
249
- *
250
- * An app that shares its directory gets a tree of its own under that,
251
- * `<app>/.gkm/<target>/<tree>`, so its build replaces nothing another app
252
- * wrote. An app alone in its directory — nearly every one — keeps the path it
253
- * always had, so no handler a deploy already points at moves.
254
- */
255
- function appOutputDir(appRoot, target, tree) {
256
- const base = join(appRoot, ".gkm", target);
257
- return tree ? join(base, tree) : base;
258
- }
259
- //#endregion
260
- //#region src/generators/ProcessorGenerator.ts
261
- /** Where a file server's processor entry lives, under an app's `.gkm/server`. */
262
- function processorEntryDir(serverDir, fileServerId) {
263
- return join(serverDir, "processors", processorUnitName(fileServerId));
264
- }
265
- /** The file its bundle is written to, beside the server's. */
266
- function processorBundleName(fileServerId) {
267
- return `${processorUnitName(fileServerId)}.mjs`;
268
- }
269
- /**
270
- * A file server's processors, as the build generates them.
271
- *
272
- * On AWS each is a Lambda behind a function URL — the CDN's origin for its
273
- * pattern. On a server they are one process per file server, the processor
274
- * unit (see {@link ProcessorGenerator.buildEntry}), so the `server` target
275
- * generates nothing per processor here.
276
- */
277
- var ProcessorGenerator = class extends ConstructGenerator {
278
- isConstruct(value) {
279
- return Processor.isProcessor(value);
280
- }
281
- async build(context, constructs, outputDir, options) {
282
- if ((options?.target ?? "aws") !== "aws" || constructs.length === 0) return [];
283
- const dir = join(outputDir, "processors");
284
- await mkdir(dir, { recursive: true });
285
- const infos = [];
286
- for (const { key, construct, path } of constructs) {
287
- const file = join(dir, `${key}.ts`);
288
- const importPath = relative(dirname(file), path.relative).replace(/\.ts$/, ".js");
289
- const drivers = driversOf(context, construct);
290
- await writeFile(file, `import { AWSLambdaProcessor } from '@geekmidas/constructs/processors';
291
- import { ${key} } from '${importPath}';
292
- ${drivers?.imports ?? ""}
293
- ${drivers?.setup ? `\n// The handler registers the drivers its target needs.\n${drivers.setup}\n` : ""}
294
- const adapter = new AWSLambdaProcessor(${key});
295
-
296
- export const handler = adapter.handler;
297
- `);
298
- infos.push(await processorInfo(key, construct, relative(options?.root ?? process.cwd(), file).replace(/\.ts$/, ".handler"), context));
299
- }
300
- return infos;
301
- }
302
- /**
303
- * `gkm dev`'s half: `processors.ts` beside the dev server's app, mounting
304
- * each file server's processors under `/__gkm/processors/<FileServer>`.
305
- * The local edge sends each pattern on the file server's host there, so
306
- * `processedUrl()` answers locally as it does deployed.
307
- *
308
- * In the dev server's own process rather than a unit of its own: locally
309
- * there is no CPU to protect, and the dev server already reloads on change.
310
- */
311
- async buildDev(outputDir, processors) {
312
- await mkdir(outputDir, { recursive: true });
313
- const file = join(outputDir, "processors.ts");
314
- const imports = processors.map(({ key, path }) => {
315
- const specifier = relative(outputDir, path.absolute).replace(/\.ts$/, ".js");
316
- return `import { ${key} } from '${specifier.startsWith(".") ? specifier : `./${specifier}`}';`;
317
- }).join("\n");
318
- const byServer = /* @__PURE__ */ new Map();
319
- for (const { key, construct } of processors) byServer.set(construct.surfaceId, [...byServer.get(construct.surfaceId) ?? [], key]);
320
- const units = [...byServer.entries()].map(([id, keys]) => ` ${JSON.stringify(id)}: [${keys.join(", ")}],`).join("\n");
321
- await writeFile(file, `/**
322
- * Generated processors setup for \`gkm dev\`.
323
- *
324
- * Each file server's processors, under ${PROCESSORS_DEV_PREFIX}<FileServer>: the
325
- * local edge rewrites each processor pattern on the file server's host here.
326
- */
327
- import type { EnvironmentParser } from '@geekmidas/envkit';
328
- import { processorServer } from '@geekmidas/constructs/processors';
329
- ${imports}
330
-
331
- export function setupProcessors(
332
- app: { all: (path: string, handler: (c: any) => unknown) => unknown },
333
- envParser: EnvironmentParser<any>,
334
- ): void {
335
- const units: Record<string, ReturnType<typeof processorServer>> = Object.fromEntries(
336
- Object.entries({
337
- ${units}
338
- }).map(([id, processors]) => [id, processorServer(processors, envParser)]),
339
- );
340
-
341
- app.all('${PROCESSORS_DEV_PREFIX}:server/*', async (c: any) => {
342
- const server = c.req.param('server') as string;
343
- const serve = units[server];
344
- if (!serve) return c.notFound();
345
- const path = c.req.path.slice(\`${PROCESSORS_DEV_PREFIX}\${server}\`.length) || '/';
346
- const response = await serve({ method: c.req.method, path });
347
- if (!response) {
348
- return new Response(null, {
349
- status: 404,
350
- headers: { 'cache-control': 'public, max-age=60' },
351
- });
352
- }
353
- return new Response(c.req.method === 'HEAD' ? null : response.body, {
354
- status: response.status,
355
- headers: response.headers,
356
- });
357
- });
358
- }
359
- `);
360
- return file;
361
- }
362
- /**
363
- * A file server's processor unit: one process answering each of its
364
- * processors' patterns, and `/health`. Returns its entry, `processors.ts`.
365
- *
366
- * Its own process because making a derivative is CPU-bound — a resize
367
- * spike in the API's process would be every request's latency.
368
- */
369
- async buildEntry(input) {
370
- const { context, outputDir, processors } = input;
371
- await mkdir(outputDir, { recursive: true });
372
- await writeTelemetryModule(outputDir, input.telemetry);
373
- const healthCheck = context.production?.healthCheck ?? "/health";
374
- const imports = processors.map(({ key, path }) => {
375
- const specifier = relative(outputDir, path.absolute).replace(/\.ts$/, ".js");
376
- return `import { ${key} } from '${specifier.startsWith(".") ? specifier : `./${specifier}`}';`;
377
- }).join("\n");
378
- const entry = join(outputDir, "processors.ts");
379
- await writeFile(entry, `#!/usr/bin/env node
380
- /**
381
- * Production entry for ${input.fileServerId}'s processors.
382
- * Generated by 'gkm build --production'.
383
- *
384
- * Answers each processor's pattern, and ${healthCheck} on PORT. The edge
385
- * routes only those patterns here; everything else on the file server's
386
- * domain is the bucket.
387
- */
388
- import { timingSafeEqual } from 'node:crypto';
389
- import { createServer } from 'node:http';
390
- import { runShutdownHooks } from '@geekmidas/constructs';
391
- import { processorServer } from '@geekmidas/constructs/processors';
392
- ${context.storageDrivers?.imports ?? ""}
393
- ${imports}
394
-
395
- ${startTelemetryCode([healthCheck])}
396
- ${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n` : ""}
397
- process.env.GKM_APP_NAME ??= ${JSON.stringify(processorUnitName(input.fileServerId))};
398
-
399
- const processors = [${processors.map(({ key }) => key).join(", ")}];
400
- const serve = processorServer(processors);
401
- const port = Number(process.env.PORT) || 3000;
402
- let stopping = false;
403
-
404
- ${input.telemetry ? REQUEST_SPANS : NO_REQUEST_SPANS}
405
- // Where the CDN fronts this unit, the secret it adds to every request: one
406
- // without it is refused here, whatever the edge in front did or could not.
407
- const originSecret = process.env.${PROCESSOR_ORIGIN_SECRET_ENV}
408
- ? Buffer.from(process.env.${PROCESSOR_ORIGIN_SECRET_ENV})
409
- : undefined;
410
- const fromOrigin = (header: string | string[] | undefined) => {
411
- if (!originSecret) return true;
412
- const given = Buffer.from(typeof header === 'string' ? header : '');
413
- return given.length === originSecret.length && timingSafeEqual(given, originSecret);
414
- };
415
-
416
- const server = createServer(async (req, res) => {
417
- const method = req.method ?? 'GET';
418
- const path = (req.url ?? '/').split('?')[0] ?? '/';
419
- if (path === ${JSON.stringify(healthCheck)}) {
420
- res.writeHead(stopping ? 503 : 200, { 'content-type': 'application/json' });
421
- res.end(JSON.stringify({ status: stopping ? 'stopping' : 'ok' }));
422
- return;
423
- }
424
- if (!fromOrigin(req.headers[${JSON.stringify(ORIGIN_VERIFY_HEADER.toLowerCase())}])) {
425
- res.writeHead(403, { 'cache-control': 'no-store' }).end();
426
- return;
427
- }
428
- await traced(method, path, async () => {
429
- try {
430
- const response = await serve({ method, path });
431
- if (!response) {
432
- res.writeHead(404, { 'cache-control': 'public, max-age=60' }).end();
433
- return 404;
434
- }
435
- res.writeHead(response.status, response.headers);
436
- res.end(method === 'HEAD' ? undefined : response.body);
437
- return response.status;
438
- } catch (error) {
439
- console.error(error);
440
- res.writeHead(500, { 'cache-control': 'no-store' }).end();
441
- return 500;
442
- }
443
- });
444
- });
445
- server.listen(port);
446
-
447
- const shutdown = async () => {
448
- if (stopping) return;
449
- stopping = true;
450
- setTimeout(() => process.exit(1), Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000).unref();
451
- server.close();
452
- await runShutdownHooks((error) => console.error(error));
453
- process.exit(0);
454
- };
455
- process.on('SIGTERM', shutdown);
456
- process.on('SIGINT', shutdown);
457
- `);
458
- return entry;
459
- }
460
- };
461
- /**
462
- * A SERVER span per request, once telemetry has started — opened by the unit
463
- * rather than by hooking node:http, which sees nothing inside a bundle. Named
464
- * after the processor's pattern, never the key, which has no bound.
465
- *
466
- * Only in an entry whose file server has a `Telemetry` node: the bundle
467
- * follows the import, and an app without one need not install the API.
468
- */
469
- const REQUEST_SPANS = `const tracing = requestSpans ? await import('@opentelemetry/api') : undefined;
470
- const routeOf = (path: string) =>
471
- processors.find((processor) => path.startsWith(processor.prefix))?.pattern;
472
-
473
- async function traced(
474
- method: string,
475
- path: string,
476
- run: () => Promise<number>,
477
- ): Promise<void> {
478
- if (!tracing) {
479
- await run();
480
- return;
481
- }
482
- const route = routeOf(path);
483
- await tracing.trace.getTracer('@geekmidas/processors').startActiveSpan(
484
- route ? \`\${method} \${route}\` : method,
485
- {
486
- kind: tracing.SpanKind.SERVER,
487
- attributes: {
488
- 'http.request.method': method,
489
- 'url.path': path,
490
- ...(route ? { 'http.route': route } : {}),
491
- },
492
- },
493
- async (span) => {
494
- try {
495
- const status = await run();
496
- span.setAttribute('http.response.status_code', status);
497
- if (status >= 500) span.setStatus({ code: tracing.SpanStatusCode.ERROR });
498
- } finally {
499
- span.end();
500
- }
501
- },
502
- );
503
- }
504
- `;
505
- /** The same shape without telemetry: each request just runs. */
506
- const NO_REQUEST_SPANS = `async function traced(
507
- _method: string,
508
- _path: string,
509
- run: () => Promise<number>,
510
- ): Promise<void> {
511
- await run();
512
- }
513
- `;
514
- /** What the manifest records of one processor. */
515
- async function processorInfo(name, processor, handler, context) {
516
- return {
517
- name,
518
- handler,
519
- fileServer: processor.surfaceId,
520
- path: processor.pattern,
521
- prefix: processor.prefix,
522
- ...processor.native.length ? { native: [...processor.native] } : {},
523
- ...processor.timeout !== void 0 ? { timeout: processor.timeout } : {},
524
- ...processor.memorySize !== void 0 ? { memorySize: processor.memorySize } : {},
525
- environment: await processor.getEnvironment({ markOptional: context.markOptional }),
526
- dependencies: processor.constructs
527
- };
528
- }
529
- //#endregion
530
- //#region src/generators/CronGenerator.ts
531
- var CronGenerator = class extends ConstructGenerator {
532
- async build(context, constructs, outputDir, options) {
533
- const target = options?.target ?? "aws";
534
- const logger = console;
535
- const cronInfos = [];
536
- if (target === "server") {
537
- await this.generateServerCronsFile(outputDir, constructs);
538
- logger.log(`Generated server crons file with ${constructs.length} crons`);
539
- return cronInfos;
540
- }
541
- if (constructs.length === 0) return cronInfos;
542
- const cronsDir = join(outputDir, "crons");
543
- await mkdir(cronsDir, { recursive: true });
544
- for (const { key, construct, path } of constructs) {
545
- const handlerFile = await this.generateCronHandler(cronsDir, path.relative, key, {
546
- ...context,
547
- storageDrivers: driversOf(context, construct)
548
- }, construct.owner);
549
- cronInfos.push({
550
- name: key,
551
- handler: relative(options?.root ?? process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
552
- schedule: construct.schedule || "rate(1 hour)",
553
- timeout: construct.timeout,
554
- memorySize: construct.memorySize,
555
- environment: await construct.getEnvironment({ markOptional: context.markOptional }),
556
- dependencies: construct.constructs
557
- });
558
- logger.log(`Generated cron handler: ${key}`);
559
- }
560
- return cronInfos;
561
- }
562
- isConstruct(value) {
563
- return Cron.isCron(value);
564
- }
565
- /**
566
- * The crons file a server entry imports.
567
- *
568
- * Shaped after `generateServerSubscribersFile`: one module, every cron, a
569
- * `setupCrons` the generated entry calls beside `setupSubscribers`.
570
- *
571
- * It picks its scheduler from what the process can reach. With a Postgres it
572
- * uses pg-boss, whose schedules live in the database — so a deployment
573
- * running four replicas fires each job once, which is the thing a timer in
574
- * every process gets wrong and does not report. With no database it falls
575
- * back to timers and says plainly that it is doing so.
576
- */
577
- async generateServerCronsFile(outputDir, crons) {
578
- await mkdir(outputDir, { recursive: true });
579
- const cronsPath = join(outputDir, "crons.ts");
580
- if (crons.length === 0) {
581
- await writeFile(cronsPath, `/**
582
- * Generated cron setup — this app declares none.
583
- */
584
- import type { EnvironmentParser } from '@geekmidas/envkit';
585
- import type { Logger } from '@geekmidas/logger';
586
-
587
- export async function setupCrons(
588
- _envParser: EnvironmentParser<any>,
589
- _logger: Logger,
590
- ): Promise<void> {}
591
-
592
- export function cronsStatus(): { failed: string[]; connections: unknown[] } {
593
- return { failed: [], connections: [] };
594
- }
595
-
596
- export async function stopCrons(): Promise<void> {}
597
- `);
598
- return cronsPath;
599
- }
600
- const importsByFile = /* @__PURE__ */ new Map();
601
- for (const { path, key } of crons) {
602
- const importPath = relative(dirname(cronsPath), path.relative).replace(/\.ts$/, ".js");
603
- if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
604
- importsByFile.get(importPath)?.push(key);
605
- }
606
- const content = `/**
607
- * Generated cron setup.
608
- *
609
- * Schedules every cron this app declares, in the process that serves it.
610
- *
611
- * The schedule lives in Postgres, through pg-boss, in the database the worker
612
- * named with \`.database(db)\`. That is what makes running several replicas
613
- * safe: each job fires once, where a timer in every process fires it once per
614
- * replica and reports nothing.
615
- *
616
- * No connection string appears here. The construct that owns the database is
617
- * the only thing that knows its key, and it is resolved through service
618
- * discovery like any other dependency.
619
- */
620
- import type { EnvironmentParser } from '@geekmidas/envkit';
621
- import type { Logger } from '@geekmidas/logger';
622
- import { runCron, scheduleInProcess, toCronExpression } from '@geekmidas/constructs/crons';
623
- import { ServiceDiscovery } from '@geekmidas/services';
624
- ${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
625
-
626
- const crons = [
627
- ${crons.map(({ key }) => ` { name: '${key}', cron: ${key} }`).join(",\n")}
628
- ];
629
-
630
- type Stoppable = { stop: () => Promise<void> | void };
631
- const running: Stoppable[] = [];
632
- // What a worker's health check reads: the crons that cannot be scheduled, and
633
- // the broker connection the schedule is kept through.
634
- const failed: string[] = [];
635
- const connections: import('@geekmidas/events').EventConnection[] = [];
636
-
637
- export async function setupCrons(
638
- envParser: EnvironmentParser<any>,
639
- logger: Logger,
640
- ): Promise<void> {
641
- if (crons.length === 0) {
642
- return;
643
- }
644
-
645
- const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
646
-
647
- // Resolved once per cron rather than per firing: registering services on
648
- // every tick would reconnect a database every minute.
649
- const prepared = [];
650
- for (const { name, cron } of crons) {
651
- try {
652
- const schedule = toCronExpression(cron.schedule);
653
- const services = cron.services.length > 0
654
- ? await serviceDiscovery.register(cron.services)
655
- : {};
656
-
657
- prepared.push({ name, cron, schedule, services });
658
- } catch (error) {
659
- // An unrepresentable schedule is a build-time mistake, and failing the
660
- // process for it would take the HTTP server down with it.
661
- logger.error({ err: error, cron: name }, 'Cron has no runnable schedule, skipping');
662
- failed.push(name);
663
- }
664
- }
665
-
666
- const run = async (entry: (typeof prepared)[number]) => {
667
- try {
668
- // The cron's own function, the way its Lambda would run it — services,
669
- // the worker's database as \`db\`, its events. It used to call a
670
- // \`handler\` a Cron does not have, so every firing logged a failure.
671
- await runCron(entry.cron, serviceDiscovery, entry.name);
672
- } catch (error) {
673
- logger.error({ err: error, cron: entry.name }, 'Cron failed');
674
- }
675
- };
676
-
677
- // The app's one pg-boss: the events broker's, as the broker's role, in the
678
- // broker's schema. A server fires its own crons, and a process scheduling in
679
- // memory fires each job once per replica — so the schedule lives in
680
- // Postgres. It used to be a second pg-boss on the worker's database, as the
681
- // runtime role, which can neither create a schema nor use the broker's.
682
- const { url, devPid } = envParser
683
- .create((get) => ({
684
- url: get('EVENT_PUBLISHER_CONNECTION_STRING').string().optional(),
685
- // Set by \`gkm dev\` on the server it starts, and by nothing deployed.
686
- devPid: get('GKM_DEV_PID').string().optional(),
687
- }))
688
- .parse();
689
-
690
- if (!url?.startsWith('pgboss://')) {
691
- // \`gkm dev\` on a target whose crons are infrastructure once deployed —
692
- // EventBridge rules on AWS — has no broker to keep a schedule in. It is one
693
- // process, so a timer fires each job once, which is all pg-boss is for
694
- // here. Only there: a deployed server firing by timer fires once per
695
- // replica, so outside dev this stays the error below.
696
- if (devPid) {
697
- for (const entry of prepared) {
698
- running.push(scheduleInProcess(entry.schedule, () => run(entry)));
699
- logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled in this process');
700
- }
701
- return;
702
- }
703
-
704
- logger.error(
705
- { crons: prepared.map(({ name }) => name) },
706
- 'These crons have nowhere to keep their schedule. On a server they are ' +
707
- 'scheduled through the pg-boss events broker ' +
708
- '(EVENT_PUBLISHER_CONNECTION_STRING), and ' +
709
- (url ? 'the broker configured is not pg-boss.' : 'none is configured.'),
710
- );
711
- failed.push(...prepared.map(({ name }) => name));
712
- return;
713
- }
714
-
715
- // Through the registered pg-boss driver, which the entry registers for a
716
- // server whose broker is pg-boss. Naming \`@geekmidas/events/pgboss\` here
717
- // made every bundle with a cron resolve pg-boss, whatever its broker.
718
- const { EventConnectionFactory } = await import('@geekmidas/events');
719
- const connection = (await EventConnectionFactory.fromConnectionString(
720
- url,
721
- )) as import('@geekmidas/events').EventConnection & { instance?: any };
722
- const boss = connection.instance!;
723
-
724
- // What this app declares now. Anything else under the prefix belonged to a
725
- // cron since renamed or deleted, and would keep firing at a handler that has
726
- // gone.
727
- //
728
- // The prefix is \`cron.\` rather than \`cron:\`: pg-boss accepts
729
- // alphanumerics, underscores, hyphens, periods and slashes in a queue name,
730
- // and rejects a colon outright.
731
- const declared = new Set(prepared.map(({ name }) => \`cron.\${name}\`));
732
- for (const existing of await boss.getSchedules()) {
733
- if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {
734
- await boss.unschedule(existing.name);
735
- logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');
736
- }
737
- }
738
-
739
- for (const entry of prepared) {
740
- const queue = \`cron.\${entry.name}\`;
741
- await boss.createQueue(queue);
742
- // UTC, so this agrees with the schedule a deploy target would have made.
743
- await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });
744
- await boss.work(queue, () => run(entry));
745
-
746
- logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');
747
- }
748
-
749
- running.push({ stop: () => connection.close() });
750
- connections.push(connection);
751
- logger.info({ count: prepared.length }, 'Crons scheduled');
752
- }
753
-
754
- /** The crons that cannot be scheduled, and the connection that schedules the rest. */
755
- export function cronsStatus(): {
756
- failed: string[];
757
- connections: import('@geekmidas/events').EventConnection[];
758
- } {
759
- return { failed: [...failed], connections: [...connections] };
760
- }
761
-
762
- /**
763
- * Stop scheduling, let a firing in flight finish, and close the broker
764
- * connection — pg-boss's graceful stop does all three. The caller bounds it.
765
- */
766
- export async function stopCrons(): Promise<void> {
767
- const open = [...running];
768
- running.length = 0;
769
- connections.length = 0;
770
- await Promise.all(open.map((r) => r.stop()));
771
- }
772
- `;
773
- await writeFile(cronsPath, content);
774
- return cronsPath;
775
- }
776
- async generateCronHandler(outputDir, sourceFile, exportName, context, owner) {
777
- const handlerFileName = `${exportName}.ts`;
778
- const handlerPath = join(outputDir, handlerFileName);
779
- const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
780
- const runtime = runtimeFor(context, dirname(handlerPath), owner);
781
- const content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';
782
- import { ${exportName} } from '${importPath}';
783
- ${runtime.imports}
784
- ${context.storageDrivers?.imports ?? ""}
785
- ${runtime.bindings}
786
- ${context.storageDrivers?.setup ? `\n// The handler registers the drivers its target needs.\n${context.storageDrivers.setup}\n` : ""}
787
- const adapter = new AWSScheduledFunction(envParser, ${exportName});
788
-
789
- export const handler = adapter.handler;
790
- `;
791
- await writeFile(handlerPath, content);
792
- return handlerPath;
793
- }
794
- };
795
- //#endregion
796
- //#region src/generators/QueueGenerator.ts
797
- /**
798
- * Generates the runtime for queue consumers (`worker.queue(…)`).
799
- *
800
- * - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that
801
- * polls each queue in-process, alongside the Hono server, through the queue's
802
- * own connection string — pg-boss by default, SQS on the AWS emulator.
803
- * - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed
804
- * by an SQS event-source mapping.
805
- */
806
- var QueueGenerator = class extends ConstructGenerator {
807
- isConstruct(value) {
808
- return Queue.isQueue(value);
809
- }
810
- async build(context, constructs, outputDir, options) {
811
- const target = options?.target ?? "aws";
812
- const logger = console;
813
- const queueInfos = [];
814
- if (target === "server") {
815
- await this.generateServerQueuesFile(outputDir, constructs);
816
- logger.log(`Generated server queues file with ${constructs.length} queues (polling mode)`);
817
- return queueInfos;
818
- }
819
- if (constructs.length === 0) return queueInfos;
820
- const queuesDir = join(outputDir, "queues");
821
- await mkdir(queuesDir, { recursive: true });
822
- for (const { key, construct, path } of constructs) {
823
- const handlerFile = await this.generateQueueHandler(queuesDir, path.relative, key, {
824
- ...context,
825
- storageDrivers: driversOf(context, construct)
826
- }, construct.owner);
827
- queueInfos.push({
828
- name: construct.name,
829
- handler: relative(options?.root ?? process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
830
- batchSize: construct.batchSize,
831
- fifo: construct.fifo,
832
- timeout: construct.timeout,
833
- environment: await construct.getEnvironment({ markOptional: context.markOptional }),
834
- dependencies: construct.constructs
835
- });
836
- logger.log(`Generated queue handler: ${key}`);
837
- }
838
- return queueInfos;
839
- }
840
- async generateQueueHandler(outputDir, sourceFile, exportName, context, owner) {
841
- const handlerPath = join(outputDir, `${exportName}.ts`);
842
- const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
843
- const runtime = runtimeFor(context, dirname(handlerPath), owner);
844
- const content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';
845
- import { ${exportName} } from '${importPath}';
846
- ${runtime.imports}
847
- ${context.storageDrivers?.imports ?? ""}
848
- ${runtime.bindings}
849
- ${context.storageDrivers?.setup ? `\n// The handler registers the drivers its target needs.\n${context.storageDrivers.setup}\n` : ""}
850
- const adapter = new AWSLambdaQueue(envParser, ${exportName});
851
-
852
- export const handler = adapter.handler;
853
- `;
854
- await writeFile(handlerPath, content);
855
- return handlerPath;
856
- }
857
- async generateServerQueuesFile(outputDir, queues) {
858
- await mkdir(outputDir, { recursive: true });
859
- const queuesPath = join(outputDir, "queues.ts");
860
- if (queues.length === 0) {
861
- await writeFile(queuesPath, `/**
862
- * Generated queues setup — this app declares none.
863
- */
864
- import type { EnvironmentParser } from '@geekmidas/envkit';
865
- import type { Logger } from '@geekmidas/logger';
866
-
867
- export async function setupQueues(
868
- _envParser: EnvironmentParser<any>,
869
- _logger: Logger,
870
- ): Promise<void> {}
871
-
872
- export function queuesStatus(): { failed: string[]; connections: unknown[] } {
873
- return { failed: [], connections: [] };
874
- }
875
-
876
- export async function stopQueues(): Promise<void> {}
877
- `);
878
- return queuesPath;
879
- }
880
- const importsByFile = /* @__PURE__ */ new Map();
881
- for (const { path, key } of queues) {
882
- const importPath = relative(dirname(queuesPath), path.relative).replace(/\.ts$/, ".js");
883
- if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
884
- importsByFile.get(importPath)?.push(key);
885
- }
886
- const content = `/**
887
- * Generated queue consumers setup.
888
- *
889
- * Each queue's one consumer polls its own queue, through the queue's own
890
- * connection string — the one its producers publish on. SQS cannot push, so
891
- * this is a poller on every transport: pg-boss locally by default, the SQS
892
- * queue on the AWS emulator.
893
- *
894
- * Deployed on Lambda, a queue's consumer is an SQS event source instead.
895
- */
896
- import type { EnvironmentParser } from '@geekmidas/envkit';
897
- import type { Logger } from '@geekmidas/logger';
898
- import { EventConnectionFactory, Subscriber } from '@geekmidas/events';
899
- import type { EventConnection } from '@geekmidas/events';
900
- import { ServiceDiscovery } from '@geekmidas/services';
901
- ${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
902
-
903
- const queues = [
904
- ${queues.map(({ key, construct }) => ` { queue: ${key}, connectionKey: '${providedKeyFor(construct.id, "queue", "publisherConnectionString")}' },`).join("\n")}
905
- ];
906
-
907
- // What was opened, and what could not be: a worker's health check reads both,
908
- // and its shutdown closes what was opened.
909
- const connections = new Map<string, EventConnection>();
910
- const failed: string[] = [];
911
-
912
- export async function setupQueues(
913
- envParser: EnvironmentParser<any>,
914
- logger: Logger,
915
- ): Promise<void> {
916
- const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
917
-
918
- for (const { queue, connectionKey } of queues) {
919
- const connectionString = process.env[connectionKey];
920
- if (!connectionString) {
921
- logger.error({ queue: queue.name, connectionKey }, 'No connection string for this queue');
922
- failed.push(queue.name);
923
- continue;
924
- }
925
-
926
- try {
927
- let connection = connections.get(connectionString);
928
- if (!connection) {
929
- connection = await EventConnectionFactory.fromConnectionString(connectionString);
930
- connections.set(connectionString, connection);
931
- }
932
- const eventSubscriber = await Subscriber.fromConnection(connection);
933
- const services = queue.services.length > 0
934
- ? await serviceDiscovery.register(queue.services)
935
- : {};
936
- // The queue's database — the worker's, or its own — handed over as \`db\`.
937
- const db = queue.databaseService
938
- ? (await serviceDiscovery.register([queue.databaseService]))[
939
- queue.databaseService.serviceName
940
- ]
941
- : undefined;
942
-
943
- // A queue's messages carry one type — its own name.
944
- await eventSubscriber.subscribe([queue.name], async (message) => {
945
- try {
946
- const validation = await queue.messageSchema['~standard'].validate(message.payload);
947
- if (validation.issues) {
948
- logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');
949
- return;
950
- }
951
-
952
- await queue.handler({
953
- messages: [validation.value],
954
- services: services,
955
- logger: queue.logger,
956
- db,
957
- } as any);
958
- } catch (error) {
959
- logger.error({ err: error, queue: queue.name }, 'Failed to process queue message');
960
- // Rethrown so the transport keeps the message for a retry.
961
- throw error;
962
- }
963
- });
964
- logger.info({ queue: queue.name }, 'Queue consumer started polling');
965
- } catch (error) {
966
- logger.error({ err: error, queue: queue.name }, 'Failed to set up queue consumer');
967
- failed.push(queue.name);
968
- }
969
- }
970
- }
971
-
972
- /** The consumers that could not start, and the connections that did. */
973
- export function queuesStatus(): { failed: string[]; connections: EventConnection[] } {
974
- return { failed: [...failed], connections: [...connections.values()] };
975
- }
976
-
977
- /**
978
- * Stop polling, let the messages in flight finish, and close each broker
979
- * connection — pg-boss's graceful stop does all three. The caller bounds it.
980
- */
981
- export async function stopQueues(): Promise<void> {
982
- const open = [...connections.values()];
983
- connections.clear();
984
- await Promise.all(open.map((connection) => connection.close()));
985
- }
986
- `;
987
- await writeFile(queuesPath, content);
988
- return queuesPath;
989
- }
990
- };
991
- //#endregion
992
- //#region src/generators/WorkerGenerator.ts
993
- /**
994
- * A worker whose topic subscribers would have to be pushed to over HTTP.
995
- *
996
- * On SNS a subscriber is an HTTP endpoint SNS delivers to, and a worker's
997
- * process serves nothing but its health check. A server target's broker is
998
- * pg-boss, where each subscriber polls a queue of its own, so this is only
999
- * reached by building server images for a project that deploys to AWS — where
1000
- * a subscriber is a Lambda instead.
1001
- */
1002
- var WorkerSubscribersNeedPush = class extends GkmError {
1003
- worker;
1004
- subscribers;
1005
- constructor(worker, subscribers) {
1006
- super(`The worker '${worker}' runs topic subscribers (${subscribers.join(", ")}), and this build's broker is SNS, which pushes each event to its subscriber over HTTP. A worker image serves only its health check. Deploy to a server target, whose broker is pg-boss and whose subscribers poll, or to AWS, where each subscriber is a Lambda.`);
1007
- this.worker = worker;
1008
- this.subscribers = subscribers;
1009
- this.name = "WorkerSubscribersNeedPush";
1010
- }
1011
- };
1012
- /** Where a worker's generated entry lives, under an app's `.gkm/server`. */
1013
- function workerEntryDir(serverDir, workerId) {
1014
- return join(serverDir, "workers", appKey(workerId));
1015
- }
1016
- /** The file a worker's bundle is written to, beside the server's. */
1017
- function workerBundleName(workerId) {
1018
- return `worker-${appKey(workerId)}.mjs`;
1019
- }
1020
- /**
1021
- * A Worker's production entry: the process that runs its crons, its queue
1022
- * consumers and its topic subscribers, and answers nothing but a health check.
1023
- *
1024
- * It is the server's runtime without the server. The `crons.ts`, `queues.ts`
1025
- * and `subscribers.ts` it starts are the files `gkm dev` starts — written by
1026
- * the same generators, given only this worker's constructs — so a consumer
1027
- * runs the same code in development and in the image. What it adds is the
1028
- * process around them: drivers, a health check that says when a consumer or
1029
- * the broker is down, and a shutdown that drains.
1030
- */
1031
- var WorkerGenerator = class {
1032
- generators;
1033
- constructor(generators = {
1034
- cron: new CronGenerator(),
1035
- queue: new QueueGenerator(),
1036
- subscriber: new SubscriberGenerator()
1037
- }) {
1038
- this.generators = generators;
1039
- }
1040
- /** Write the worker's files; returns its entry, `worker.ts`. */
1041
- async build(input) {
1042
- const { context, workerId, outputDir } = input;
1043
- if (input.subscribers.length > 0 && context.eventsBackends?.includes("sns")) throw new WorkerSubscribersNeedPush(workerId, input.subscribers.map(({ key }) => key));
1044
- await mkdir(outputDir, { recursive: true });
1045
- const options = { target: "server" };
1046
- await Promise.all([
1047
- this.generators.cron.build(context, input.crons, outputDir, options),
1048
- this.generators.queue.build(context, input.queues, outputDir, options),
1049
- this.generators.subscriber.build(context, input.subscribers, outputDir, options)
1050
- ]);
1051
- await writeFile(join(outputDir, "app.ts"), workerApp(context, workerId, outputDir));
1052
- await writeTelemetryModule(outputDir, input.telemetry);
1053
- const entry = join(outputDir, "worker.ts");
1054
- await writeFile(entry, workerEntry(context.production?.healthCheck ?? "/health"));
1055
- return entry;
1056
- }
1057
- };
1058
- /**
1059
- * `app.ts`: the worker's runtime — its logger and environment parser off the
1060
- * Worker construct, the drivers its target needs, and a `startWorker` that
1061
- * starts every cron, consumer and subscriber it owns.
1062
- */
1063
- function workerApp(context, workerId, outputDir) {
1064
- const runtime = runtimeFor(context, outputDir, workerId);
1065
- return `/**
1066
- * Generated worker runtime for ${workerId}.
1067
- * Generated by 'gkm build --production'.
1068
- */
1069
- import { setupCrons, cronsStatus, stopCrons } from './crons.js';
1070
- import { setupQueues, queuesStatus, stopQueues } from './queues.js';
1071
- import { setupSubscribers, subscribersStatus, stopSubscribers } from './subscribers.js';
1072
- ${runtime.imports}
1073
- ${context.storageDrivers?.imports ?? ""}
1074
-
1075
- ${runtime.bindings}
1076
-
1077
- ${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.
1078
- ${context.storageDrivers.setup}
1079
- ` : ""}
1080
- // Who this worker is to Postgres: application_name on every connection.
1081
- process.env.GKM_APP_NAME ??= ${JSON.stringify(workerId)};
1082
-
1083
- export { logger };
1084
-
1085
- /** What the health check answers, and why. */
1086
- export interface WorkerHealth {
1087
- healthy: boolean;
1088
- /** The crons, queues and subscribers that could not start. */
1089
- failed: string[];
1090
- /** How many broker connections did not answer. */
1091
- down: number;
1092
- }
1093
-
1094
- /** Whether one broker connection answers: open, and — on pg-boss — a query. */
1095
- async function answers(connection: unknown): Promise<boolean> {
1096
- const c = connection as {
1097
- isConnected?: () => boolean;
1098
- instance?: { getDb?: () => { executeSql: (sql: string) => Promise<unknown> } };
1099
- };
1100
- if (c.isConnected && !c.isConnected()) return false;
1101
- const db = c.instance?.getDb?.();
1102
- if (!db) return true;
1103
- try {
1104
- await Promise.race([
1105
- db.executeSql('select 1'),
1106
- new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 2000).unref()),
1107
- ]);
1108
- return true;
1109
- } catch {
1110
- return false;
1111
- }
1112
- }
1113
-
1114
- /** A request to a route this worker mounted, and what it answered. */
1115
- export interface WorkerRequest {
1116
- headers: Record<string, string | string[] | undefined>;
1117
- body: string;
1118
- /** The request's query — Mailpit's webhook carries its token there. */
1119
- query?: URLSearchParams;
1120
- }
1121
- export interface WorkerAnswer {
1122
- status: number;
1123
- body: unknown;
1124
- }
1125
-
1126
- // The routes something pushes to: an SNS subscriber's, and the one a local
1127
- // object store posts a bucket's events to. Mounted by the subscribers, served
1128
- // by the entry's HTTP server beside the health check.
1129
- const routes = new Map<string, (c: any) => unknown>();
1130
- const app = {
1131
- post: (path: string, handler: (c: any) => unknown) => {
1132
- routes.set(path, handler);
1133
- },
1134
- };
1135
-
1136
- /** Run one mounted route, as the subscribers' handlers expect to be called. */
1137
- async function route(path: string, request: WorkerRequest): Promise<WorkerAnswer | undefined> {
1138
- const handler = routes.get(path);
1139
- if (!handler) return undefined;
1140
- let answer: WorkerAnswer | undefined;
1141
- const c = {
1142
- req: {
1143
- text: async () => request.body,
1144
- query: (name: string) => request.query?.get(name) ?? undefined,
1145
- header: (name: string) => {
1146
- const value = request.headers[name.toLowerCase()];
1147
- return Array.isArray(value) ? value[0] : value;
1148
- },
1149
- },
1150
- json: (body: unknown, status = 200) => {
1151
- answer = { status, body };
1152
- return answer;
1153
- },
1154
- };
1155
- await handler(c);
1156
- return answer ?? { status: 204, body: null };
1157
- }
1158
-
1159
- /** Start everything this worker runs. */
1160
- export async function startWorker(): Promise<{
1161
- health: () => Promise<WorkerHealth>;
1162
- stop: () => Promise<void>;
1163
- route: typeof route;
1164
- /** Subscribe the pushed routes, once the server answers on \`port\`. */
1165
- subscribeForPush: (port: number) => Promise<void>;
1166
- }> {
1167
- const subscribeForPush = await setupSubscribers(app, envParser, logger).catch((error) => {
1168
- logger.error({ err: error }, 'Failed to start subscribers');
1169
- return async (_port: number) => {};
1170
- });
1171
- await setupQueues(envParser, logger).catch((error) => {
1172
- logger.error({ err: error }, 'Failed to start queue consumers');
1173
- });
1174
- await setupCrons(envParser, logger).catch((error) => {
1175
- logger.error({ err: error }, 'Failed to schedule crons');
1176
- });
1177
-
1178
- const statuses = () => [subscribersStatus(), queuesStatus(), cronsStatus()];
1179
-
1180
- return {
1181
- route,
1182
- subscribeForPush,
1183
- async health() {
1184
- const all = statuses();
1185
- const failed = all.flatMap((s) => s.failed);
1186
- const alive = await Promise.all(
1187
- all.flatMap((s) => s.connections as unknown[]).map(answers),
1188
- );
1189
- const down = alive.filter((ok) => !ok).length;
1190
- return { healthy: failed.length === 0 && down === 0, failed, down };
1191
- },
1192
- // Each stops pulling, waits for what it has in flight, and closes its
1193
- // broker connection. Together, so one slow handler does not hold the
1194
- // others' connections open.
1195
- async stop() {
1196
- await Promise.all([stopSubscribers(), stopQueues(), stopCrons()]);
1197
- },
1198
- };
1199
- }
1200
- `;
1201
- }
1202
- /**
1203
- * `worker.ts`: the process. Health first, so the container answers while the
1204
- * consumers connect; then the worker; then a shutdown that drains.
1205
- */
1206
- function workerEntry(healthCheck) {
1207
- return `#!/usr/bin/env node
1208
- /**
1209
- * Production worker entry point.
1210
- * Generated by 'gkm build --production'.
1211
- *
1212
- * Runs this worker's crons, queue consumers and topic subscribers, and serves
1213
- * its health check: ${healthCheck}, on PORT — 200 when every consumer started
1214
- * and every broker connection answers, 503 otherwise. Beside it, on the same
1215
- * port, the POST routes its subscribers mounted: where a local object store
1216
- * posts a bucket's events.
1217
- *
1218
- * On SIGTERM it stops pulling messages and scheduling crons, lets the handlers
1219
- * in flight finish, closes its broker connections and database pools, and
1220
- * exits 0 — or 1, at GKM_SHUTDOWN_TIMEOUT_MS (8s by default, under Docker's
1221
- * 10s stop timeout).
1222
- */
1223
- import { createServer } from 'node:http';
1224
- import { runShutdownHooks } from '@geekmidas/constructs';
1225
-
1226
- ${startTelemetryCode([healthCheck])}
1227
- const { startWorker, logger } = await import('./app.js');
1228
-
1229
- const port = Number(process.env.PORT) || 3000;
1230
-
1231
- let worker: Awaited<ReturnType<typeof startWorker>> | undefined;
1232
- let stopping = false;
1233
-
1234
- const server = createServer((req, res) => {
1235
- // Parsed once: the path routes, the query goes to the route.
1236
- const url = new URL(req.url ?? '/', 'http://localhost');
1237
- const path = url.pathname;
1238
- const answer = (status: number, body: unknown) => {
1239
- res.writeHead(status, { 'content-type': 'application/json' });
1240
- res.end(JSON.stringify(body));
1241
- };
1242
-
1243
- // A route a subscriber mounted: what SNS pushes to, or what a local object
1244
- // store posts a bucket's events to. Refused while starting or stopping, so
1245
- // the sender keeps the message and sends it again.
1246
- if (req.method === 'POST') {
1247
- let body = '';
1248
- req.setEncoding('utf8');
1249
- req.on('data', (chunk) => {
1250
- body += chunk;
1251
- });
1252
- req.on('end', () => {
1253
- if (stopping) return answer(503, { status: 'stopping' });
1254
- if (!worker) return answer(503, { status: 'starting' });
1255
- worker.route(path, { headers: req.headers, body, query: url.searchParams }).then(
1256
- (routed) => (routed ? answer(routed.status, routed.body) : answer(404, { status: 'not found' })),
1257
- (error) => {
1258
- logger.error({ err: error, path }, 'Route failed');
1259
- answer(500, { status: 'failed' });
1260
- },
1261
- );
1262
- });
1263
- return;
1264
- }
1265
-
1266
- if (path !== ${JSON.stringify(healthCheck)} || (req.method !== 'GET' && req.method !== 'HEAD')) {
1267
- res.writeHead(404).end();
1268
- return;
1269
- }
1270
- if (stopping) return answer(503, { status: 'stopping' });
1271
- if (!worker) return answer(503, { status: 'starting' });
1272
- worker.health().then(
1273
- (health) => answer(health.healthy ? 200 : 503, { status: health.healthy ? 'ok' : 'unhealthy', ...health }),
1274
- (error) => answer(503, { status: 'unhealthy', error: String(error) }),
1275
- );
1276
- });
1277
- server.listen(port);
1278
-
1279
- const shutdown = async () => {
1280
- if (stopping) return;
1281
- stopping = true;
1282
- const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;
1283
- logger.info({ deadline }, 'Graceful shutdown initiated');
1284
- setTimeout(() => {
1285
- logger.warn({ deadline }, 'Shutdown deadline reached, exiting');
1286
- process.exit(1);
1287
- }, deadline).unref();
1288
-
1289
- // Nothing new is pulled or scheduled; what is in flight finishes.
1290
- await worker?.stop().catch((error) => logger.error({ err: error }, 'Failed to stop the worker'));
1291
- // Then what the handlers used: database pools.
1292
- await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));
1293
- server.close();
1294
- logger.info('Worker stopped');
1295
- process.exit(0);
1296
- };
1297
-
1298
- process.on('SIGTERM', shutdown);
1299
- process.on('SIGINT', shutdown);
1300
-
1301
- worker = await startWorker();
1302
- logger.info({ port }, 'Worker started');
1303
- await worker.subscribeForPush(port).catch((error) => {
1304
- logger.error({ err: error }, 'Failed to subscribe for push');
1305
- });
1306
- `;
1307
- }
1308
- //#endregion
1309
- //#region src/docker/index.ts
1310
- const logger = output;
1311
- /** `docker build` failed; what docker printed above says why. */
1312
- var DockerBuildFailed = class extends Error {
1313
- imageRef;
1314
- constructor(imageRef, cause) {
1315
- super(`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
1316
- this.imageRef = imageRef;
1317
- this.name = "DockerBuildFailed";
1318
- }
1319
- };
1320
- /** `docker push` failed — usually the registry login or its permissions. */
1321
- var DockerPushFailed = class extends Error {
1322
- imageRef;
1323
- constructor(imageRef, cause) {
1324
- super(`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
1325
- this.imageRef = imageRef;
1326
- this.name = "DockerPushFailed";
1327
- }
1328
- };
1329
- /** `gkm docker --push` was asked for with nowhere to push to. */
1330
- var PushNeedsRegistry = class extends GkmError {
1331
- imageName;
1332
- constructor(imageName) {
1333
- super(`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`);
1334
- this.imageName = imageName;
1335
- this.name = "PushNeedsRegistry";
1336
- }
1337
- };
1338
- /**
1339
- * Docker command implementation: one Dockerfile per deployable app, each
1340
- * building its image inside Docker from a turbo-pruned slice of the build
1341
- * root — nothing is built on the host — plus the build root's
1342
- * `.dockerignore` and `docker-compose.constructs.yml`.
1343
- */
1344
- async function dockerCommand(options) {
1345
- const cwd = options.cwd ?? process.cwd();
1346
- const loaded = await loadWorkspaceConfig(cwd);
1347
- const names = loaded.type === "single" ? Object.fromEntries(Object.keys(loaded.workspace.apps).map((name) => [name, resolveDockerConfig(loaded.raw).imageName])) : {};
1348
- const result = await workspaceDockerCommand(loaded.workspace, loaded.manifest, names, loaded.background, options.stage);
1349
- if (options.build) for (const app of result.apps) await buildDockerImage(app, result.buildRoot, options);
1350
- if (options.push) for (const app of result.apps) await pushDockerImage(app.imageName, options, result.buildRoot);
1351
- return result;
1352
- }
1353
- /**
1354
- * Build one app's image, from the build root.
1355
- * Uses BuildKit for cache mount support
1356
- */
1357
- async function buildDockerImage(app, buildRoot, options) {
1358
- const tag = options.tag ?? "latest";
1359
- const registry = options.registry;
1360
- const fullImageName = validateImageRef(registry ? `${registry}/${app.imageName}:${tag}` : `${app.imageName}:${tag}`);
1361
- logger.log(`\n🐳 Building Docker image: ${fullImageName}`);
1362
- try {
1363
- await run("docker", [
1364
- "build",
1365
- `--file=${relative(buildRoot, app.dockerfile)}`,
1366
- `--tag=${fullImageName}`,
1367
- "."
1368
- ], {
1369
- cwd: buildRoot,
1370
- env: {
1371
- ...process.env,
1372
- DOCKER_BUILDKIT: "1"
1373
- }
1374
- });
1375
- logger.log(`✅ Docker image built: ${fullImageName}`);
1376
- } catch (error) {
1377
- throw new DockerBuildFailed(fullImageName, error);
1378
- }
1379
- }
1380
- /**
1381
- * Push Docker image to registry
1382
- */
1383
- async function pushDockerImage(imageName, options, cwd) {
1384
- const tag = options.tag ?? "latest";
1385
- const registry = options.registry;
1386
- if (!registry) throw new PushNeedsRegistry(imageName);
1387
- const fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);
1388
- logger.log(`\n🚀 Pushing Docker image: ${fullImageName}`);
1389
- try {
1390
- await run("docker", ["push", fullImageName], { cwd });
1391
- logger.log(`✅ Docker image pushed: ${fullImageName}`);
1392
- } catch (error) {
1393
- throw new DockerPushFailed(fullImageName, error);
1394
- }
1395
- }
1396
- /**
1397
- * Generate Dockerfiles for all apps in a workspace.
1398
- * @internal Exported for testing
1399
- */
1400
- async function workspaceDockerCommand(workspace, manifest, imageNames = {}, background = {}, stage) {
1401
- const results = [];
1402
- const layout = imageLayout(workspace);
1403
- logger.log(`\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);
1404
- logger.log(` Build root: ${layout.buildRoot}`);
1405
- logger.log(` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ""}, turbo@${layout.tools.turboVersion}`);
1406
- for (const [appName, app] of Object.entries(workspace.apps)) {
1407
- if (app.type === "mobile") {
1408
- logger.log(`\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`);
1409
- continue;
1410
- }
1411
- const buildType = app.entry ? "entry" : app.type;
1412
- logger.log(`\n 📄 Generating Dockerfile for ${appName} (${buildType})`);
1413
- const dockerfile = appDockerfile(appName, app, {
1414
- layout,
1415
- workspaceRoot: workspace.root,
1416
- apps: workspace.apps,
1417
- ...manifest ? { manifest } : {},
1418
- workspace,
1419
- ...stage ? { stage } : {}
1420
- });
1421
- const path = dockerfileOf(appName, app.path);
1422
- const dockerfilePath = join(workspace.root, path);
1423
- await mkdir(dirname(dockerfilePath), { recursive: true });
1424
- await writeFile(dockerfilePath, dockerfile);
1425
- logger.log(` Generated: ${path}`);
1426
- results.push({
1427
- appName,
1428
- type: app.type,
1429
- dockerfile: dockerfilePath,
1430
- imageName: imageNames[appName] ?? appName
1431
- });
1432
- }
1433
- for (const worker of manifest ? workerUnits(workspace, manifest, background) : []) {
1434
- logger.log(`\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`);
1435
- const dockerfile = workerDockerfile(worker, workspace.apps[worker.app], {
1436
- layout,
1437
- workspaceRoot: workspace.root,
1438
- ...manifest ? { manifest } : {}
1439
- });
1440
- const path = workerDockerfileOf(worker.name);
1441
- const dockerfilePath = join(workspace.root, path);
1442
- await mkdir(dirname(dockerfilePath), { recursive: true });
1443
- await writeFile(dockerfilePath, dockerfile);
1444
- logger.log(` Generated: ${path}`);
1445
- results.push({
1446
- appName: worker.name,
1447
- type: "backend",
1448
- dockerfile: dockerfilePath,
1449
- imageName: imageNames[worker.name] ?? worker.name
1450
- });
1451
- }
1452
- for (const unit of manifest ? processorUnits(workspace, manifest) : []) {
1453
- logger.log(`\n 📄 Generating Dockerfile for ${unit.name} (processors of ${unit.id}, built from ${unit.app})`);
1454
- const dockerfile = processorDockerfile(unit, workspace.apps[unit.app], {
1455
- layout,
1456
- workspaceRoot: workspace.root,
1457
- ...manifest ? { manifest } : {}
1458
- });
1459
- const path = workerDockerfileOf(unit.name);
1460
- const dockerfilePath = join(workspace.root, path);
1461
- await mkdir(dirname(dockerfilePath), { recursive: true });
1462
- await writeFile(dockerfilePath, dockerfile);
1463
- logger.log(` Generated: ${path}`);
1464
- results.push({
1465
- appName: unit.name,
1466
- type: "backend",
1467
- dockerfile: dockerfilePath,
1468
- imageName: imageNames[unit.name] ?? unit.name
1469
- });
1470
- }
1471
- const dockerignorePath = await ensureDockerignore(layout.buildRoot);
1472
- logger.log(`\n Ensured: ${dockerignorePath}`);
1473
- const composePath = await writeConstructsCompose(workspace);
1474
- logger.log(`\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`);
1475
- logger.log(`\n📋 Build commands (from ${layout.buildRoot}):`);
1476
- for (const result of results) {
1477
- const icon = result.type === "backend" ? "⚙️" : result.type === "mobile" ? "📱" : "🌐";
1478
- logger.log(` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`);
1479
- }
1480
- printRunInstructions(workspace);
1481
- return {
1482
- apps: results,
1483
- dockerCompose: composePath,
1484
- dockerignore: dockerignorePath,
1485
- buildRoot: layout.buildRoot
1486
- };
1487
- }
1488
- /**
1489
- * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,
1490
- * a backend with its own entry bundled by esbuild, or a site by its
1491
- * framework. The one choice every builder of images makes.
1492
- */
1493
- function appDockerfile(appName, app, options) {
1494
- const image = appImageOptions(options.layout, appName, app, options.workspaceRoot, options.apps, app.type === "web" && options.manifest && options.workspace ? siteClientTelemetry(options.manifest, appName, options.workspace, options.stage) : void 0);
1495
- if (app.type === "web") return siteDockerfile(appName, app, {
1496
- image,
1497
- ...options.manifest ? { manifest: options.manifest } : {},
1498
- ...options.publicUrlArgs ? { publicUrlArgs: options.publicUrlArgs } : {}
1499
- });
1500
- if (app.entry) return generateEntryDockerfile({
1501
- ...image,
1502
- entry: app.entry,
1503
- healthCheckPath: "/health"
1504
- });
1505
- return generateBackendDockerfile({
1506
- ...image,
1507
- ...sharedDirectory(options, appName, app),
1508
- healthCheckPath: "/health",
1509
- ...options.cache ? { cache: options.cache } : {}
1510
- });
1511
- }
1512
- /**
1513
- * For a gkm backend whose directory holds another surface: the app its image's
1514
- * build is for, which is also the tree under `.gkm/server` it writes — see
1515
- * `sharedDirectoryTree`. Nothing for an app alone in its directory.
1516
- */
1517
- function sharedDirectory(options, appName, app) {
1518
- if (!options.manifest) return {};
1519
- const tree = sharedDirectoryTree(options.manifest, options.workspaceRoot, resolve(options.workspaceRoot, app.path), appName);
1520
- return tree ? { sharedDirectoryApp: tree } : {};
1521
- }
1522
- /** Where `gkm docker` writes a worker's Dockerfile. */
1523
- function workerDockerfileOf(worker) {
1524
- return `.gkm/docker/Dockerfile.${worker}`;
1525
- }
1526
- /**
1527
- * A Worker's Dockerfile: its host app's build, and the worker's bundle as the
1528
- * runner — see `generateWorkerDockerfile`.
1529
- */
1530
- function workerDockerfile(worker, host, options) {
1531
- const image = {
1532
- ...appImageOptions(options.layout, worker.app, host, options.workspaceRoot),
1533
- ...sharedDirectory(options, worker.app, host)
1534
- };
1535
- return generateWorkerDockerfile({
1536
- ...image,
1537
- imageName: worker.name,
1538
- port: WORKER_PORT,
1539
- worker: worker.id,
1540
- bundle: workerBundleName(worker.id),
1541
- healthCheckPath: "/health",
1542
- ...options.cache ? { cache: options.cache } : {}
1543
- });
1544
- }
1545
- /**
1546
- * A file server's processor unit's Dockerfile: its host app's build, and the
1547
- * unit's bundle as the runner, with its processors' native packages
1548
- * installed beside it — see `generateProcessorDockerfile`.
1549
- */
1550
- function processorDockerfile(unit, host, options) {
1551
- const image = {
1552
- ...appImageOptions(options.layout, unit.app, host, options.workspaceRoot),
1553
- ...sharedDirectory(options, unit.app, host)
1554
- };
1555
- return generateProcessorDockerfile({
1556
- ...image,
1557
- imageName: unit.name,
1558
- port: PROCESSOR_PORT,
1559
- fileServer: unit.id,
1560
- bundle: processorBundleName(unit.id),
1561
- healthCheckPath: "/health",
1562
- ...options.cache ? { cache: options.cache } : {}
1563
- });
1564
- }
1565
- /**
1566
- * A site's Dockerfile, with an `ARG` for every key its bundler inlines.
1567
- *
1568
- * The keys come from the site's declaration where there is one — every
1569
- * public key its edges give it, `VITE_UPLOADS_URL` included — and an
1570
- * `ARG` the Dockerfile does not declare is a build argument the build drops,
1571
- * leaving the bundle with an empty URL.
1572
- */
1573
- function siteDockerfile(appName, app, options) {
1574
- const declared = options.manifest ? Object.entries(options.manifest).find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1] : void 0;
1575
- const publicUrlArgs = options.publicUrlArgs ?? (declared?.kind === "site" && options.manifest ? [
1576
- providedKeyFor(declared.id, declared.kind, "url"),
1577
- ...Object.keys(publicEnvFor(declared, options.manifest)),
1578
- ...[imageOriginsFor(declared, options.manifest)?.key].filter((key) => key !== void 0)
1579
- ] : getPublicUrlArgNames(app));
1580
- const webOpts = {
1581
- ...options.image,
1582
- publicUrlArgs,
1583
- ...declared?.kind === "site" && declared.prerender === "stage" ? { prerender: true } : {}
1584
- };
1585
- switch (app.framework) {
1586
- case "vite": return generateViteStaticDockerfile(webOpts);
1587
- case "tanstack-start":
1588
- case "remix": return generateNodeWebDockerfile(webOpts);
1589
- default: return generateNextjsDockerfile(webOpts);
1590
- }
1591
- }
1592
- /**
1593
- * What a build root's `.dockerignore` must leave out of every image's
1594
- * context: dependencies installed for another platform, anything built on the
1595
- * host (every image builds from source), git, and gkm's own output —
1596
- * `.gkm/compose`'s env files hold a stage's secrets.
1597
- */
1598
- const REQUIRED_IGNORES = [
1599
- "**/node_modules",
1600
- ".git",
1601
- "**/dist",
1602
- "**/.next",
1603
- "**/.turbo",
1604
- "**/.gkm",
1605
- "**/.gkm/compose"
1606
- ];
1607
- /**
1608
- * Make sure the build root's `.dockerignore` leaves out what no image may
1609
- * hold: written whole where there is none, and each missing line appended to
1610
- * one the project keeps.
1611
- */
1612
- async function ensureDockerignore(buildRoot) {
1613
- const path = join(buildRoot, ".dockerignore");
1614
- if (!existsSync(path)) {
1615
- await writeFile(path, generateDockerignore());
1616
- return path;
1617
- }
1618
- const current = await readFile(path, "utf-8");
1619
- const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
1620
- const missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));
1621
- if (missing.length === 0) return path;
1622
- await appendFile(path, `${current.endsWith("\n") || current === "" ? "" : "\n"}\n# gkm: images build from source, and a stack's env files hold its secrets\n${missing.join("\n")}\n`);
1623
- return path;
1624
- }
1625
- /**
1626
- * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with
1627
- * the apps beside the containers their constructs derive.
1628
- *
1629
- * Through reconcile rather than a second generator, so what `gkm docker`
1630
- * describes and what `gkm dev` runs cannot disagree. Nothing is started.
1631
- */
1632
- async function writeConstructsCompose(workspace) {
1633
- await reconcileWorkspace(workspace, {
1634
- stage: workspace.stages.local,
1635
- start: false
1636
- });
1637
- logger.log(` Generated: ${COMPOSE_PATH} (project root)`);
1638
- return join(workspace.root, COMPOSE_PATH);
1639
- }
1640
- function printRunInstructions(workspace) {
1641
- const project = existsSync(join(workspace.root, "docker-compose.yml")) ? " -f docker-compose.yml" : "";
1642
- logger.log("\n📋 Run everything (the apps sit behind the \"apps\" profile):");
1643
- logger.log(" gkm setup # starts the containers and creates what they hold");
1644
- logger.log(` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`);
1645
- }
1646
- //#endregion
1647
- export { servedBy as C, reachedBy as S, validateImageRef as T, processorInfo as _, ensureDockerignore as a, handlerDriversFor as b, workerDockerfileOf as c, workerEntryDir as d, QueueGenerator as f, processorEntryDir as g, processorBundleName as h, dockerCommand as i, WorkerGenerator as l, ProcessorGenerator as m, DockerPushFailed as n, processorDockerfile as o, CronGenerator as p, appDockerfile as r, workerDockerfile as s, DockerBuildFailed as t, workerBundleName as u, appOutputDir as v, surfaceAt as w, ownersContext as x, sharedDirectoryTree as y };
1648
-
1649
- //# sourceMappingURL=docker-DDiEfZox.mjs.map