@geekmidas/cli 10.0.0-alpha.17 → 10.0.0-alpha.170

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 (452) hide show
  1. package/README.md +323 -380
  2. package/bin/adjacent-tsconfig.mjs +46 -8
  3. package/bin/gkm.mjs +11 -3
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/EndpointGenerator-C1h_wExz.cjs +1098 -0
  7. package/dist/EndpointGenerator-C1h_wExz.cjs.map +1 -0
  8. package/dist/EndpointGenerator-CSKhAD6W.mjs +1039 -0
  9. package/dist/EndpointGenerator-CSKhAD6W.mjs.map +1 -0
  10. package/dist/GoDaddyProvider-Cf4MIuaD.mjs +412 -0
  11. package/dist/GoDaddyProvider-Cf4MIuaD.mjs.map +1 -0
  12. package/dist/GoDaddyProvider-DK9_Jw9d.cjs +412 -0
  13. package/dist/GoDaddyProvider-DK9_Jw9d.cjs.map +1 -0
  14. package/dist/{HostingerProvider-BY26bWwB.mjs → HostingerProvider-CQebZrz3.mjs} +23 -9
  15. package/dist/HostingerProvider-CQebZrz3.mjs.map +1 -0
  16. package/dist/{HostingerProvider-BZFGYYVA.cjs → HostingerProvider-qQzo4MYp.cjs} +23 -9
  17. package/dist/HostingerProvider-qQzo4MYp.cjs.map +1 -0
  18. package/dist/LegacyStateStore-BeMRGXRi.cjs +124 -0
  19. package/dist/LegacyStateStore-BeMRGXRi.cjs.map +1 -0
  20. package/dist/LegacyStateStore-DXPHKdMk.mjs +124 -0
  21. package/dist/LegacyStateStore-DXPHKdMk.mjs.map +1 -0
  22. package/dist/LocalStateStore-BYQ9lPje.mjs +167 -0
  23. package/dist/LocalStateStore-BYQ9lPje.mjs.map +1 -0
  24. package/dist/LocalStateStore-E_sa5GR2.cjs +178 -0
  25. package/dist/LocalStateStore-E_sa5GR2.cjs.map +1 -0
  26. package/dist/OpenApiTsGenerator-5xPn-p65.mjs +534 -0
  27. package/dist/OpenApiTsGenerator-5xPn-p65.mjs.map +1 -0
  28. package/dist/OpenApiTsGenerator-CzrLGzC0.cjs +539 -0
  29. package/dist/OpenApiTsGenerator-CzrLGzC0.cjs.map +1 -0
  30. package/dist/{Route53Provider-Cvj40A8I.mjs → Route53Provider-Di_SD9CF.mjs} +3 -3
  31. package/dist/Route53Provider-Di_SD9CF.mjs.map +1 -0
  32. package/dist/{Route53Provider-DVILBsvV.cjs → Route53Provider-emLuQHVw.cjs} +3 -3
  33. package/dist/Route53Provider-emLuQHVw.cjs.map +1 -0
  34. package/dist/S3StateStore-BQaGVNRf.mjs +223 -0
  35. package/dist/S3StateStore-BQaGVNRf.mjs.map +1 -0
  36. package/dist/S3StateStore-Cjr4Rtsf.cjs +222 -0
  37. package/dist/S3StateStore-Cjr4Rtsf.cjs.map +1 -0
  38. package/dist/SSMStateStore-Bq_S7x5_.mjs +205 -0
  39. package/dist/SSMStateStore-Bq_S7x5_.mjs.map +1 -0
  40. package/dist/SSMStateStore-Cnfwdlme.cjs +204 -0
  41. package/dist/SSMStateStore-Cnfwdlme.cjs.map +1 -0
  42. package/dist/SubscriberGenerator-CfZWX0lT.mjs +783 -0
  43. package/dist/SubscriberGenerator-CfZWX0lT.mjs.map +1 -0
  44. package/dist/SubscriberGenerator-DMi4siph.cjs +848 -0
  45. package/dist/SubscriberGenerator-DMi4siph.cjs.map +1 -0
  46. package/dist/add-3_IHpF5F.cjs +713 -0
  47. package/dist/add-3_IHpF5F.cjs.map +1 -0
  48. package/dist/add-CNQFnG0C.mjs +711 -0
  49. package/dist/add-CNQFnG0C.mjs.map +1 -0
  50. package/dist/appPorts-BoXMwolc.mjs +249 -0
  51. package/dist/appPorts-BoXMwolc.mjs.map +1 -0
  52. package/dist/appPorts-IW-OZmRi.cjs +296 -0
  53. package/dist/appPorts-IW-OZmRi.cjs.map +1 -0
  54. package/dist/apps-BGu47YRF.cjs +6404 -0
  55. package/dist/apps-BGu47YRF.cjs.map +1 -0
  56. package/dist/apps-DGod3aS9.mjs +5765 -0
  57. package/dist/apps-DGod3aS9.mjs.map +1 -0
  58. package/dist/aws-C5LAU_Ii.mjs +97 -0
  59. package/dist/aws-C5LAU_Ii.mjs.map +1 -0
  60. package/dist/aws-DKC2m3sT.cjs +108 -0
  61. package/dist/aws-DKC2m3sT.cjs.map +1 -0
  62. package/dist/awsStore-Bx5nCFnS.mjs +121 -0
  63. package/dist/awsStore-Bx5nCFnS.mjs.map +1 -0
  64. package/dist/awsStore-u3ehhMoY.cjs +138 -0
  65. package/dist/awsStore-u3ehhMoY.cjs.map +1 -0
  66. package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
  67. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  68. package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
  69. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  70. package/dist/backups/runner.cjs +519 -0
  71. package/dist/backups/runner.cjs.map +1 -0
  72. package/dist/backups/runner.d.cts +102 -0
  73. package/dist/backups/runner.d.cts.map +1 -0
  74. package/dist/backups/runner.d.mts +102 -0
  75. package/dist/backups/runner.d.mts.map +1 -0
  76. package/dist/backups/runner.mjs +506 -0
  77. package/dist/backups/runner.mjs.map +1 -0
  78. package/dist/{bundler-mjqGAvu1.cjs → bundler-DWGxNGSB.cjs} +59 -14
  79. package/dist/bundler-DWGxNGSB.cjs.map +1 -0
  80. package/dist/{bundler-mwH7WOb1.mjs → bundler-Dm0mB7EK.mjs} +59 -14
  81. package/dist/bundler-Dm0mB7EK.mjs.map +1 -0
  82. package/dist/cli-CYeZF85I.cjs +80 -0
  83. package/dist/cli-CYeZF85I.cjs.map +1 -0
  84. package/dist/cli-Qm-8tG46.mjs +80 -0
  85. package/dist/cli-Qm-8tG46.mjs.map +1 -0
  86. package/dist/compose-BVeevJO_.mjs +3139 -0
  87. package/dist/compose-BVeevJO_.mjs.map +1 -0
  88. package/dist/compose-CXgwCuqv.mjs +1560 -0
  89. package/dist/compose-CXgwCuqv.mjs.map +1 -0
  90. package/dist/compose-CshnO-Th.cjs +1919 -0
  91. package/dist/compose-CshnO-Th.cjs.map +1 -0
  92. package/dist/compose-IsvqY6iX.cjs +3240 -0
  93. package/dist/compose-IsvqY6iX.cjs.map +1 -0
  94. package/dist/config-B8gSu59v.d.mts +291 -0
  95. package/dist/config-B8gSu59v.d.mts.map +1 -0
  96. package/dist/config-u5XdE1Cq.d.cts +291 -0
  97. package/dist/config-u5XdE1Cq.d.cts.map +1 -0
  98. package/dist/config.cjs +457 -9
  99. package/dist/config.cjs.map +1 -0
  100. package/dist/config.d.cts +4 -117
  101. package/dist/config.d.mts +4 -117
  102. package/dist/config.mjs +441 -3
  103. package/dist/config.mjs.map +1 -0
  104. package/dist/credentialSchemas-BzJiK1nQ.mjs +236 -0
  105. package/dist/credentialSchemas-BzJiK1nQ.mjs.map +1 -0
  106. package/dist/credentialSchemas-OVXofU-r.cjs +271 -0
  107. package/dist/credentialSchemas-OVXofU-r.cjs.map +1 -0
  108. package/dist/credentials-CKIeLL7T.mjs +1838 -0
  109. package/dist/credentials-CKIeLL7T.mjs.map +1 -0
  110. package/dist/credentials-DzR2j8h1.cjs +2293 -0
  111. package/dist/credentials-DzR2j8h1.cjs.map +1 -0
  112. package/dist/databases-CuTL1e7s.cjs +703 -0
  113. package/dist/databases-CuTL1e7s.cjs.map +1 -0
  114. package/dist/databases-zN-gEox0.mjs +588 -0
  115. package/dist/databases-zN-gEox0.mjs.map +1 -0
  116. package/dist/define-6poNqm5O.mjs +106 -0
  117. package/dist/define-6poNqm5O.mjs.map +1 -0
  118. package/dist/define-crmMcXFS.cjs +153 -0
  119. package/dist/define-crmMcXFS.cjs.map +1 -0
  120. package/dist/deploy/public.cjs +211 -0
  121. package/dist/deploy/public.cjs.map +1 -0
  122. package/dist/deploy/public.d.cts +658 -0
  123. package/dist/deploy/public.d.cts.map +1 -0
  124. package/dist/deploy/public.d.mts +658 -0
  125. package/dist/deploy/public.d.mts.map +1 -0
  126. package/dist/deploy/public.mjs +144 -0
  127. package/dist/deploy/public.mjs.map +1 -0
  128. package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
  129. package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
  130. package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
  131. package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
  132. package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
  133. package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
  134. package/dist/deploy/sniffer-hooks.cjs +1 -1
  135. package/dist/deploy/sniffer-hooks.mjs +1 -1
  136. package/dist/deploy/sniffer-loader.cjs +2 -2
  137. package/dist/deploy/sniffer-loader.mjs +1 -1
  138. package/dist/deploy/sniffer-routes-worker.cjs +2 -2
  139. package/dist/deploy/sniffer-routes-worker.mjs +1 -1
  140. package/dist/deploy-CjubyZlP.mjs +3848 -0
  141. package/dist/deploy-CjubyZlP.mjs.map +1 -0
  142. package/dist/deploy-DQjEjUfB.cjs +3904 -0
  143. package/dist/deploy-DQjEjUfB.cjs.map +1 -0
  144. package/dist/destroy-D1375m8C.cjs +789 -0
  145. package/dist/destroy-D1375m8C.cjs.map +1 -0
  146. package/dist/destroy-D4m5aO9k.mjs +788 -0
  147. package/dist/destroy-D4m5aO9k.mjs.map +1 -0
  148. package/dist/discover-39VKSE2i.cjs +1085 -0
  149. package/dist/discover-39VKSE2i.cjs.map +1 -0
  150. package/dist/discover-B_PDDaVj.mjs +940 -0
  151. package/dist/discover-B_PDDaVj.mjs.map +1 -0
  152. package/dist/docker-C27YUUMQ.mjs +1413 -0
  153. package/dist/docker-C27YUUMQ.mjs.map +1 -0
  154. package/dist/docker-CSEAKwFr.cjs +1520 -0
  155. package/dist/docker-CSEAKwFr.cjs.map +1 -0
  156. package/dist/dokploy-CSqDsvY-.mjs +38 -0
  157. package/dist/dokploy-CSqDsvY-.mjs.map +1 -0
  158. package/dist/dokploy-DJDdiFz6.cjs +38 -0
  159. package/dist/dokploy-DJDdiFz6.cjs.map +1 -0
  160. package/dist/drivers-BhdC9Efj.cjs +248 -0
  161. package/dist/drivers-BhdC9Efj.cjs.map +1 -0
  162. package/dist/drivers-wcDnzf7l.mjs +213 -0
  163. package/dist/drivers-wcDnzf7l.mjs.map +1 -0
  164. package/dist/eas-DC3F8cy0.mjs +334 -0
  165. package/dist/eas-DC3F8cy0.mjs.map +1 -0
  166. package/dist/eas-DryGYjFk.cjs +337 -0
  167. package/dist/eas-DryGYjFk.cjs.map +1 -0
  168. package/dist/emit-C4KSXOeS.mjs +153 -0
  169. package/dist/emit-C4KSXOeS.mjs.map +1 -0
  170. package/dist/emit-DiW0kbue.cjs +164 -0
  171. package/dist/emit-DiW0kbue.cjs.map +1 -0
  172. package/dist/encryption-8qZGm15p.cjs +90 -0
  173. package/dist/encryption-8qZGm15p.cjs.map +1 -0
  174. package/dist/encryption-C8Y8Ly6n.mjs +89 -0
  175. package/dist/encryption-C8Y8Ly6n.mjs.map +1 -0
  176. package/dist/engine-C9E0MeLm.mjs +3216 -0
  177. package/dist/engine-C9E0MeLm.mjs.map +1 -0
  178. package/dist/engine-DI7JAyiD.cjs +3329 -0
  179. package/dist/engine-DI7JAyiD.cjs.map +1 -0
  180. package/dist/errors-D8Gwp5kU.mjs +23 -0
  181. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  182. package/dist/errors-DMC4Umsb.cjs +34 -0
  183. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  184. package/dist/github-DdaV-Gll.mjs +977 -0
  185. package/dist/github-DdaV-Gll.mjs.map +1 -0
  186. package/dist/github-g3nRZlli.cjs +978 -0
  187. package/dist/github-g3nRZlli.cjs.map +1 -0
  188. package/dist/googlePlay-BHJ_iThq.cjs +931 -0
  189. package/dist/googlePlay-BHJ_iThq.cjs.map +1 -0
  190. package/dist/googlePlay-BmeR1kY4.mjs +931 -0
  191. package/dist/googlePlay-BmeR1kY4.mjs.map +1 -0
  192. package/dist/iam-BoYPPNdM.cjs +521 -0
  193. package/dist/iam-BoYPPNdM.cjs.map +1 -0
  194. package/dist/iam-ra1_Y405.mjs +442 -0
  195. package/dist/iam-ra1_Y405.mjs.map +1 -0
  196. package/dist/{index-RCUizGxL.d.cts → index-1H93w_H6.d.cts} +38 -14
  197. package/dist/index-1H93w_H6.d.cts.map +1 -0
  198. package/dist/{index-B4H4XF7A.d.mts → index-DFZ0SMwN.d.mts} +38 -14
  199. package/dist/index-DFZ0SMwN.d.mts.map +1 -0
  200. package/dist/index.cjs +15142 -13470
  201. package/dist/index.cjs.map +1 -1
  202. package/dist/index.mjs +14959 -13285
  203. package/dist/index.mjs.map +1 -1
  204. package/dist/local-Bkv-e8uM.mjs +224 -0
  205. package/dist/local-Bkv-e8uM.mjs.map +1 -0
  206. package/dist/local-DTidpa-a.cjs +241 -0
  207. package/dist/local-DTidpa-a.cjs.map +1 -0
  208. package/dist/migrate-BZRsJwni.mjs +181 -0
  209. package/dist/migrate-BZRsJwni.mjs.map +1 -0
  210. package/dist/migrate-CXLhrHwu.cjs +272 -0
  211. package/dist/migrate-CXLhrHwu.cjs.map +1 -0
  212. package/dist/migrate-DNOI23QA.mjs +267 -0
  213. package/dist/migrate-DNOI23QA.mjs.map +1 -0
  214. package/dist/migrate-DU4MtKxz.cjs +181 -0
  215. package/dist/migrate-DU4MtKxz.cjs.map +1 -0
  216. package/dist/next.cjs +59 -0
  217. package/dist/next.cjs.map +1 -0
  218. package/dist/next.d.cts +44 -0
  219. package/dist/next.d.cts.map +1 -0
  220. package/dist/next.d.mts +44 -0
  221. package/dist/next.d.mts.map +1 -0
  222. package/dist/next.mjs +58 -0
  223. package/dist/next.mjs.map +1 -0
  224. package/dist/notes-1TM_Vzi7.mjs +408 -0
  225. package/dist/notes-1TM_Vzi7.mjs.map +1 -0
  226. package/dist/notes-BpaXOAkA.cjs +509 -0
  227. package/dist/notes-BpaXOAkA.cjs.map +1 -0
  228. package/dist/openapi.cjs +213 -7
  229. package/dist/openapi.cjs.map +1 -0
  230. package/dist/openapi.d.cts +32 -8
  231. package/dist/openapi.d.cts.map +1 -1
  232. package/dist/openapi.d.mts +32 -8
  233. package/dist/openapi.d.mts.map +1 -1
  234. package/dist/openapi.mjs +208 -2
  235. package/dist/openapi.mjs.map +1 -0
  236. package/dist/projectBucket-BRgsSv2P.mjs +222 -0
  237. package/dist/projectBucket-BRgsSv2P.mjs.map +1 -0
  238. package/dist/projectBucket-DbEWuLGX.cjs +263 -0
  239. package/dist/projectBucket-DbEWuLGX.cjs.map +1 -0
  240. package/dist/provider-BqpjG9QM.cjs +57 -0
  241. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  242. package/dist/provider-CEOKk8NS.mjs +46 -0
  243. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  244. package/dist/publish-BN1l3tPF.cjs +124 -0
  245. package/dist/publish-BN1l3tPF.cjs.map +1 -0
  246. package/dist/publish-DjFgxu2v.mjs +123 -0
  247. package/dist/publish-DjFgxu2v.mjs.map +1 -0
  248. package/dist/ready-COJHr1Yi.mjs +375 -0
  249. package/dist/ready-COJHr1Yi.mjs.map +1 -0
  250. package/dist/ready-DcD0SCnV.cjs +404 -0
  251. package/dist/ready-DcD0SCnV.cjs.map +1 -0
  252. package/dist/reconcile/public.cjs +3 -5
  253. package/dist/reconcile/public.d.cts +33 -89
  254. package/dist/reconcile/public.d.cts.map +1 -1
  255. package/dist/reconcile/public.d.mts +33 -89
  256. package/dist/reconcile/public.d.mts.map +1 -1
  257. package/dist/reconcile/public.mjs +3 -3
  258. package/dist/reconcile--I7V4Klj.mjs +34 -0
  259. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  260. package/dist/reconcile-CuCQBa5-.cjs +34 -0
  261. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  262. package/dist/resolve-BHVyg4Hg.cjs +316 -0
  263. package/dist/resolve-BHVyg4Hg.cjs.map +1 -0
  264. package/dist/resolve-NEKsqNAw.mjs +263 -0
  265. package/dist/resolve-NEKsqNAw.mjs.map +1 -0
  266. package/dist/rollback-BVgyLE7B.mjs +136 -0
  267. package/dist/rollback-BVgyLE7B.mjs.map +1 -0
  268. package/dist/rollback-CUjvOIDE.cjs +165 -0
  269. package/dist/rollback-CUjvOIDE.cjs.map +1 -0
  270. package/dist/runtime-CKOkIrw0.d.cts +82 -0
  271. package/dist/runtime-CKOkIrw0.d.cts.map +1 -0
  272. package/dist/runtime-Cdvv8SfU.d.mts +82 -0
  273. package/dist/runtime-Cdvv8SfU.d.mts.map +1 -0
  274. package/dist/s3-BO4yr61G.mjs +240 -0
  275. package/dist/s3-BO4yr61G.mjs.map +1 -0
  276. package/dist/s3-DnPbDfQN.cjs +240 -0
  277. package/dist/s3-DnPbDfQN.cjs.map +1 -0
  278. package/dist/sandbox/config-worker.cjs +43 -0
  279. package/dist/sandbox/config-worker.cjs.map +1 -0
  280. package/dist/sandbox/config-worker.d.cts +1 -0
  281. package/dist/sandbox/config-worker.d.mts +1 -0
  282. package/dist/sandbox/config-worker.mjs +44 -0
  283. package/dist/sandbox/config-worker.mjs.map +1 -0
  284. package/dist/sandbox/credentials-worker.cjs +53 -0
  285. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  286. package/dist/sandbox/credentials-worker.d.cts +1 -0
  287. package/dist/sandbox/credentials-worker.d.mts +1 -0
  288. package/dist/sandbox/credentials-worker.mjs +54 -0
  289. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  290. package/dist/sandbox/discover-worker.cjs +47 -0
  291. package/dist/sandbox/discover-worker.cjs.map +1 -0
  292. package/dist/sandbox/discover-worker.d.cts +1 -0
  293. package/dist/sandbox/discover-worker.d.mts +1 -0
  294. package/dist/sandbox/discover-worker.mjs +48 -0
  295. package/dist/sandbox/discover-worker.mjs.map +1 -0
  296. package/dist/sandbox/migrate-worker.cjs +75 -0
  297. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  298. package/dist/sandbox/migrate-worker.d.cts +1 -0
  299. package/dist/sandbox/migrate-worker.d.mts +1 -0
  300. package/dist/sandbox/migrate-worker.mjs +76 -0
  301. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  302. package/dist/{workspace-B8NLb54N.cjs → schemas-BCwKKA42.mjs} +399 -1173
  303. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  304. package/dist/{workspace-DI-M3BnN.mjs → schemas-BQ_v0lEX.cjs} +487 -982
  305. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  306. package/dist/secretsManager-CJyxFcBH.mjs +113 -0
  307. package/dist/secretsManager-CJyxFcBH.mjs.map +1 -0
  308. package/dist/secretsManager-D8on44WI.cjs +124 -0
  309. package/dist/secretsManager-D8on44WI.cjs.map +1 -0
  310. package/dist/seeds-Bc3niNVb.cjs +382 -0
  311. package/dist/seeds-Bc3niNVb.cjs.map +1 -0
  312. package/dist/seeds-Ccn0Ru2T.mjs +299 -0
  313. package/dist/seeds-Ccn0Ru2T.mjs.map +1 -0
  314. package/dist/serverSetup-BxnCM11A.mjs +685 -0
  315. package/dist/serverSetup-BxnCM11A.mjs.map +1 -0
  316. package/dist/serverSetup-DScJ7tQs.cjs +685 -0
  317. package/dist/serverSetup-DScJ7tQs.cjs.map +1 -0
  318. package/dist/sniffer-9smKtb86.mjs +1824 -0
  319. package/dist/sniffer-9smKtb86.mjs.map +1 -0
  320. package/dist/sniffer-DHcxlSJF.cjs +1997 -0
  321. package/dist/sniffer-DHcxlSJF.cjs.map +1 -0
  322. package/dist/snsSubscriptions-B8TYeAM-.cjs +1184 -0
  323. package/dist/snsSubscriptions-B8TYeAM-.cjs.map +1 -0
  324. package/dist/snsSubscriptions-CygsiXhb.mjs +1053 -0
  325. package/dist/snsSubscriptions-CygsiXhb.mjs.map +1 -0
  326. package/dist/sst-Bgb3WWEl.mjs +478 -0
  327. package/dist/sst-Bgb3WWEl.mjs.map +1 -0
  328. package/dist/sst-DiHVSku5.cjs +501 -0
  329. package/dist/sst-DiHVSku5.cjs.map +1 -0
  330. package/dist/stack-A3evQgbk.cjs +2512 -0
  331. package/dist/stack-A3evQgbk.cjs.map +1 -0
  332. package/dist/stack-Cy2FwO3Z.mjs +2331 -0
  333. package/dist/stack-Cy2FwO3Z.mjs.map +1 -0
  334. package/dist/stage-Bm1x9Anp.cjs +313 -0
  335. package/dist/stage-Bm1x9Anp.cjs.map +1 -0
  336. package/dist/stage-Dgy08WVL.mjs +302 -0
  337. package/dist/stage-Dgy08WVL.mjs.map +1 -0
  338. package/dist/stages-BWg3NU3J.cjs +190 -0
  339. package/dist/stages-BWg3NU3J.cjs.map +1 -0
  340. package/dist/stages-COiipV8N.mjs +190 -0
  341. package/dist/stages-COiipV8N.mjs.map +1 -0
  342. package/dist/target/public.cjs +15 -0
  343. package/dist/target/public.d.cts +28 -0
  344. package/dist/target/public.d.cts.map +1 -0
  345. package/dist/target/public.d.mts +28 -0
  346. package/dist/target/public.d.mts.map +1 -0
  347. package/dist/target/public.mjs +4 -0
  348. package/dist/terminal-BDRxzEZD.cjs +85 -0
  349. package/dist/terminal-BDRxzEZD.cjs.map +1 -0
  350. package/dist/terminal-BRAIvH83.mjs +85 -0
  351. package/dist/terminal-BRAIvH83.mjs.map +1 -0
  352. package/dist/types-Bl_CwZC9.cjs +90 -0
  353. package/dist/types-Bl_CwZC9.cjs.map +1 -0
  354. package/dist/{types-7R81hu0i.d.mts → types-DEmuMHsS.d.cts} +2147 -428
  355. package/dist/types-DEmuMHsS.d.cts.map +1 -0
  356. package/dist/types-Y1NfWlyG.mjs +61 -0
  357. package/dist/types-Y1NfWlyG.mjs.map +1 -0
  358. package/dist/{types-N7c2O2m7.d.cts → types-g_S0_RAi.d.mts} +2145 -428
  359. package/dist/types-g_S0_RAi.d.mts.map +1 -0
  360. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  361. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  362. package/dist/utils-D_fxUqvU.mjs +156 -0
  363. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  364. package/dist/vitest.cjs +65 -0
  365. package/dist/vitest.cjs.map +1 -0
  366. package/dist/vitest.d.cts +29 -0
  367. package/dist/vitest.d.cts.map +1 -0
  368. package/dist/vitest.d.mts +29 -0
  369. package/dist/vitest.d.mts.map +1 -0
  370. package/dist/vitest.mjs +65 -0
  371. package/dist/vitest.mjs.map +1 -0
  372. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  373. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  374. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  375. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  376. package/dist/workspace/index.cjs +6 -2
  377. package/dist/workspace/index.d.cts +3 -3
  378. package/dist/workspace/index.d.mts +3 -3
  379. package/dist/workspace/index.mjs +2 -2
  380. package/dist/workspace-CEpojAus.cjs +3528 -0
  381. package/dist/workspace-CEpojAus.cjs.map +1 -0
  382. package/dist/workspace-_aoe8v6u.mjs +2990 -0
  383. package/dist/workspace-_aoe8v6u.mjs.map +1 -0
  384. package/package.json +75 -13
  385. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  386. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  387. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  388. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  389. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  390. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  391. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  392. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  393. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  394. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  395. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  396. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  397. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  398. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  399. package/dist/bundler-mjqGAvu1.cjs.map +0 -1
  400. package/dist/bundler-mwH7WOb1.mjs.map +0 -1
  401. package/dist/config-CdTMeMU_.cjs +0 -467
  402. package/dist/config-CdTMeMU_.cjs.map +0 -1
  403. package/dist/config-DPnPkWyH.mjs +0 -414
  404. package/dist/config-DPnPkWyH.mjs.map +0 -1
  405. package/dist/config.d.cts.map +0 -1
  406. package/dist/config.d.mts.map +0 -1
  407. package/dist/credentials-fJP5-fa1.mjs +0 -2780
  408. package/dist/credentials-fJP5-fa1.mjs.map +0 -1
  409. package/dist/credentials-tvyReUAd.cjs +0 -2917
  410. package/dist/credentials-tvyReUAd.cjs.map +0 -1
  411. package/dist/discover-BERGFg8v.cjs +0 -288
  412. package/dist/discover-BERGFg8v.cjs.map +0 -1
  413. package/dist/discover-CK-n3w6b.mjs +0 -244
  414. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  415. package/dist/emit-BdoPFjZf.cjs +0 -253
  416. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  417. package/dist/emit-Bzq7JsMP.mjs +0 -224
  418. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  419. package/dist/generator-LfZU7NlU.mjs +0 -247
  420. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  421. package/dist/generator-Wdfp0jCS.cjs +0 -282
  422. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  423. package/dist/github-CAfKyYPN.mjs +0 -216
  424. package/dist/github-CAfKyYPN.mjs.map +0 -1
  425. package/dist/github-DVE8Gg_F.cjs +0 -216
  426. package/dist/github-DVE8Gg_F.cjs.map +0 -1
  427. package/dist/index-B4H4XF7A.d.mts.map +0 -1
  428. package/dist/index-RCUizGxL.d.cts.map +0 -1
  429. package/dist/openapi-BeckoaP9.cjs +0 -2038
  430. package/dist/openapi-BeckoaP9.cjs.map +0 -1
  431. package/dist/openapi-DolhBm6r.mjs +0 -1991
  432. package/dist/openapi-DolhBm6r.mjs.map +0 -1
  433. package/dist/reconcile-Cq4cO83R.cjs +0 -136
  434. package/dist/reconcile-Cq4cO83R.cjs.map +0 -1
  435. package/dist/reconcile-fmoluZmZ.mjs +0 -113
  436. package/dist/reconcile-fmoluZmZ.mjs.map +0 -1
  437. package/dist/ssm-BKN1Cg4z.mjs +0 -60
  438. package/dist/ssm-BKN1Cg4z.mjs.map +0 -1
  439. package/dist/ssm-FxeSAt35.cjs +0 -60
  440. package/dist/ssm-FxeSAt35.cjs.map +0 -1
  441. package/dist/storage-DgypfSD6.cjs +0 -351
  442. package/dist/storage-DgypfSD6.cjs.map +0 -1
  443. package/dist/storage-TP0x118M.mjs +0 -304
  444. package/dist/storage-TP0x118M.mjs.map +0 -1
  445. package/dist/transfer-4A4S2hcw.mjs +0 -122
  446. package/dist/transfer-4A4S2hcw.mjs.map +0 -1
  447. package/dist/transfer-DdmtKLzi.cjs +0 -151
  448. package/dist/transfer-DdmtKLzi.cjs.map +0 -1
  449. package/dist/types-7R81hu0i.d.mts.map +0 -1
  450. package/dist/types-N7c2O2m7.d.cts.map +0 -1
  451. package/dist/workspace-B8NLb54N.cjs.map +0 -1
  452. package/dist/workspace-DI-M3BnN.mjs.map +0 -1
@@ -0,0 +1,1413 @@
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { ot as run } from "./credentials-CKIeLL7T.mjs";
3
+ import { ot as appKey } from "./workspace-_aoe8v6u.mjs";
4
+ import { B as WORKER_PORT, D as ORIGIN_VERIFY_HEADER, F as imageLayout, G as generateEntryDockerfile, Gt as PROCESSORS_DEV_PREFIX, J as generateProcessorDockerfile, K as generateNextjsDockerfile, Lt as siteClientTelemetry, M as appImageOptions, O as PROCESSOR_ORIGIN_SECRET_ENV, Q as resolveDockerConfig, R as PROCESSOR_PORT, U as generateBackendDockerfile, W as generateDockerignore, X as generateWorkerDockerfile, Y as generateViteStaticDockerfile, ct as processorUnits, g as COMPOSE_PATH, i as dockerfileOf, lt as workerUnits, m as reconcileWorkspace, q as generateNodeWebDockerfile, st as processorUnitName } from "./apps-DGod3aS9.mjs";
5
+ import { rt as getPublicUrlArgNames } from "./compose-CXgwCuqv.mjs";
6
+ import { t as SubscriberGenerator } from "./SubscriberGenerator-CfZWX0lT.mjs";
7
+ import { a as startTelemetryCode, n as runtimeFor, s as writeTelemetryModule } from "./EndpointGenerator-CSKhAD6W.mjs";
8
+ import { v as ConstructGenerator, y as output } from "./discover-B_PDDaVj.mjs";
9
+ import { loadWorkspaceConfig } from "./config.mjs";
10
+ import { dirname, join, relative } from "node:path";
11
+ import { existsSync } from "node:fs";
12
+ import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
13
+ import { IMAGE_ORIGINS_KEY, PUBLIC_PREFIX, imageOriginSources, providedKeyFor, publicEnvFor } from "@geekmidas/manifest";
14
+ import { Cron } from "@geekmidas/constructs/crons";
15
+ import { Processor } from "@geekmidas/constructs/processors";
16
+ import { Queue } from "@geekmidas/constructs/queue";
17
+ //#region src/docker/imageRef.ts
18
+ /**
19
+ * An image reference, checked before it reaches `docker`.
20
+ *
21
+ * The parts come from the workspace — a registry in `gkm.config.ts`, an image
22
+ * name from the project, a tag from `--tag` — and an argument array already
23
+ * keeps them out of a shell. What it cannot do is stop `docker` reading a value
24
+ * that starts with `-` as one of its own flags, so a ref is held to Docker's
25
+ * own grammar (distribution/reference) and anything else is refused by name
26
+ * before a build starts.
27
+ */
28
+ const DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
29
+ const DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
30
+ const PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
31
+ 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,})?$`);
32
+ /** Docker refuses a repository name longer than this. */
33
+ const MAX_NAME_LENGTH = 255;
34
+ /** A value that is not an image reference was about to be built or pushed. */
35
+ var ImageRefInvalid = class extends GkmError {
36
+ ref;
37
+ constructor(ref) {
38
+ 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.`);
39
+ this.ref = ref;
40
+ this.name = "ImageRefInvalid";
41
+ }
42
+ };
43
+ /** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */
44
+ function validateImageRef(ref) {
45
+ const name = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
46
+ if (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) throw new ImageRefInvalid(ref);
47
+ return ref;
48
+ }
49
+ //#endregion
50
+ //#region src/generators/ProcessorGenerator.ts
51
+ /** Where a file server's processor entry lives, under an app's `.gkm/server`. */
52
+ function processorEntryDir(serverDir, fileServerId) {
53
+ return join(serverDir, "processors", processorUnitName(fileServerId));
54
+ }
55
+ /** The file its bundle is written to, beside the server's. */
56
+ function processorBundleName(fileServerId) {
57
+ return `${processorUnitName(fileServerId)}.mjs`;
58
+ }
59
+ /**
60
+ * A file server's processors, as the build generates them.
61
+ *
62
+ * On AWS each is a Lambda behind a function URL — the CDN's origin for its
63
+ * pattern. On a server they are one process per file server, the processor
64
+ * unit (see {@link ProcessorGenerator.buildEntry}), so the `server` target
65
+ * generates nothing per processor here.
66
+ */
67
+ var ProcessorGenerator = class extends ConstructGenerator {
68
+ isConstruct(value) {
69
+ return Processor.isProcessor(value);
70
+ }
71
+ async build(context, constructs, outputDir, options) {
72
+ if ((options?.target ?? "aws") !== "aws" || constructs.length === 0) return [];
73
+ const dir = join(outputDir, "processors");
74
+ await mkdir(dir, { recursive: true });
75
+ const infos = [];
76
+ for (const { key, construct, path } of constructs) {
77
+ const file = join(dir, `${key}.ts`);
78
+ const importPath = relative(dirname(file), path.relative).replace(/\.ts$/, ".js");
79
+ await writeFile(file, `import { AWSLambdaProcessor } from '@geekmidas/constructs/processors';
80
+ import { ${key} } from '${importPath}';
81
+ ${context.storageDrivers?.imports ?? ""}
82
+ ${context.storageDrivers?.setup ? `\n// The handler registers the drivers its target needs.\n${context.storageDrivers.setup}\n` : ""}
83
+ const adapter = new AWSLambdaProcessor(${key});
84
+
85
+ export const handler = adapter.handler;
86
+ `);
87
+ infos.push(await processorInfo(key, construct, relative(options?.root ?? process.cwd(), file).replace(/\.ts$/, ".handler"), context));
88
+ }
89
+ return infos;
90
+ }
91
+ /**
92
+ * `gkm dev`'s half: `processors.ts` beside the dev server's app, mounting
93
+ * each file server's processors under `/__gkm/processors/<FileServer>`.
94
+ * The local edge sends each pattern on the file server's host there, so
95
+ * `processedUrl()` answers locally as it does deployed.
96
+ *
97
+ * In the dev server's own process rather than a unit of its own: locally
98
+ * there is no CPU to protect, and the dev server already reloads on change.
99
+ */
100
+ async buildDev(outputDir, processors) {
101
+ await mkdir(outputDir, { recursive: true });
102
+ const file = join(outputDir, "processors.ts");
103
+ const imports = processors.map(({ key, path }) => {
104
+ const specifier = relative(outputDir, path.absolute).replace(/\.ts$/, ".js");
105
+ return `import { ${key} } from '${specifier.startsWith(".") ? specifier : `./${specifier}`}';`;
106
+ }).join("\n");
107
+ const byServer = /* @__PURE__ */ new Map();
108
+ for (const { key, construct } of processors) byServer.set(construct.surfaceId, [...byServer.get(construct.surfaceId) ?? [], key]);
109
+ const units = [...byServer.entries()].map(([id, keys]) => ` ${JSON.stringify(id)}: [${keys.join(", ")}],`).join("\n");
110
+ await writeFile(file, `/**
111
+ * Generated processors setup for \`gkm dev\`.
112
+ *
113
+ * Each file server's processors, under ${PROCESSORS_DEV_PREFIX}<FileServer>: the
114
+ * local edge rewrites each processor pattern on the file server's host here.
115
+ */
116
+ import type { EnvironmentParser } from '@geekmidas/envkit';
117
+ import { processorServer } from '@geekmidas/constructs/processors';
118
+ ${imports}
119
+
120
+ export function setupProcessors(
121
+ app: { all: (path: string, handler: (c: any) => unknown) => unknown },
122
+ envParser: EnvironmentParser<any>,
123
+ ): void {
124
+ const units: Record<string, ReturnType<typeof processorServer>> = Object.fromEntries(
125
+ Object.entries({
126
+ ${units}
127
+ }).map(([id, processors]) => [id, processorServer(processors, envParser)]),
128
+ );
129
+
130
+ app.all('${PROCESSORS_DEV_PREFIX}:server/*', async (c: any) => {
131
+ const server = c.req.param('server') as string;
132
+ const serve = units[server];
133
+ if (!serve) return c.notFound();
134
+ const path = c.req.path.slice(\`${PROCESSORS_DEV_PREFIX}\${server}\`.length) || '/';
135
+ const response = await serve({ method: c.req.method, path });
136
+ if (!response) {
137
+ return new Response(null, {
138
+ status: 404,
139
+ headers: { 'cache-control': 'public, max-age=60' },
140
+ });
141
+ }
142
+ return new Response(c.req.method === 'HEAD' ? null : response.body, {
143
+ status: response.status,
144
+ headers: response.headers,
145
+ });
146
+ });
147
+ }
148
+ `);
149
+ return file;
150
+ }
151
+ /**
152
+ * A file server's processor unit: one process answering each of its
153
+ * processors' patterns, and `/health`. Returns its entry, `processors.ts`.
154
+ *
155
+ * Its own process because making a derivative is CPU-bound — a resize
156
+ * spike in the API's process would be every request's latency.
157
+ */
158
+ async buildEntry(input) {
159
+ const { context, outputDir, processors } = input;
160
+ await mkdir(outputDir, { recursive: true });
161
+ await writeTelemetryModule(outputDir, input.telemetry);
162
+ const healthCheck = context.production?.healthCheck ?? "/health";
163
+ const imports = processors.map(({ key, path }) => {
164
+ const specifier = relative(outputDir, path.absolute).replace(/\.ts$/, ".js");
165
+ return `import { ${key} } from '${specifier.startsWith(".") ? specifier : `./${specifier}`}';`;
166
+ }).join("\n");
167
+ const entry = join(outputDir, "processors.ts");
168
+ await writeFile(entry, `#!/usr/bin/env node
169
+ /**
170
+ * Production entry for ${input.fileServerId}'s processors.
171
+ * Generated by 'gkm build --production'.
172
+ *
173
+ * Answers each processor's pattern, and ${healthCheck} on PORT. The edge
174
+ * routes only those patterns here; everything else on the file server's
175
+ * domain is the bucket.
176
+ */
177
+ import { timingSafeEqual } from 'node:crypto';
178
+ import { createServer } from 'node:http';
179
+ import { runShutdownHooks } from '@geekmidas/constructs';
180
+ import { processorServer } from '@geekmidas/constructs/processors';
181
+ ${context.storageDrivers?.imports ?? ""}
182
+ ${imports}
183
+
184
+ ${startTelemetryCode([healthCheck])}
185
+ ${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n` : ""}
186
+ process.env.GKM_APP_NAME ??= ${JSON.stringify(processorUnitName(input.fileServerId))};
187
+
188
+ const processors = [${processors.map(({ key }) => key).join(", ")}];
189
+ const serve = processorServer(processors);
190
+ const port = Number(process.env.PORT) || 3000;
191
+ let stopping = false;
192
+
193
+ ${input.telemetry ? REQUEST_SPANS : NO_REQUEST_SPANS}
194
+ // Where the CDN fronts this unit, the secret it adds to every request: one
195
+ // without it is refused here, whatever the edge in front did or could not.
196
+ const originSecret = process.env.${PROCESSOR_ORIGIN_SECRET_ENV}
197
+ ? Buffer.from(process.env.${PROCESSOR_ORIGIN_SECRET_ENV})
198
+ : undefined;
199
+ const fromOrigin = (header: string | string[] | undefined) => {
200
+ if (!originSecret) return true;
201
+ const given = Buffer.from(typeof header === 'string' ? header : '');
202
+ return given.length === originSecret.length && timingSafeEqual(given, originSecret);
203
+ };
204
+
205
+ const server = createServer(async (req, res) => {
206
+ const method = req.method ?? 'GET';
207
+ const path = (req.url ?? '/').split('?')[0] ?? '/';
208
+ if (path === ${JSON.stringify(healthCheck)}) {
209
+ res.writeHead(stopping ? 503 : 200, { 'content-type': 'application/json' });
210
+ res.end(JSON.stringify({ status: stopping ? 'stopping' : 'ok' }));
211
+ return;
212
+ }
213
+ if (!fromOrigin(req.headers[${JSON.stringify(ORIGIN_VERIFY_HEADER.toLowerCase())}])) {
214
+ res.writeHead(403, { 'cache-control': 'no-store' }).end();
215
+ return;
216
+ }
217
+ await traced(method, path, async () => {
218
+ try {
219
+ const response = await serve({ method, path });
220
+ if (!response) {
221
+ res.writeHead(404, { 'cache-control': 'public, max-age=60' }).end();
222
+ return 404;
223
+ }
224
+ res.writeHead(response.status, response.headers);
225
+ res.end(method === 'HEAD' ? undefined : response.body);
226
+ return response.status;
227
+ } catch (error) {
228
+ console.error(error);
229
+ res.writeHead(500, { 'cache-control': 'no-store' }).end();
230
+ return 500;
231
+ }
232
+ });
233
+ });
234
+ server.listen(port);
235
+
236
+ const shutdown = async () => {
237
+ if (stopping) return;
238
+ stopping = true;
239
+ setTimeout(() => process.exit(1), Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000).unref();
240
+ server.close();
241
+ await runShutdownHooks((error) => console.error(error));
242
+ process.exit(0);
243
+ };
244
+ process.on('SIGTERM', shutdown);
245
+ process.on('SIGINT', shutdown);
246
+ `);
247
+ return entry;
248
+ }
249
+ };
250
+ /**
251
+ * A SERVER span per request, once telemetry has started — opened by the unit
252
+ * rather than by hooking node:http, which sees nothing inside a bundle. Named
253
+ * after the processor's pattern, never the key, which has no bound.
254
+ *
255
+ * Only in an entry whose file server has a `Telemetry` node: the bundle
256
+ * follows the import, and an app without one need not install the API.
257
+ */
258
+ const REQUEST_SPANS = `const tracing = requestSpans ? await import('@opentelemetry/api') : undefined;
259
+ const routeOf = (path: string) =>
260
+ processors.find((processor) => path.startsWith(processor.prefix))?.pattern;
261
+
262
+ async function traced(
263
+ method: string,
264
+ path: string,
265
+ run: () => Promise<number>,
266
+ ): Promise<void> {
267
+ if (!tracing) {
268
+ await run();
269
+ return;
270
+ }
271
+ const route = routeOf(path);
272
+ await tracing.trace.getTracer('@geekmidas/processors').startActiveSpan(
273
+ route ? \`\${method} \${route}\` : method,
274
+ {
275
+ kind: tracing.SpanKind.SERVER,
276
+ attributes: {
277
+ 'http.request.method': method,
278
+ 'url.path': path,
279
+ ...(route ? { 'http.route': route } : {}),
280
+ },
281
+ },
282
+ async (span) => {
283
+ try {
284
+ const status = await run();
285
+ span.setAttribute('http.response.status_code', status);
286
+ if (status >= 500) span.setStatus({ code: tracing.SpanStatusCode.ERROR });
287
+ } finally {
288
+ span.end();
289
+ }
290
+ },
291
+ );
292
+ }
293
+ `;
294
+ /** The same shape without telemetry: each request just runs. */
295
+ const NO_REQUEST_SPANS = `async function traced(
296
+ _method: string,
297
+ _path: string,
298
+ run: () => Promise<number>,
299
+ ): Promise<void> {
300
+ await run();
301
+ }
302
+ `;
303
+ /** What the manifest records of one processor. */
304
+ async function processorInfo(name, processor, handler, context) {
305
+ return {
306
+ name,
307
+ handler,
308
+ fileServer: processor.surfaceId,
309
+ path: processor.pattern,
310
+ prefix: processor.prefix,
311
+ ...processor.native.length ? { native: [...processor.native] } : {},
312
+ ...processor.timeout !== void 0 ? { timeout: processor.timeout } : {},
313
+ ...processor.memorySize !== void 0 ? { memorySize: processor.memorySize } : {},
314
+ environment: await processor.getEnvironment({ markOptional: context.markOptional }),
315
+ dependencies: processor.constructs
316
+ };
317
+ }
318
+ //#endregion
319
+ //#region src/generators/CronGenerator.ts
320
+ var CronGenerator = class extends ConstructGenerator {
321
+ async build(context, constructs, outputDir, options) {
322
+ const target = options?.target ?? "aws";
323
+ const logger = console;
324
+ const cronInfos = [];
325
+ if (target === "server") {
326
+ await this.generateServerCronsFile(outputDir, constructs);
327
+ logger.log(`Generated server crons file with ${constructs.length} crons`);
328
+ return cronInfos;
329
+ }
330
+ if (constructs.length === 0) return cronInfos;
331
+ const cronsDir = join(outputDir, "crons");
332
+ await mkdir(cronsDir, { recursive: true });
333
+ for (const { key, construct, path } of constructs) {
334
+ const handlerFile = await this.generateCronHandler(cronsDir, path.relative, key, context, construct.owner);
335
+ cronInfos.push({
336
+ name: key,
337
+ handler: relative(options?.root ?? process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
338
+ schedule: construct.schedule || "rate(1 hour)",
339
+ timeout: construct.timeout,
340
+ memorySize: construct.memorySize,
341
+ environment: await construct.getEnvironment({ markOptional: context.markOptional }),
342
+ dependencies: construct.constructs
343
+ });
344
+ logger.log(`Generated cron handler: ${key}`);
345
+ }
346
+ return cronInfos;
347
+ }
348
+ isConstruct(value) {
349
+ return Cron.isCron(value);
350
+ }
351
+ /**
352
+ * The crons file a server entry imports.
353
+ *
354
+ * Shaped after `generateServerSubscribersFile`: one module, every cron, a
355
+ * `setupCrons` the generated entry calls beside `setupSubscribers`.
356
+ *
357
+ * It picks its scheduler from what the process can reach. With a Postgres it
358
+ * uses pg-boss, whose schedules live in the database — so a deployment
359
+ * running four replicas fires each job once, which is the thing a timer in
360
+ * every process gets wrong and does not report. With no database it falls
361
+ * back to timers and says plainly that it is doing so.
362
+ */
363
+ async generateServerCronsFile(outputDir, crons) {
364
+ await mkdir(outputDir, { recursive: true });
365
+ const cronsPath = join(outputDir, "crons.ts");
366
+ if (crons.length === 0) {
367
+ await writeFile(cronsPath, `/**
368
+ * Generated cron setup — this app declares none.
369
+ */
370
+ import type { EnvironmentParser } from '@geekmidas/envkit';
371
+ import type { Logger } from '@geekmidas/logger';
372
+
373
+ export async function setupCrons(
374
+ _envParser: EnvironmentParser<any>,
375
+ _logger: Logger,
376
+ ): Promise<void> {}
377
+
378
+ export function cronsStatus(): { failed: string[]; connections: unknown[] } {
379
+ return { failed: [], connections: [] };
380
+ }
381
+
382
+ export async function stopCrons(): Promise<void> {}
383
+ `);
384
+ return cronsPath;
385
+ }
386
+ const importsByFile = /* @__PURE__ */ new Map();
387
+ for (const { path, key } of crons) {
388
+ const importPath = relative(dirname(cronsPath), path.relative).replace(/\.ts$/, ".js");
389
+ if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
390
+ importsByFile.get(importPath)?.push(key);
391
+ }
392
+ const content = `/**
393
+ * Generated cron setup.
394
+ *
395
+ * Schedules every cron this app declares, in the process that serves it.
396
+ *
397
+ * The schedule lives in Postgres, through pg-boss, in the database the worker
398
+ * named with \`.database(db)\`. That is what makes running several replicas
399
+ * safe: each job fires once, where a timer in every process fires it once per
400
+ * replica and reports nothing.
401
+ *
402
+ * No connection string appears here. The construct that owns the database is
403
+ * the only thing that knows its key, and it is resolved through service
404
+ * discovery like any other dependency.
405
+ */
406
+ import type { EnvironmentParser } from '@geekmidas/envkit';
407
+ import type { Logger } from '@geekmidas/logger';
408
+ import { runCron, scheduleInProcess, toCronExpression } from '@geekmidas/constructs/crons';
409
+ import { ServiceDiscovery } from '@geekmidas/services';
410
+ ${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
411
+
412
+ const crons = [
413
+ ${crons.map(({ key }) => ` { name: '${key}', cron: ${key} }`).join(",\n")}
414
+ ];
415
+
416
+ type Stoppable = { stop: () => Promise<void> | void };
417
+ const running: Stoppable[] = [];
418
+ // What a worker's health check reads: the crons that cannot be scheduled, and
419
+ // the broker connection the schedule is kept through.
420
+ const failed: string[] = [];
421
+ const connections: import('@geekmidas/events').EventConnection[] = [];
422
+
423
+ export async function setupCrons(
424
+ envParser: EnvironmentParser<any>,
425
+ logger: Logger,
426
+ ): Promise<void> {
427
+ if (crons.length === 0) {
428
+ return;
429
+ }
430
+
431
+ const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
432
+
433
+ // Resolved once per cron rather than per firing: registering services on
434
+ // every tick would reconnect a database every minute.
435
+ const prepared = [];
436
+ for (const { name, cron } of crons) {
437
+ try {
438
+ const schedule = toCronExpression(cron.schedule);
439
+ const services = cron.services.length > 0
440
+ ? await serviceDiscovery.register(cron.services)
441
+ : {};
442
+
443
+ prepared.push({ name, cron, schedule, services });
444
+ } catch (error) {
445
+ // An unrepresentable schedule is a build-time mistake, and failing the
446
+ // process for it would take the HTTP server down with it.
447
+ logger.error({ err: error, cron: name }, 'Cron has no runnable schedule, skipping');
448
+ failed.push(name);
449
+ }
450
+ }
451
+
452
+ const run = async (entry: (typeof prepared)[number]) => {
453
+ try {
454
+ // The cron's own function, the way its Lambda would run it — services,
455
+ // the worker's database as \`db\`, its events. It used to call a
456
+ // \`handler\` a Cron does not have, so every firing logged a failure.
457
+ await runCron(entry.cron, serviceDiscovery, entry.name);
458
+ } catch (error) {
459
+ logger.error({ err: error, cron: entry.name }, 'Cron failed');
460
+ }
461
+ };
462
+
463
+ // The app's one pg-boss: the events broker's, as the broker's role, in the
464
+ // broker's schema. A server fires its own crons, and a process scheduling in
465
+ // memory fires each job once per replica — so the schedule lives in
466
+ // Postgres. It used to be a second pg-boss on the worker's database, as the
467
+ // runtime role, which can neither create a schema nor use the broker's.
468
+ const { url, devPid } = envParser
469
+ .create((get) => ({
470
+ url: get('EVENT_PUBLISHER_CONNECTION_STRING').string().optional(),
471
+ // Set by \`gkm dev\` on the server it starts, and by nothing deployed.
472
+ devPid: get('GKM_DEV_PID').string().optional(),
473
+ }))
474
+ .parse();
475
+
476
+ if (!url?.startsWith('pgboss://')) {
477
+ // \`gkm dev\` on a target whose crons are infrastructure once deployed —
478
+ // EventBridge rules on AWS — has no broker to keep a schedule in. It is one
479
+ // process, so a timer fires each job once, which is all pg-boss is for
480
+ // here. Only there: a deployed server firing by timer fires once per
481
+ // replica, so outside dev this stays the error below.
482
+ if (devPid) {
483
+ for (const entry of prepared) {
484
+ running.push(scheduleInProcess(entry.schedule, () => run(entry)));
485
+ logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled in this process');
486
+ }
487
+ return;
488
+ }
489
+
490
+ logger.error(
491
+ { crons: prepared.map(({ name }) => name) },
492
+ 'These crons have nowhere to keep their schedule. On a server they are ' +
493
+ 'scheduled through the pg-boss events broker ' +
494
+ '(EVENT_PUBLISHER_CONNECTION_STRING), and ' +
495
+ (url ? 'the broker configured is not pg-boss.' : 'none is configured.'),
496
+ );
497
+ failed.push(...prepared.map(({ name }) => name));
498
+ return;
499
+ }
500
+
501
+ // Through the registered pg-boss driver, which the entry registers for a
502
+ // server whose broker is pg-boss. Naming \`@geekmidas/events/pgboss\` here
503
+ // made every bundle with a cron resolve pg-boss, whatever its broker.
504
+ const { EventConnectionFactory } = await import('@geekmidas/events');
505
+ const connection = (await EventConnectionFactory.fromConnectionString(
506
+ url,
507
+ )) as import('@geekmidas/events').EventConnection & { instance?: any };
508
+ const boss = connection.instance!;
509
+
510
+ // What this app declares now. Anything else under the prefix belonged to a
511
+ // cron since renamed or deleted, and would keep firing at a handler that has
512
+ // gone.
513
+ //
514
+ // The prefix is \`cron.\` rather than \`cron:\`: pg-boss accepts
515
+ // alphanumerics, underscores, hyphens, periods and slashes in a queue name,
516
+ // and rejects a colon outright.
517
+ const declared = new Set(prepared.map(({ name }) => \`cron.\${name}\`));
518
+ for (const existing of await boss.getSchedules()) {
519
+ if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {
520
+ await boss.unschedule(existing.name);
521
+ logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');
522
+ }
523
+ }
524
+
525
+ for (const entry of prepared) {
526
+ const queue = \`cron.\${entry.name}\`;
527
+ await boss.createQueue(queue);
528
+ // UTC, so this agrees with the schedule a deploy target would have made.
529
+ await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });
530
+ await boss.work(queue, () => run(entry));
531
+
532
+ logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');
533
+ }
534
+
535
+ running.push({ stop: () => connection.close() });
536
+ connections.push(connection);
537
+ logger.info({ count: prepared.length }, 'Crons scheduled');
538
+ }
539
+
540
+ /** The crons that cannot be scheduled, and the connection that schedules the rest. */
541
+ export function cronsStatus(): {
542
+ failed: string[];
543
+ connections: import('@geekmidas/events').EventConnection[];
544
+ } {
545
+ return { failed: [...failed], connections: [...connections] };
546
+ }
547
+
548
+ /**
549
+ * Stop scheduling, let a firing in flight finish, and close the broker
550
+ * connection — pg-boss's graceful stop does all three. The caller bounds it.
551
+ */
552
+ export async function stopCrons(): Promise<void> {
553
+ const open = [...running];
554
+ running.length = 0;
555
+ connections.length = 0;
556
+ await Promise.all(open.map((r) => r.stop()));
557
+ }
558
+ `;
559
+ await writeFile(cronsPath, content);
560
+ return cronsPath;
561
+ }
562
+ async generateCronHandler(outputDir, sourceFile, exportName, context, owner) {
563
+ const handlerFileName = `${exportName}.ts`;
564
+ const handlerPath = join(outputDir, handlerFileName);
565
+ const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
566
+ const runtime = runtimeFor(context, dirname(handlerPath), owner);
567
+ const content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';
568
+ import { ${exportName} } from '${importPath}';
569
+ ${runtime.imports}
570
+ ${context.storageDrivers?.imports ?? ""}
571
+ ${runtime.bindings}
572
+ ${context.storageDrivers?.setup ? `\n// The handler registers the drivers its target needs.\n${context.storageDrivers.setup}\n` : ""}
573
+ const adapter = new AWSScheduledFunction(envParser, ${exportName});
574
+
575
+ export const handler = adapter.handler;
576
+ `;
577
+ await writeFile(handlerPath, content);
578
+ return handlerPath;
579
+ }
580
+ };
581
+ //#endregion
582
+ //#region src/generators/QueueGenerator.ts
583
+ /**
584
+ * Generates the runtime for queue consumers (`worker.queue(…)`).
585
+ *
586
+ * - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that
587
+ * polls each queue in-process, alongside the Hono server, through the queue's
588
+ * own connection string — pg-boss by default, SQS on the AWS emulator.
589
+ * - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed
590
+ * by an SQS event-source mapping.
591
+ */
592
+ var QueueGenerator = class extends ConstructGenerator {
593
+ isConstruct(value) {
594
+ return Queue.isQueue(value);
595
+ }
596
+ async build(context, constructs, outputDir, options) {
597
+ const target = options?.target ?? "aws";
598
+ const logger = console;
599
+ const queueInfos = [];
600
+ if (target === "server") {
601
+ await this.generateServerQueuesFile(outputDir, constructs);
602
+ logger.log(`Generated server queues file with ${constructs.length} queues (polling mode)`);
603
+ return queueInfos;
604
+ }
605
+ if (constructs.length === 0) return queueInfos;
606
+ const queuesDir = join(outputDir, "queues");
607
+ await mkdir(queuesDir, { recursive: true });
608
+ for (const { key, construct, path } of constructs) {
609
+ const handlerFile = await this.generateQueueHandler(queuesDir, path.relative, key, context, construct.owner);
610
+ queueInfos.push({
611
+ name: construct.name,
612
+ handler: relative(options?.root ?? process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
613
+ batchSize: construct.batchSize,
614
+ fifo: construct.fifo,
615
+ timeout: construct.timeout,
616
+ environment: await construct.getEnvironment({ markOptional: context.markOptional }),
617
+ dependencies: construct.constructs
618
+ });
619
+ logger.log(`Generated queue handler: ${key}`);
620
+ }
621
+ return queueInfos;
622
+ }
623
+ async generateQueueHandler(outputDir, sourceFile, exportName, context, owner) {
624
+ const handlerPath = join(outputDir, `${exportName}.ts`);
625
+ const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
626
+ const runtime = runtimeFor(context, dirname(handlerPath), owner);
627
+ const content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';
628
+ import { ${exportName} } from '${importPath}';
629
+ ${runtime.imports}
630
+ ${context.storageDrivers?.imports ?? ""}
631
+ ${runtime.bindings}
632
+ ${context.storageDrivers?.setup ? `\n// The handler registers the drivers its target needs.\n${context.storageDrivers.setup}\n` : ""}
633
+ const adapter = new AWSLambdaQueue(envParser, ${exportName});
634
+
635
+ export const handler = adapter.handler;
636
+ `;
637
+ await writeFile(handlerPath, content);
638
+ return handlerPath;
639
+ }
640
+ async generateServerQueuesFile(outputDir, queues) {
641
+ await mkdir(outputDir, { recursive: true });
642
+ const queuesPath = join(outputDir, "queues.ts");
643
+ if (queues.length === 0) {
644
+ await writeFile(queuesPath, `/**
645
+ * Generated queues setup — this app declares none.
646
+ */
647
+ import type { EnvironmentParser } from '@geekmidas/envkit';
648
+ import type { Logger } from '@geekmidas/logger';
649
+
650
+ export async function setupQueues(
651
+ _envParser: EnvironmentParser<any>,
652
+ _logger: Logger,
653
+ ): Promise<void> {}
654
+
655
+ export function queuesStatus(): { failed: string[]; connections: unknown[] } {
656
+ return { failed: [], connections: [] };
657
+ }
658
+
659
+ export async function stopQueues(): Promise<void> {}
660
+ `);
661
+ return queuesPath;
662
+ }
663
+ const importsByFile = /* @__PURE__ */ new Map();
664
+ for (const { path, key } of queues) {
665
+ const importPath = relative(dirname(queuesPath), path.relative).replace(/\.ts$/, ".js");
666
+ if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
667
+ importsByFile.get(importPath)?.push(key);
668
+ }
669
+ const content = `/**
670
+ * Generated queue consumers setup.
671
+ *
672
+ * Each queue's one consumer polls its own queue, through the queue's own
673
+ * connection string — the one its producers publish on. SQS cannot push, so
674
+ * this is a poller on every transport: pg-boss locally by default, the SQS
675
+ * queue on the AWS emulator.
676
+ *
677
+ * Deployed on Lambda, a queue's consumer is an SQS event source instead.
678
+ */
679
+ import type { EnvironmentParser } from '@geekmidas/envkit';
680
+ import type { Logger } from '@geekmidas/logger';
681
+ import { EventConnectionFactory, Subscriber } from '@geekmidas/events';
682
+ import type { EventConnection } from '@geekmidas/events';
683
+ import { ServiceDiscovery } from '@geekmidas/services';
684
+ ${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
685
+
686
+ const queues = [
687
+ ${queues.map(({ key, construct }) => ` { queue: ${key}, connectionKey: '${providedKeyFor(construct.id, "queue", "publisherConnectionString")}' },`).join("\n")}
688
+ ];
689
+
690
+ // What was opened, and what could not be: a worker's health check reads both,
691
+ // and its shutdown closes what was opened.
692
+ const connections = new Map<string, EventConnection>();
693
+ const failed: string[] = [];
694
+
695
+ export async function setupQueues(
696
+ envParser: EnvironmentParser<any>,
697
+ logger: Logger,
698
+ ): Promise<void> {
699
+ const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
700
+
701
+ for (const { queue, connectionKey } of queues) {
702
+ const connectionString = process.env[connectionKey];
703
+ if (!connectionString) {
704
+ logger.error({ queue: queue.name, connectionKey }, 'No connection string for this queue');
705
+ failed.push(queue.name);
706
+ continue;
707
+ }
708
+
709
+ try {
710
+ let connection = connections.get(connectionString);
711
+ if (!connection) {
712
+ connection = await EventConnectionFactory.fromConnectionString(connectionString);
713
+ connections.set(connectionString, connection);
714
+ }
715
+ const eventSubscriber = await Subscriber.fromConnection(connection);
716
+ const services = queue.services.length > 0
717
+ ? await serviceDiscovery.register(queue.services)
718
+ : {};
719
+ // The queue's database — the worker's, or its own — handed over as \`db\`.
720
+ const db = queue.databaseService
721
+ ? (await serviceDiscovery.register([queue.databaseService]))[
722
+ queue.databaseService.serviceName
723
+ ]
724
+ : undefined;
725
+
726
+ // A queue's messages carry one type — its own name.
727
+ await eventSubscriber.subscribe([queue.name], async (message) => {
728
+ try {
729
+ const validation = await queue.messageSchema['~standard'].validate(message.payload);
730
+ if (validation.issues) {
731
+ logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');
732
+ return;
733
+ }
734
+
735
+ await queue.handler({
736
+ messages: [validation.value],
737
+ services: services,
738
+ logger: queue.logger,
739
+ db,
740
+ } as any);
741
+ } catch (error) {
742
+ logger.error({ err: error, queue: queue.name }, 'Failed to process queue message');
743
+ // Rethrown so the transport keeps the message for a retry.
744
+ throw error;
745
+ }
746
+ });
747
+ logger.info({ queue: queue.name }, 'Queue consumer started polling');
748
+ } catch (error) {
749
+ logger.error({ err: error, queue: queue.name }, 'Failed to set up queue consumer');
750
+ failed.push(queue.name);
751
+ }
752
+ }
753
+ }
754
+
755
+ /** The consumers that could not start, and the connections that did. */
756
+ export function queuesStatus(): { failed: string[]; connections: EventConnection[] } {
757
+ return { failed: [...failed], connections: [...connections.values()] };
758
+ }
759
+
760
+ /**
761
+ * Stop polling, let the messages in flight finish, and close each broker
762
+ * connection — pg-boss's graceful stop does all three. The caller bounds it.
763
+ */
764
+ export async function stopQueues(): Promise<void> {
765
+ const open = [...connections.values()];
766
+ connections.clear();
767
+ await Promise.all(open.map((connection) => connection.close()));
768
+ }
769
+ `;
770
+ await writeFile(queuesPath, content);
771
+ return queuesPath;
772
+ }
773
+ };
774
+ //#endregion
775
+ //#region src/generators/WorkerGenerator.ts
776
+ /**
777
+ * A worker whose topic subscribers would have to be pushed to over HTTP.
778
+ *
779
+ * On SNS a subscriber is an HTTP endpoint SNS delivers to, and a worker's
780
+ * process serves nothing but its health check. A server target's broker is
781
+ * pg-boss, where each subscriber polls a queue of its own, so this is only
782
+ * reached by building server images for a project that deploys to AWS — where
783
+ * a subscriber is a Lambda instead.
784
+ */
785
+ var WorkerSubscribersNeedPush = class extends GkmError {
786
+ worker;
787
+ subscribers;
788
+ constructor(worker, subscribers) {
789
+ 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.`);
790
+ this.worker = worker;
791
+ this.subscribers = subscribers;
792
+ this.name = "WorkerSubscribersNeedPush";
793
+ }
794
+ };
795
+ /** Where a worker's generated entry lives, under an app's `.gkm/server`. */
796
+ function workerEntryDir(serverDir, workerId) {
797
+ return join(serverDir, "workers", appKey(workerId));
798
+ }
799
+ /** The file a worker's bundle is written to, beside the server's. */
800
+ function workerBundleName(workerId) {
801
+ return `worker-${appKey(workerId)}.mjs`;
802
+ }
803
+ /**
804
+ * A Worker's production entry: the process that runs its crons, its queue
805
+ * consumers and its topic subscribers, and answers nothing but a health check.
806
+ *
807
+ * It is the server's runtime without the server. The `crons.ts`, `queues.ts`
808
+ * and `subscribers.ts` it starts are the files `gkm dev` starts — written by
809
+ * the same generators, given only this worker's constructs — so a consumer
810
+ * runs the same code in development and in the image. What it adds is the
811
+ * process around them: drivers, a health check that says when a consumer or
812
+ * the broker is down, and a shutdown that drains.
813
+ */
814
+ var WorkerGenerator = class {
815
+ generators;
816
+ constructor(generators = {
817
+ cron: new CronGenerator(),
818
+ queue: new QueueGenerator(),
819
+ subscriber: new SubscriberGenerator()
820
+ }) {
821
+ this.generators = generators;
822
+ }
823
+ /** Write the worker's files; returns its entry, `worker.ts`. */
824
+ async build(input) {
825
+ const { context, workerId, outputDir } = input;
826
+ if (input.subscribers.length > 0 && context.eventsBackends?.includes("sns")) throw new WorkerSubscribersNeedPush(workerId, input.subscribers.map(({ key }) => key));
827
+ await mkdir(outputDir, { recursive: true });
828
+ const options = { target: "server" };
829
+ await Promise.all([
830
+ this.generators.cron.build(context, input.crons, outputDir, options),
831
+ this.generators.queue.build(context, input.queues, outputDir, options),
832
+ this.generators.subscriber.build(context, input.subscribers, outputDir, options)
833
+ ]);
834
+ await writeFile(join(outputDir, "app.ts"), workerApp(context, workerId, outputDir));
835
+ await writeTelemetryModule(outputDir, input.telemetry);
836
+ const entry = join(outputDir, "worker.ts");
837
+ await writeFile(entry, workerEntry(context.production?.healthCheck ?? "/health"));
838
+ return entry;
839
+ }
840
+ };
841
+ /**
842
+ * `app.ts`: the worker's runtime — its logger and environment parser off the
843
+ * Worker construct, the drivers its target needs, and a `startWorker` that
844
+ * starts every cron, consumer and subscriber it owns.
845
+ */
846
+ function workerApp(context, workerId, outputDir) {
847
+ const runtime = runtimeFor(context, outputDir, workerId);
848
+ return `/**
849
+ * Generated worker runtime for ${workerId}.
850
+ * Generated by 'gkm build --production'.
851
+ */
852
+ import { setupCrons, cronsStatus, stopCrons } from './crons.js';
853
+ import { setupQueues, queuesStatus, stopQueues } from './queues.js';
854
+ import { setupSubscribers, subscribersStatus, stopSubscribers } from './subscribers.js';
855
+ ${runtime.imports}
856
+ ${context.storageDrivers?.imports ?? ""}
857
+
858
+ ${runtime.bindings}
859
+
860
+ ${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.
861
+ ${context.storageDrivers.setup}
862
+ ` : ""}
863
+ // Who this worker is to Postgres: application_name on every connection.
864
+ process.env.GKM_APP_NAME ??= ${JSON.stringify(workerId)};
865
+
866
+ export { logger };
867
+
868
+ /** What the health check answers, and why. */
869
+ export interface WorkerHealth {
870
+ healthy: boolean;
871
+ /** The crons, queues and subscribers that could not start. */
872
+ failed: string[];
873
+ /** How many broker connections did not answer. */
874
+ down: number;
875
+ }
876
+
877
+ /** Whether one broker connection answers: open, and — on pg-boss — a query. */
878
+ async function answers(connection: unknown): Promise<boolean> {
879
+ const c = connection as {
880
+ isConnected?: () => boolean;
881
+ instance?: { getDb?: () => { executeSql: (sql: string) => Promise<unknown> } };
882
+ };
883
+ if (c.isConnected && !c.isConnected()) return false;
884
+ const db = c.instance?.getDb?.();
885
+ if (!db) return true;
886
+ try {
887
+ await Promise.race([
888
+ db.executeSql('select 1'),
889
+ new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 2000).unref()),
890
+ ]);
891
+ return true;
892
+ } catch {
893
+ return false;
894
+ }
895
+ }
896
+
897
+ /** A request to a route this worker mounted, and what it answered. */
898
+ export interface WorkerRequest {
899
+ headers: Record<string, string | string[] | undefined>;
900
+ body: string;
901
+ /** The request's query — Mailpit's webhook carries its token there. */
902
+ query?: URLSearchParams;
903
+ }
904
+ export interface WorkerAnswer {
905
+ status: number;
906
+ body: unknown;
907
+ }
908
+
909
+ // The routes something pushes to: an SNS subscriber's, and the one a local
910
+ // object store posts a bucket's events to. Mounted by the subscribers, served
911
+ // by the entry's HTTP server beside the health check.
912
+ const routes = new Map<string, (c: any) => unknown>();
913
+ const app = {
914
+ post: (path: string, handler: (c: any) => unknown) => {
915
+ routes.set(path, handler);
916
+ },
917
+ };
918
+
919
+ /** Run one mounted route, as the subscribers' handlers expect to be called. */
920
+ async function route(path: string, request: WorkerRequest): Promise<WorkerAnswer | undefined> {
921
+ const handler = routes.get(path);
922
+ if (!handler) return undefined;
923
+ let answer: WorkerAnswer | undefined;
924
+ const c = {
925
+ req: {
926
+ text: async () => request.body,
927
+ query: (name: string) => request.query?.get(name) ?? undefined,
928
+ header: (name: string) => {
929
+ const value = request.headers[name.toLowerCase()];
930
+ return Array.isArray(value) ? value[0] : value;
931
+ },
932
+ },
933
+ json: (body: unknown, status = 200) => {
934
+ answer = { status, body };
935
+ return answer;
936
+ },
937
+ };
938
+ await handler(c);
939
+ return answer ?? { status: 204, body: null };
940
+ }
941
+
942
+ /** Start everything this worker runs. */
943
+ export async function startWorker(): Promise<{
944
+ health: () => Promise<WorkerHealth>;
945
+ stop: () => Promise<void>;
946
+ route: typeof route;
947
+ /** Subscribe the pushed routes, once the server answers on \`port\`. */
948
+ subscribeForPush: (port: number) => Promise<void>;
949
+ }> {
950
+ const subscribeForPush = await setupSubscribers(app, envParser, logger).catch((error) => {
951
+ logger.error({ err: error }, 'Failed to start subscribers');
952
+ return async (_port: number) => {};
953
+ });
954
+ await setupQueues(envParser, logger).catch((error) => {
955
+ logger.error({ err: error }, 'Failed to start queue consumers');
956
+ });
957
+ await setupCrons(envParser, logger).catch((error) => {
958
+ logger.error({ err: error }, 'Failed to schedule crons');
959
+ });
960
+
961
+ const statuses = () => [subscribersStatus(), queuesStatus(), cronsStatus()];
962
+
963
+ return {
964
+ route,
965
+ subscribeForPush,
966
+ async health() {
967
+ const all = statuses();
968
+ const failed = all.flatMap((s) => s.failed);
969
+ const alive = await Promise.all(
970
+ all.flatMap((s) => s.connections as unknown[]).map(answers),
971
+ );
972
+ const down = alive.filter((ok) => !ok).length;
973
+ return { healthy: failed.length === 0 && down === 0, failed, down };
974
+ },
975
+ // Each stops pulling, waits for what it has in flight, and closes its
976
+ // broker connection. Together, so one slow handler does not hold the
977
+ // others' connections open.
978
+ async stop() {
979
+ await Promise.all([stopSubscribers(), stopQueues(), stopCrons()]);
980
+ },
981
+ };
982
+ }
983
+ `;
984
+ }
985
+ /**
986
+ * `worker.ts`: the process. Health first, so the container answers while the
987
+ * consumers connect; then the worker; then a shutdown that drains.
988
+ */
989
+ function workerEntry(healthCheck) {
990
+ return `#!/usr/bin/env node
991
+ /**
992
+ * Production worker entry point.
993
+ * Generated by 'gkm build --production'.
994
+ *
995
+ * Runs this worker's crons, queue consumers and topic subscribers, and serves
996
+ * its health check: ${healthCheck}, on PORT — 200 when every consumer started
997
+ * and every broker connection answers, 503 otherwise. Beside it, on the same
998
+ * port, the POST routes its subscribers mounted: where a local object store
999
+ * posts a bucket's events.
1000
+ *
1001
+ * On SIGTERM it stops pulling messages and scheduling crons, lets the handlers
1002
+ * in flight finish, closes its broker connections and database pools, and
1003
+ * exits 0 — or 1, at GKM_SHUTDOWN_TIMEOUT_MS (8s by default, under Docker's
1004
+ * 10s stop timeout).
1005
+ */
1006
+ import { createServer } from 'node:http';
1007
+ import { runShutdownHooks } from '@geekmidas/constructs';
1008
+
1009
+ ${startTelemetryCode([healthCheck])}
1010
+ const { startWorker, logger } = await import('./app.js');
1011
+
1012
+ const port = Number(process.env.PORT) || 3000;
1013
+
1014
+ let worker: Awaited<ReturnType<typeof startWorker>> | undefined;
1015
+ let stopping = false;
1016
+
1017
+ const server = createServer((req, res) => {
1018
+ // Parsed once: the path routes, the query goes to the route.
1019
+ const url = new URL(req.url ?? '/', 'http://localhost');
1020
+ const path = url.pathname;
1021
+ const answer = (status: number, body: unknown) => {
1022
+ res.writeHead(status, { 'content-type': 'application/json' });
1023
+ res.end(JSON.stringify(body));
1024
+ };
1025
+
1026
+ // A route a subscriber mounted: what SNS pushes to, or what a local object
1027
+ // store posts a bucket's events to. Refused while starting or stopping, so
1028
+ // the sender keeps the message and sends it again.
1029
+ if (req.method === 'POST') {
1030
+ let body = '';
1031
+ req.setEncoding('utf8');
1032
+ req.on('data', (chunk) => {
1033
+ body += chunk;
1034
+ });
1035
+ req.on('end', () => {
1036
+ if (stopping) return answer(503, { status: 'stopping' });
1037
+ if (!worker) return answer(503, { status: 'starting' });
1038
+ worker.route(path, { headers: req.headers, body, query: url.searchParams }).then(
1039
+ (routed) => (routed ? answer(routed.status, routed.body) : answer(404, { status: 'not found' })),
1040
+ (error) => {
1041
+ logger.error({ err: error, path }, 'Route failed');
1042
+ answer(500, { status: 'failed' });
1043
+ },
1044
+ );
1045
+ });
1046
+ return;
1047
+ }
1048
+
1049
+ if (path !== ${JSON.stringify(healthCheck)} || (req.method !== 'GET' && req.method !== 'HEAD')) {
1050
+ res.writeHead(404).end();
1051
+ return;
1052
+ }
1053
+ if (stopping) return answer(503, { status: 'stopping' });
1054
+ if (!worker) return answer(503, { status: 'starting' });
1055
+ worker.health().then(
1056
+ (health) => answer(health.healthy ? 200 : 503, { status: health.healthy ? 'ok' : 'unhealthy', ...health }),
1057
+ (error) => answer(503, { status: 'unhealthy', error: String(error) }),
1058
+ );
1059
+ });
1060
+ server.listen(port);
1061
+
1062
+ const shutdown = async () => {
1063
+ if (stopping) return;
1064
+ stopping = true;
1065
+ const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;
1066
+ logger.info({ deadline }, 'Graceful shutdown initiated');
1067
+ setTimeout(() => {
1068
+ logger.warn({ deadline }, 'Shutdown deadline reached, exiting');
1069
+ process.exit(1);
1070
+ }, deadline).unref();
1071
+
1072
+ // Nothing new is pulled or scheduled; what is in flight finishes.
1073
+ await worker?.stop().catch((error) => logger.error({ err: error }, 'Failed to stop the worker'));
1074
+ // Then what the handlers used: database pools.
1075
+ await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));
1076
+ server.close();
1077
+ logger.info('Worker stopped');
1078
+ process.exit(0);
1079
+ };
1080
+
1081
+ process.on('SIGTERM', shutdown);
1082
+ process.on('SIGINT', shutdown);
1083
+
1084
+ worker = await startWorker();
1085
+ logger.info({ port }, 'Worker started');
1086
+ await worker.subscribeForPush(port).catch((error) => {
1087
+ logger.error({ err: error }, 'Failed to subscribe for push');
1088
+ });
1089
+ `;
1090
+ }
1091
+ //#endregion
1092
+ //#region src/docker/index.ts
1093
+ const logger = output;
1094
+ /** `docker build` failed; what docker printed above says why. */
1095
+ var DockerBuildFailed = class extends Error {
1096
+ imageRef;
1097
+ constructor(imageRef, cause) {
1098
+ super(`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
1099
+ this.imageRef = imageRef;
1100
+ this.name = "DockerBuildFailed";
1101
+ }
1102
+ };
1103
+ /** `docker push` failed — usually the registry login or its permissions. */
1104
+ var DockerPushFailed = class extends Error {
1105
+ imageRef;
1106
+ constructor(imageRef, cause) {
1107
+ super(`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
1108
+ this.imageRef = imageRef;
1109
+ this.name = "DockerPushFailed";
1110
+ }
1111
+ };
1112
+ /** `gkm docker --push` was asked for with nowhere to push to. */
1113
+ var PushNeedsRegistry = class extends GkmError {
1114
+ imageName;
1115
+ constructor(imageName) {
1116
+ super(`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`);
1117
+ this.imageName = imageName;
1118
+ this.name = "PushNeedsRegistry";
1119
+ }
1120
+ };
1121
+ /**
1122
+ * Docker command implementation: one Dockerfile per deployable app, each
1123
+ * building its image inside Docker from a turbo-pruned slice of the build
1124
+ * root — nothing is built on the host — plus the build root's
1125
+ * `.dockerignore` and `docker-compose.constructs.yml`.
1126
+ */
1127
+ async function dockerCommand(options) {
1128
+ const cwd = options.cwd ?? process.cwd();
1129
+ const loaded = await loadWorkspaceConfig(cwd);
1130
+ const names = loaded.type === "single" ? Object.fromEntries(Object.keys(loaded.workspace.apps).map((name) => [name, resolveDockerConfig(loaded.raw).imageName])) : {};
1131
+ const result = await workspaceDockerCommand(loaded.workspace, loaded.manifest, names, loaded.background, options.stage);
1132
+ if (options.build) for (const app of result.apps) await buildDockerImage(app, result.buildRoot, options);
1133
+ if (options.push) for (const app of result.apps) await pushDockerImage(app.imageName, options, result.buildRoot);
1134
+ return result;
1135
+ }
1136
+ /**
1137
+ * Build one app's image, from the build root.
1138
+ * Uses BuildKit for cache mount support
1139
+ */
1140
+ async function buildDockerImage(app, buildRoot, options) {
1141
+ const tag = options.tag ?? "latest";
1142
+ const registry = options.registry;
1143
+ const fullImageName = validateImageRef(registry ? `${registry}/${app.imageName}:${tag}` : `${app.imageName}:${tag}`);
1144
+ logger.log(`\n🐳 Building Docker image: ${fullImageName}`);
1145
+ try {
1146
+ await run("docker", [
1147
+ "build",
1148
+ `--file=${relative(buildRoot, app.dockerfile)}`,
1149
+ `--tag=${fullImageName}`,
1150
+ "."
1151
+ ], {
1152
+ cwd: buildRoot,
1153
+ env: {
1154
+ ...process.env,
1155
+ DOCKER_BUILDKIT: "1"
1156
+ }
1157
+ });
1158
+ logger.log(`✅ Docker image built: ${fullImageName}`);
1159
+ } catch (error) {
1160
+ throw new DockerBuildFailed(fullImageName, error);
1161
+ }
1162
+ }
1163
+ /**
1164
+ * Push Docker image to registry
1165
+ */
1166
+ async function pushDockerImage(imageName, options, cwd) {
1167
+ const tag = options.tag ?? "latest";
1168
+ const registry = options.registry;
1169
+ if (!registry) throw new PushNeedsRegistry(imageName);
1170
+ const fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);
1171
+ logger.log(`\n🚀 Pushing Docker image: ${fullImageName}`);
1172
+ try {
1173
+ await run("docker", ["push", fullImageName], { cwd });
1174
+ logger.log(`✅ Docker image pushed: ${fullImageName}`);
1175
+ } catch (error) {
1176
+ throw new DockerPushFailed(fullImageName, error);
1177
+ }
1178
+ }
1179
+ /**
1180
+ * Generate Dockerfiles for all apps in a workspace.
1181
+ * @internal Exported for testing
1182
+ */
1183
+ async function workspaceDockerCommand(workspace, manifest, imageNames = {}, background = {}, stage) {
1184
+ const results = [];
1185
+ const layout = imageLayout(workspace);
1186
+ logger.log(`\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);
1187
+ logger.log(` Build root: ${layout.buildRoot}`);
1188
+ logger.log(` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ""}, turbo@${layout.tools.turboVersion}`);
1189
+ for (const [appName, app] of Object.entries(workspace.apps)) {
1190
+ if (app.type === "mobile") {
1191
+ logger.log(`\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`);
1192
+ continue;
1193
+ }
1194
+ const buildType = app.entry ? "entry" : app.type;
1195
+ logger.log(`\n 📄 Generating Dockerfile for ${appName} (${buildType})`);
1196
+ const dockerfile = appDockerfile(appName, app, {
1197
+ layout,
1198
+ workspaceRoot: workspace.root,
1199
+ apps: workspace.apps,
1200
+ ...manifest ? { manifest } : {},
1201
+ workspace,
1202
+ ...stage ? { stage } : {}
1203
+ });
1204
+ const path = dockerfileOf(appName, app.path);
1205
+ const dockerfilePath = join(workspace.root, path);
1206
+ await mkdir(dirname(dockerfilePath), { recursive: true });
1207
+ await writeFile(dockerfilePath, dockerfile);
1208
+ logger.log(` Generated: ${path}`);
1209
+ results.push({
1210
+ appName,
1211
+ type: app.type,
1212
+ dockerfile: dockerfilePath,
1213
+ imageName: imageNames[appName] ?? appName
1214
+ });
1215
+ }
1216
+ for (const worker of manifest ? workerUnits(workspace, manifest, background) : []) {
1217
+ logger.log(`\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`);
1218
+ const dockerfile = workerDockerfile(worker, workspace.apps[worker.app], {
1219
+ layout,
1220
+ workspaceRoot: workspace.root
1221
+ });
1222
+ const path = workerDockerfileOf(worker.name);
1223
+ const dockerfilePath = join(workspace.root, path);
1224
+ await mkdir(dirname(dockerfilePath), { recursive: true });
1225
+ await writeFile(dockerfilePath, dockerfile);
1226
+ logger.log(` Generated: ${path}`);
1227
+ results.push({
1228
+ appName: worker.name,
1229
+ type: "backend",
1230
+ dockerfile: dockerfilePath,
1231
+ imageName: imageNames[worker.name] ?? worker.name
1232
+ });
1233
+ }
1234
+ for (const unit of manifest ? processorUnits(workspace, manifest) : []) {
1235
+ logger.log(`\n 📄 Generating Dockerfile for ${unit.name} (processors of ${unit.id}, built from ${unit.app})`);
1236
+ const dockerfile = processorDockerfile(unit, workspace.apps[unit.app], {
1237
+ layout,
1238
+ workspaceRoot: workspace.root
1239
+ });
1240
+ const path = workerDockerfileOf(unit.name);
1241
+ const dockerfilePath = join(workspace.root, path);
1242
+ await mkdir(dirname(dockerfilePath), { recursive: true });
1243
+ await writeFile(dockerfilePath, dockerfile);
1244
+ logger.log(` Generated: ${path}`);
1245
+ results.push({
1246
+ appName: unit.name,
1247
+ type: "backend",
1248
+ dockerfile: dockerfilePath,
1249
+ imageName: imageNames[unit.name] ?? unit.name
1250
+ });
1251
+ }
1252
+ const dockerignorePath = await ensureDockerignore(layout.buildRoot);
1253
+ logger.log(`\n Ensured: ${dockerignorePath}`);
1254
+ const composePath = await writeConstructsCompose(workspace);
1255
+ logger.log(`\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`);
1256
+ logger.log(`\n📋 Build commands (from ${layout.buildRoot}):`);
1257
+ for (const result of results) {
1258
+ const icon = result.type === "backend" ? "⚙️" : result.type === "mobile" ? "📱" : "🌐";
1259
+ logger.log(` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`);
1260
+ }
1261
+ printRunInstructions(workspace);
1262
+ return {
1263
+ apps: results,
1264
+ dockerCompose: composePath,
1265
+ dockerignore: dockerignorePath,
1266
+ buildRoot: layout.buildRoot
1267
+ };
1268
+ }
1269
+ /**
1270
+ * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,
1271
+ * a backend with its own entry bundled by esbuild, or a site by its
1272
+ * framework. The one choice every builder of images makes.
1273
+ */
1274
+ function appDockerfile(appName, app, options) {
1275
+ 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);
1276
+ if (app.type === "web") return siteDockerfile(appName, app, {
1277
+ image,
1278
+ ...options.manifest ? { manifest: options.manifest } : {},
1279
+ ...options.publicUrlArgs ? { publicUrlArgs: options.publicUrlArgs } : {}
1280
+ });
1281
+ if (app.entry) return generateEntryDockerfile({
1282
+ ...image,
1283
+ entry: app.entry,
1284
+ healthCheckPath: "/health"
1285
+ });
1286
+ return generateBackendDockerfile({
1287
+ ...image,
1288
+ healthCheckPath: "/health",
1289
+ ...options.cache ? { cache: options.cache } : {}
1290
+ });
1291
+ }
1292
+ /** Where `gkm docker` writes a worker's Dockerfile. */
1293
+ function workerDockerfileOf(worker) {
1294
+ return `.gkm/docker/Dockerfile.${worker}`;
1295
+ }
1296
+ /**
1297
+ * A Worker's Dockerfile: its host app's build, and the worker's bundle as the
1298
+ * runner — see `generateWorkerDockerfile`.
1299
+ */
1300
+ function workerDockerfile(worker, host, options) {
1301
+ const image = appImageOptions(options.layout, worker.app, host, options.workspaceRoot);
1302
+ return generateWorkerDockerfile({
1303
+ ...image,
1304
+ imageName: worker.name,
1305
+ port: WORKER_PORT,
1306
+ worker: worker.id,
1307
+ bundle: workerBundleName(worker.id),
1308
+ healthCheckPath: "/health",
1309
+ ...options.cache ? { cache: options.cache } : {}
1310
+ });
1311
+ }
1312
+ /**
1313
+ * A file server's processor unit's Dockerfile: its host app's build, and the
1314
+ * unit's bundle as the runner, with its processors' native packages
1315
+ * installed beside it — see `generateProcessorDockerfile`.
1316
+ */
1317
+ function processorDockerfile(unit, host, options) {
1318
+ const image = appImageOptions(options.layout, unit.app, host, options.workspaceRoot);
1319
+ return generateProcessorDockerfile({
1320
+ ...image,
1321
+ imageName: unit.name,
1322
+ port: PROCESSOR_PORT,
1323
+ fileServer: unit.id,
1324
+ bundle: processorBundleName(unit.id),
1325
+ healthCheckPath: "/health",
1326
+ ...options.cache ? { cache: options.cache } : {}
1327
+ });
1328
+ }
1329
+ /**
1330
+ * A site's Dockerfile, with an `ARG` for every key its bundler inlines.
1331
+ *
1332
+ * The keys come from the site's declaration where there is one — every
1333
+ * public key its edges give it, `VITE_UPLOADS_URL` included — and an
1334
+ * `ARG` the Dockerfile does not declare is a build argument the build drops,
1335
+ * leaving the bundle with an empty URL.
1336
+ */
1337
+ function siteDockerfile(appName, app, options) {
1338
+ const declared = options.manifest ? Object.entries(options.manifest).find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1] : void 0;
1339
+ const publicUrlArgs = options.publicUrlArgs ?? (declared?.kind === "site" && options.manifest ? [
1340
+ providedKeyFor(declared.id, declared.kind, "url"),
1341
+ ...Object.keys(publicEnvFor(declared, options.manifest)),
1342
+ ...imageOriginSources(declared, options.manifest).length > 0 ? [`${PUBLIC_PREFIX[declared.variant]}${IMAGE_ORIGINS_KEY}`] : []
1343
+ ] : getPublicUrlArgNames(app));
1344
+ const webOpts = {
1345
+ ...options.image,
1346
+ publicUrlArgs,
1347
+ ...declared?.kind === "site" && declared.prerender === "stage" ? { prerender: true } : {}
1348
+ };
1349
+ switch (app.framework) {
1350
+ case "vite": return generateViteStaticDockerfile(webOpts);
1351
+ case "tanstack-start":
1352
+ case "remix": return generateNodeWebDockerfile(webOpts);
1353
+ default: return generateNextjsDockerfile(webOpts);
1354
+ }
1355
+ }
1356
+ /**
1357
+ * What a build root's `.dockerignore` must leave out of every image's
1358
+ * context: dependencies installed for another platform, anything built on the
1359
+ * host (every image builds from source), git, and gkm's own output —
1360
+ * `.gkm/compose`'s env files hold a stage's secrets.
1361
+ */
1362
+ const REQUIRED_IGNORES = [
1363
+ "**/node_modules",
1364
+ ".git",
1365
+ "**/dist",
1366
+ "**/.next",
1367
+ "**/.turbo",
1368
+ "**/.gkm",
1369
+ "**/.gkm/compose"
1370
+ ];
1371
+ /**
1372
+ * Make sure the build root's `.dockerignore` leaves out what no image may
1373
+ * hold: written whole where there is none, and each missing line appended to
1374
+ * one the project keeps.
1375
+ */
1376
+ async function ensureDockerignore(buildRoot) {
1377
+ const path = join(buildRoot, ".dockerignore");
1378
+ if (!existsSync(path)) {
1379
+ await writeFile(path, generateDockerignore());
1380
+ return path;
1381
+ }
1382
+ const current = await readFile(path, "utf-8");
1383
+ const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
1384
+ const missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));
1385
+ if (missing.length === 0) return path;
1386
+ 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`);
1387
+ return path;
1388
+ }
1389
+ /**
1390
+ * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with
1391
+ * the apps beside the containers their constructs derive.
1392
+ *
1393
+ * Through reconcile rather than a second generator, so what `gkm docker`
1394
+ * describes and what `gkm dev` runs cannot disagree. Nothing is started.
1395
+ */
1396
+ async function writeConstructsCompose(workspace) {
1397
+ await reconcileWorkspace(workspace, {
1398
+ stage: workspace.stages.local,
1399
+ start: false
1400
+ });
1401
+ logger.log(` Generated: ${COMPOSE_PATH} (project root)`);
1402
+ return join(workspace.root, COMPOSE_PATH);
1403
+ }
1404
+ function printRunInstructions(workspace) {
1405
+ const project = existsSync(join(workspace.root, "docker-compose.yml")) ? " -f docker-compose.yml" : "";
1406
+ logger.log("\n📋 Run everything (the apps sit behind the \"apps\" profile):");
1407
+ logger.log(" gkm setup # starts the containers and creates what they hold");
1408
+ logger.log(` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`);
1409
+ }
1410
+ //#endregion
1411
+ export { processorInfo as _, ensureDockerignore as a, 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, validateImageRef as v };
1412
+
1413
+ //# sourceMappingURL=docker-C27YUUMQ.mjs.map