@geekmidas/cli 10.0.0-alpha.12 → 10.0.0-alpha.120

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 (517) hide show
  1. package/README.md +310 -377
  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-BDa6pPgE.cjs +1090 -0
  7. package/dist/EndpointGenerator-BDa6pPgE.cjs.map +1 -0
  8. package/dist/EndpointGenerator-CP_z_E3e.mjs +1031 -0
  9. package/dist/EndpointGenerator-CP_z_E3e.mjs.map +1 -0
  10. package/dist/GoDaddyProvider-3C8U_tVu.cjs +388 -0
  11. package/dist/GoDaddyProvider-3C8U_tVu.cjs.map +1 -0
  12. package/dist/GoDaddyProvider-D0MQoOM4.mjs +388 -0
  13. package/dist/GoDaddyProvider-D0MQoOM4.mjs.map +1 -0
  14. package/dist/{HostingerProvider-BcyFRbqV.mjs → HostingerProvider-BNpS9aRJ.mjs} +29 -25
  15. package/dist/HostingerProvider-BNpS9aRJ.mjs.map +1 -0
  16. package/dist/{HostingerProvider-BOvsgATO.cjs → HostingerProvider-DR1iws1P.cjs} +29 -25
  17. package/dist/HostingerProvider-DR1iws1P.cjs.map +1 -0
  18. package/dist/LegacyStateStore-CRi7TosX.mjs +124 -0
  19. package/dist/LegacyStateStore-CRi7TosX.mjs.map +1 -0
  20. package/dist/LegacyStateStore-DHsoQGOo.cjs +124 -0
  21. package/dist/LegacyStateStore-DHsoQGOo.cjs.map +1 -0
  22. package/dist/LocalStateStore-BQXTkeoS.cjs +178 -0
  23. package/dist/LocalStateStore-BQXTkeoS.cjs.map +1 -0
  24. package/dist/LocalStateStore-Dkth0jXX.mjs +167 -0
  25. package/dist/LocalStateStore-Dkth0jXX.mjs.map +1 -0
  26. package/dist/OpenApiTsGenerator-CsrukCE-.mjs +536 -0
  27. package/dist/OpenApiTsGenerator-CsrukCE-.mjs.map +1 -0
  28. package/dist/OpenApiTsGenerator-FNhY7Ssz.cjs +541 -0
  29. package/dist/OpenApiTsGenerator-FNhY7Ssz.cjs.map +1 -0
  30. package/dist/{Route53Provider-CH9XH7bz.cjs → Route53Provider-Bllus2NR.cjs} +21 -22
  31. package/dist/Route53Provider-Bllus2NR.cjs.map +1 -0
  32. package/dist/{Route53Provider-C0xmer8U.mjs → Route53Provider-QXxjkZO1.mjs} +13 -13
  33. package/dist/Route53Provider-QXxjkZO1.mjs.map +1 -0
  34. package/dist/S3StateStore-DGKZgyKz.cjs +222 -0
  35. package/dist/S3StateStore-DGKZgyKz.cjs.map +1 -0
  36. package/dist/S3StateStore-pZZnLLBd.mjs +223 -0
  37. package/dist/S3StateStore-pZZnLLBd.mjs.map +1 -0
  38. package/dist/SSMStateStore-CZRMERDA.mjs +205 -0
  39. package/dist/SSMStateStore-CZRMERDA.mjs.map +1 -0
  40. package/dist/SSMStateStore-DzkyjQ5D.cjs +204 -0
  41. package/dist/SSMStateStore-DzkyjQ5D.cjs.map +1 -0
  42. package/dist/SubscriberGenerator-C8CPxrCK.cjs +592 -0
  43. package/dist/SubscriberGenerator-C8CPxrCK.cjs.map +1 -0
  44. package/dist/SubscriberGenerator-y3pncae_.mjs +533 -0
  45. package/dist/SubscriberGenerator-y3pncae_.mjs.map +1 -0
  46. package/dist/add-C0kXOsWS.mjs +717 -0
  47. package/dist/add-C0kXOsWS.mjs.map +1 -0
  48. package/dist/add-Df8cmz0H.cjs +719 -0
  49. package/dist/add-Df8cmz0H.cjs.map +1 -0
  50. package/dist/appPorts-BoXMwolc.mjs +249 -0
  51. package/dist/appPorts-BoXMwolc.mjs.map +1 -0
  52. package/dist/appPorts-IW-OZmRi.cjs +296 -0
  53. package/dist/appPorts-IW-OZmRi.cjs.map +1 -0
  54. package/dist/aws-8QQ8n-t6.mjs +89 -0
  55. package/dist/aws-8QQ8n-t6.mjs.map +1 -0
  56. package/dist/aws-DY9NqQIT.cjs +100 -0
  57. package/dist/aws-DY9NqQIT.cjs.map +1 -0
  58. package/dist/awsStore-Bx5nCFnS.mjs +121 -0
  59. package/dist/awsStore-Bx5nCFnS.mjs.map +1 -0
  60. package/dist/awsStore-u3ehhMoY.cjs +138 -0
  61. package/dist/awsStore-u3ehhMoY.cjs.map +1 -0
  62. package/dist/{backup-provisioner-DXXg6FIL.mjs → backup-provisioner-C8DnCmxK.mjs} +11 -8
  63. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  64. package/dist/{backup-provisioner-cE2PuCTb.cjs → backup-provisioner-oDEsPj02.cjs} +22 -20
  65. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  66. package/dist/backups/runner.cjs +519 -0
  67. package/dist/backups/runner.cjs.map +1 -0
  68. package/dist/backups/runner.d.cts +102 -0
  69. package/dist/backups/runner.d.cts.map +1 -0
  70. package/dist/backups/runner.d.mts +102 -0
  71. package/dist/backups/runner.d.mts.map +1 -0
  72. package/dist/backups/runner.mjs +506 -0
  73. package/dist/backups/runner.mjs.map +1 -0
  74. package/dist/{bundler-Bux2iF-v.mjs → bundler-B-I4Du99.mjs} +35 -16
  75. package/dist/bundler-B-I4Du99.mjs.map +1 -0
  76. package/dist/{bundler-BMekgx7a.cjs → bundler-Dx_grUmc.cjs} +37 -19
  77. package/dist/bundler-Dx_grUmc.cjs.map +1 -0
  78. package/dist/cli-Cd9exatJ.cjs +71 -0
  79. package/dist/cli-Cd9exatJ.cjs.map +1 -0
  80. package/dist/cli-DL7GxGAe.mjs +71 -0
  81. package/dist/cli-DL7GxGAe.mjs.map +1 -0
  82. package/dist/compose-C43c03WZ.mjs +3284 -0
  83. package/dist/compose-C43c03WZ.mjs.map +1 -0
  84. package/dist/compose-Mdgea4Yt.cjs +3427 -0
  85. package/dist/compose-Mdgea4Yt.cjs.map +1 -0
  86. package/dist/config-D48erO2j.d.mts +269 -0
  87. package/dist/config-D48erO2j.d.mts.map +1 -0
  88. package/dist/config-DHDtsQrB.d.cts +269 -0
  89. package/dist/config-DHDtsQrB.d.cts.map +1 -0
  90. package/dist/config.cjs +421 -11
  91. package/dist/config.cjs.map +1 -0
  92. package/dist/config.d.cts +4 -120
  93. package/dist/config.d.mts +4 -120
  94. package/dist/config.mjs +405 -4
  95. package/dist/config.mjs.map +1 -0
  96. package/dist/credentialSchemas-B67WJOOm.cjs +272 -0
  97. package/dist/credentialSchemas-B67WJOOm.cjs.map +1 -0
  98. package/dist/credentialSchemas-DDOLRCLF.mjs +237 -0
  99. package/dist/credentialSchemas-DDOLRCLF.mjs.map +1 -0
  100. package/dist/credentials-B5N5yKk6.mjs +267 -0
  101. package/dist/credentials-B5N5yKk6.mjs.map +1 -0
  102. package/dist/credentials-Zqr3QQYB.cjs +350 -0
  103. package/dist/credentials-Zqr3QQYB.cjs.map +1 -0
  104. package/dist/databases-BPOgTn1u.mjs +522 -0
  105. package/dist/databases-BPOgTn1u.mjs.map +1 -0
  106. package/dist/databases-fOaoBInm.cjs +625 -0
  107. package/dist/databases-fOaoBInm.cjs.map +1 -0
  108. package/dist/define-6poNqm5O.mjs +106 -0
  109. package/dist/define-6poNqm5O.mjs.map +1 -0
  110. package/dist/define-crmMcXFS.cjs +153 -0
  111. package/dist/define-crmMcXFS.cjs.map +1 -0
  112. package/dist/deploy/public.cjs +212 -0
  113. package/dist/deploy/public.cjs.map +1 -0
  114. package/dist/deploy/public.d.cts +654 -0
  115. package/dist/deploy/public.d.cts.map +1 -0
  116. package/dist/deploy/public.d.mts +654 -0
  117. package/dist/deploy/public.d.mts.map +1 -0
  118. package/dist/deploy/public.mjs +145 -0
  119. package/dist/deploy/public.mjs.map +1 -0
  120. package/dist/deploy/sniffer-envkit-patch.cjs +18 -10
  121. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  122. package/dist/deploy/sniffer-envkit-patch.d.cts +0 -2
  123. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  124. package/dist/deploy/sniffer-envkit-patch.d.mts +0 -2
  125. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  126. package/dist/deploy/sniffer-envkit-patch.mjs +10 -2
  127. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  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 +13 -7
  135. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  136. package/dist/deploy/sniffer-hooks.d.cts +1 -2
  137. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  138. package/dist/deploy/sniffer-hooks.d.mts +1 -2
  139. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  140. package/dist/deploy/sniffer-hooks.mjs +10 -3
  141. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  142. package/dist/deploy/sniffer-loader.cjs +16 -7
  143. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  144. package/dist/deploy/sniffer-loader.d.cts +1 -1
  145. package/dist/deploy/sniffer-loader.d.mts +1 -1
  146. package/dist/deploy/sniffer-loader.mjs +14 -3
  147. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  148. package/dist/deploy/sniffer-routes-worker.cjs +11 -11
  149. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  150. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  151. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  152. package/dist/deploy/sniffer-routes-worker.mjs +4 -4
  153. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  154. package/dist/deploy/sniffer-worker.cjs +15 -6
  155. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  156. package/dist/deploy/sniffer-worker.d.cts +1 -3
  157. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  158. package/dist/deploy/sniffer-worker.d.mts +1 -3
  159. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  160. package/dist/deploy/sniffer-worker.mjs +15 -4
  161. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  162. package/dist/deploy-BMM2hx-K.cjs +2401 -0
  163. package/dist/deploy-BMM2hx-K.cjs.map +1 -0
  164. package/dist/deploy-D5YhwDng.mjs +2328 -0
  165. package/dist/deploy-D5YhwDng.mjs.map +1 -0
  166. package/dist/derive-B4vDpzgP.mjs +150 -0
  167. package/dist/derive-B4vDpzgP.mjs.map +1 -0
  168. package/dist/derive-DAbo49sm.cjs +161 -0
  169. package/dist/derive-DAbo49sm.cjs.map +1 -0
  170. package/dist/discover-C5roJuc9.mjs +560 -0
  171. package/dist/discover-C5roJuc9.mjs.map +1 -0
  172. package/dist/discover-CSW_BMWa.d.cts +125 -0
  173. package/dist/discover-CSW_BMWa.d.cts.map +1 -0
  174. package/dist/discover-DozUKs8f.cjs +639 -0
  175. package/dist/discover-DozUKs8f.cjs.map +1 -0
  176. package/dist/discover-xtT7fgWg.d.mts +125 -0
  177. package/dist/discover-xtT7fgWg.d.mts.map +1 -0
  178. package/dist/dns-BIYf20p7.cjs +1057 -0
  179. package/dist/dns-BIYf20p7.cjs.map +1 -0
  180. package/dist/dns-agf2VCdV.mjs +926 -0
  181. package/dist/dns-agf2VCdV.mjs.map +1 -0
  182. package/dist/dokploy-2p4PK6ej.mjs +38 -0
  183. package/dist/dokploy-2p4PK6ej.mjs.map +1 -0
  184. package/dist/dokploy-BANMTroy.cjs +38 -0
  185. package/dist/dokploy-BANMTroy.cjs.map +1 -0
  186. package/dist/drivers-BjGDYfnC.mjs +195 -0
  187. package/dist/drivers-BjGDYfnC.mjs.map +1 -0
  188. package/dist/drivers-DbjiYpW6.cjs +224 -0
  189. package/dist/drivers-DbjiYpW6.cjs.map +1 -0
  190. package/dist/eas-CNi16SoO.cjs +337 -0
  191. package/dist/eas-CNi16SoO.cjs.map +1 -0
  192. package/dist/eas-iT2JDHCh.mjs +334 -0
  193. package/dist/eas-iT2JDHCh.mjs.map +1 -0
  194. package/dist/{emit-CIlvnDvV.mjs → emit-C1e8qD08.mjs} +13 -26
  195. package/dist/emit-C1e8qD08.mjs.map +1 -0
  196. package/dist/{emit-CUD1BWls.cjs → emit-Dmc1nvdS.cjs} +31 -57
  197. package/dist/emit-Dmc1nvdS.cjs.map +1 -0
  198. package/dist/encryption-DkXVbyZc.mjs +89 -0
  199. package/dist/encryption-DkXVbyZc.mjs.map +1 -0
  200. package/dist/encryption-d2lLtkYx.cjs +90 -0
  201. package/dist/encryption-d2lLtkYx.cjs.map +1 -0
  202. package/dist/engine-CatKW6E-.mjs +3089 -0
  203. package/dist/engine-CatKW6E-.mjs.map +1 -0
  204. package/dist/engine-DlEHexED.cjs +3202 -0
  205. package/dist/engine-DlEHexED.cjs.map +1 -0
  206. package/dist/errors-D8Gwp5kU.mjs +23 -0
  207. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  208. package/dist/errors-DMC4Umsb.cjs +34 -0
  209. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  210. package/dist/github-BAeaC1Pl.cjs +833 -0
  211. package/dist/github-BAeaC1Pl.cjs.map +1 -0
  212. package/dist/github-DErsqKGN.mjs +832 -0
  213. package/dist/github-DErsqKGN.mjs.map +1 -0
  214. package/dist/googlePlay-BVcfFWRO.cjs +931 -0
  215. package/dist/googlePlay-BVcfFWRO.cjs.map +1 -0
  216. package/dist/googlePlay-BXJ5ZjMK.mjs +931 -0
  217. package/dist/googlePlay-BXJ5ZjMK.mjs.map +1 -0
  218. package/dist/identity-CBXr4wNi.mjs +129 -0
  219. package/dist/identity-CBXr4wNi.mjs.map +1 -0
  220. package/dist/identity-CbLfgQNT.cjs +182 -0
  221. package/dist/identity-CbLfgQNT.cjs.map +1 -0
  222. package/dist/{index-BzJ7QJ9c.d.mts → index-8OfpOtSI.d.cts} +39 -20
  223. package/dist/index-8OfpOtSI.d.cts.map +1 -0
  224. package/dist/{index-CfMjtdVC.d.cts → index-Dpji6Bxq.d.mts} +39 -20
  225. package/dist/index-Dpji6Bxq.d.mts.map +1 -0
  226. package/dist/index.cjs +14291 -11898
  227. package/dist/index.cjs.map +1 -1
  228. package/dist/index.d.cts +1 -1
  229. package/dist/index.d.mts +1 -1
  230. package/dist/index.mjs +13938 -11560
  231. package/dist/index.mjs.map +1 -1
  232. package/dist/local-BwC2v2Y8.mjs +224 -0
  233. package/dist/local-BwC2v2Y8.mjs.map +1 -0
  234. package/dist/local-DNhnkugT.cjs +241 -0
  235. package/dist/local-DNhnkugT.cjs.map +1 -0
  236. package/dist/migrate-Bb1MmGHl.mjs +181 -0
  237. package/dist/migrate-Bb1MmGHl.mjs.map +1 -0
  238. package/dist/migrate-D79GI0XM.cjs +271 -0
  239. package/dist/migrate-D79GI0XM.cjs.map +1 -0
  240. package/dist/migrate-L4a273dY.cjs +181 -0
  241. package/dist/migrate-L4a273dY.cjs.map +1 -0
  242. package/dist/migrate-s4QizIoM.mjs +266 -0
  243. package/dist/migrate-s4QizIoM.mjs.map +1 -0
  244. package/dist/openapi.cjs +214 -10
  245. package/dist/openapi.cjs.map +1 -0
  246. package/dist/openapi.d.cts +38 -17
  247. package/dist/openapi.d.cts.map +1 -1
  248. package/dist/openapi.d.mts +38 -17
  249. package/dist/openapi.d.mts.map +1 -1
  250. package/dist/openapi.mjs +208 -5
  251. package/dist/openapi.mjs.map +1 -0
  252. package/dist/projectBucket-BBbQ1lHF.cjs +263 -0
  253. package/dist/projectBucket-BBbQ1lHF.cjs.map +1 -0
  254. package/dist/projectBucket-C_DN4WzF.mjs +222 -0
  255. package/dist/projectBucket-C_DN4WzF.mjs.map +1 -0
  256. package/dist/provider-BqpjG9QM.cjs +57 -0
  257. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  258. package/dist/provider-CEOKk8NS.mjs +46 -0
  259. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  260. package/dist/publish-CcTlmJT6.mjs +123 -0
  261. package/dist/publish-CcTlmJT6.mjs.map +1 -0
  262. package/dist/publish-ydscCYsW.cjs +124 -0
  263. package/dist/publish-ydscCYsW.cjs.map +1 -0
  264. package/dist/ready-BFFP838V.cjs +404 -0
  265. package/dist/ready-BFFP838V.cjs.map +1 -0
  266. package/dist/ready-BOfogqzr.mjs +375 -0
  267. package/dist/ready-BOfogqzr.mjs.map +1 -0
  268. package/dist/reconcile/public.cjs +3 -5
  269. package/dist/reconcile/public.d.cts +11 -87
  270. package/dist/reconcile/public.d.cts.map +1 -1
  271. package/dist/reconcile/public.d.mts +11 -87
  272. package/dist/reconcile/public.d.mts.map +1 -1
  273. package/dist/reconcile/public.mjs +3 -4
  274. package/dist/{reconcile-BI0tWkwz.mjs → reconcile--I7V4Klj.mjs} +4 -7
  275. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  276. package/dist/{reconcile-Bhw5fmKu.cjs → reconcile-CuCQBa5-.cjs} +5 -8
  277. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  278. package/dist/resolve-BLp2trep.mjs +263 -0
  279. package/dist/resolve-BLp2trep.mjs.map +1 -0
  280. package/dist/resolve-BgL-brF9.cjs +316 -0
  281. package/dist/resolve-BgL-brF9.cjs.map +1 -0
  282. package/dist/rollback-2cyLXEH1.cjs +165 -0
  283. package/dist/rollback-2cyLXEH1.cjs.map +1 -0
  284. package/dist/rollback-DwqZ8zzj.mjs +136 -0
  285. package/dist/rollback-DwqZ8zzj.mjs.map +1 -0
  286. package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
  287. package/dist/{chunk-CUT6urMc.cjs → rolldown-runtime-C0BPl7ul.cjs} +23 -10
  288. package/dist/run-BJLIerMM.mjs +133 -0
  289. package/dist/run-BJLIerMM.mjs.map +1 -0
  290. package/dist/run-fVZ-rLnc.cjs +174 -0
  291. package/dist/run-fVZ-rLnc.cjs.map +1 -0
  292. package/dist/runtime-ACdfK59n.d.cts +82 -0
  293. package/dist/runtime-ACdfK59n.d.cts.map +1 -0
  294. package/dist/runtime-YyQuekxi.d.mts +82 -0
  295. package/dist/runtime-YyQuekxi.d.mts.map +1 -0
  296. package/dist/s3-CrPoA89T.cjs +215 -0
  297. package/dist/s3-CrPoA89T.cjs.map +1 -0
  298. package/dist/s3-DQXZdmCM.mjs +215 -0
  299. package/dist/s3-DQXZdmCM.mjs.map +1 -0
  300. package/dist/sandbox/config-worker.cjs +43 -0
  301. package/dist/sandbox/config-worker.cjs.map +1 -0
  302. package/dist/sandbox/config-worker.d.cts +1 -0
  303. package/dist/sandbox/config-worker.d.mts +1 -0
  304. package/dist/sandbox/config-worker.mjs +44 -0
  305. package/dist/sandbox/config-worker.mjs.map +1 -0
  306. package/dist/sandbox/credentials-worker.cjs +54 -0
  307. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  308. package/dist/sandbox/credentials-worker.d.cts +1 -0
  309. package/dist/sandbox/credentials-worker.d.mts +1 -0
  310. package/dist/sandbox/credentials-worker.mjs +55 -0
  311. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  312. package/dist/sandbox/discover-worker.cjs +50 -0
  313. package/dist/sandbox/discover-worker.cjs.map +1 -0
  314. package/dist/sandbox/discover-worker.d.cts +1 -0
  315. package/dist/sandbox/discover-worker.d.mts +1 -0
  316. package/dist/sandbox/discover-worker.mjs +51 -0
  317. package/dist/sandbox/discover-worker.mjs.map +1 -0
  318. package/dist/sandbox/migrate-worker.cjs +75 -0
  319. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  320. package/dist/sandbox/migrate-worker.d.cts +1 -0
  321. package/dist/sandbox/migrate-worker.d.mts +1 -0
  322. package/dist/sandbox/migrate-worker.mjs +76 -0
  323. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  324. package/dist/sandbox-C4g1eG31.d.mts +104 -0
  325. package/dist/sandbox-C4g1eG31.d.mts.map +1 -0
  326. package/dist/sandbox-CHv3OYXg.cjs +165 -0
  327. package/dist/sandbox-CHv3OYXg.cjs.map +1 -0
  328. package/dist/sandbox-CbVB7uOD.mjs +118 -0
  329. package/dist/sandbox-CbVB7uOD.mjs.map +1 -0
  330. package/dist/sandbox-CdKgQ3XU.d.cts +104 -0
  331. package/dist/sandbox-CdKgQ3XU.d.cts.map +1 -0
  332. package/dist/{workspace-DPV7FtAv.cjs → schemas-BCwKKA42.mjs} +958 -1816
  333. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  334. package/dist/{workspace-CtnZnWsa.mjs → schemas-BQ_v0lEX.cjs} +1048 -1626
  335. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  336. package/dist/secretsManager-CQORubp9.mjs +97 -0
  337. package/dist/secretsManager-CQORubp9.mjs.map +1 -0
  338. package/dist/secretsManager-RAGcEDX1.cjs +108 -0
  339. package/dist/secretsManager-RAGcEDX1.cjs.map +1 -0
  340. package/dist/seeds-C2w4UqVP.cjs +9347 -0
  341. package/dist/seeds-C2w4UqVP.cjs.map +1 -0
  342. package/dist/seeds-Cwtv-U9-.mjs +8350 -0
  343. package/dist/seeds-Cwtv-U9-.mjs.map +1 -0
  344. package/dist/serverSetup-CKs4K9gD.cjs +630 -0
  345. package/dist/serverSetup-CKs4K9gD.cjs.map +1 -0
  346. package/dist/serverSetup-P68H5Lal.mjs +630 -0
  347. package/dist/serverSetup-P68H5Lal.mjs.map +1 -0
  348. package/dist/sniffer-8C4q6Szd.mjs +1825 -0
  349. package/dist/sniffer-8C4q6Szd.mjs.map +1 -0
  350. package/dist/sniffer-CF7wNxMo.cjs +1998 -0
  351. package/dist/sniffer-CF7wNxMo.cjs.map +1 -0
  352. package/dist/sst-B-Uz4cvm.cjs +464 -0
  353. package/dist/sst-B-Uz4cvm.cjs.map +1 -0
  354. package/dist/sst-C1pxbFEd.mjs +441 -0
  355. package/dist/sst-C1pxbFEd.mjs.map +1 -0
  356. package/dist/stage-BvM_u2z4.mjs +302 -0
  357. package/dist/stage-BvM_u2z4.mjs.map +1 -0
  358. package/dist/stage-DEQJGW3r.cjs +313 -0
  359. package/dist/stage-DEQJGW3r.cjs.map +1 -0
  360. package/dist/stages-Cb9rqRbN.mjs +190 -0
  361. package/dist/stages-Cb9rqRbN.mjs.map +1 -0
  362. package/dist/stages-D4SnG5yl.cjs +190 -0
  363. package/dist/stages-D4SnG5yl.cjs.map +1 -0
  364. package/dist/target/public.cjs +15 -0
  365. package/dist/target/public.d.cts +28 -0
  366. package/dist/target/public.d.cts.map +1 -0
  367. package/dist/target/public.d.mts +28 -0
  368. package/dist/target/public.d.mts.map +1 -0
  369. package/dist/target/public.mjs +4 -0
  370. package/dist/terminal-CW_dWeTe.mjs +85 -0
  371. package/dist/terminal-CW_dWeTe.mjs.map +1 -0
  372. package/dist/terminal-DJlqcW_U.cjs +85 -0
  373. package/dist/terminal-DJlqcW_U.cjs.map +1 -0
  374. package/dist/types-B6UXlEkf.d.cts +7650 -0
  375. package/dist/types-B6UXlEkf.d.cts.map +1 -0
  376. package/dist/types-HqVPddRK.d.mts +7649 -0
  377. package/dist/types-HqVPddRK.d.mts.map +1 -0
  378. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  379. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  380. package/dist/utils-D_fxUqvU.mjs +156 -0
  381. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  382. package/dist/vitest.cjs +65 -0
  383. package/dist/vitest.cjs.map +1 -0
  384. package/dist/vitest.d.cts +29 -0
  385. package/dist/vitest.d.cts.map +1 -0
  386. package/dist/vitest.d.mts +29 -0
  387. package/dist/vitest.d.mts.map +1 -0
  388. package/dist/vitest.mjs +65 -0
  389. package/dist/vitest.mjs.map +1 -0
  390. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  391. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  392. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  393. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  394. package/dist/workspace/index.cjs +8 -4
  395. package/dist/workspace/index.d.cts +3 -3
  396. package/dist/workspace/index.d.mts +3 -3
  397. package/dist/workspace/index.mjs +2 -3
  398. package/dist/workspace-BwqQnool.cjs +2806 -0
  399. package/dist/workspace-BwqQnool.cjs.map +1 -0
  400. package/dist/workspace-D1QbNd55.mjs +2394 -0
  401. package/dist/workspace-D1QbNd55.mjs.map +1 -0
  402. package/package.json +54 -22
  403. package/dist/CachedStateProvider-BEBl2wQT.cjs +0 -60
  404. package/dist/CachedStateProvider-BEBl2wQT.cjs.map +0 -1
  405. package/dist/CachedStateProvider-C-8wtlto.mjs +0 -3
  406. package/dist/CachedStateProvider-Co4n5Wvs.mjs +0 -54
  407. package/dist/CachedStateProvider-Co4n5Wvs.mjs.map +0 -1
  408. package/dist/CachedStateProvider-DqhGpzsm.cjs +0 -3
  409. package/dist/HostingerProvider-BOvsgATO.cjs.map +0 -1
  410. package/dist/HostingerProvider-BcyFRbqV.mjs.map +0 -1
  411. package/dist/LocalStateProvider-Bq-0C0sg.mjs +0 -42
  412. package/dist/LocalStateProvider-Bq-0C0sg.mjs.map +0 -1
  413. package/dist/LocalStateProvider-yjXZXZDM.cjs +0 -43
  414. package/dist/LocalStateProvider-yjXZXZDM.cjs.map +0 -1
  415. package/dist/Route53Provider-C0xmer8U.mjs.map +0 -1
  416. package/dist/Route53Provider-CH9XH7bz.cjs.map +0 -1
  417. package/dist/SSMStateProvider-CXtNgPfy.cjs +0 -66
  418. package/dist/SSMStateProvider-CXtNgPfy.cjs.map +0 -1
  419. package/dist/SSMStateProvider-DOZifZfE.mjs +0 -66
  420. package/dist/SSMStateProvider-DOZifZfE.mjs.map +0 -1
  421. package/dist/backup-provisioner-DXXg6FIL.mjs.map +0 -1
  422. package/dist/backup-provisioner-cE2PuCTb.cjs.map +0 -1
  423. package/dist/bundler-BMekgx7a.cjs.map +0 -1
  424. package/dist/bundler-Bux2iF-v.mjs.map +0 -1
  425. package/dist/chunk-Duj1WY3L.mjs +0 -7
  426. package/dist/config-DTsVjKZD.mjs +0 -402
  427. package/dist/config-DTsVjKZD.mjs.map +0 -1
  428. package/dist/config-RYR9j6EF.cjs +0 -462
  429. package/dist/config-RYR9j6EF.cjs.map +0 -1
  430. package/dist/config.d.cts.map +0 -1
  431. package/dist/config.d.mts.map +0 -1
  432. package/dist/credentials-B5zRHdAl.mjs +0 -141
  433. package/dist/credentials-B5zRHdAl.mjs.map +0 -1
  434. package/dist/credentials-BapzjyV5.cjs +0 -195
  435. package/dist/credentials-BapzjyV5.cjs.map +0 -1
  436. package/dist/credentials-DQRvPz2S.cjs +0 -2769
  437. package/dist/credentials-DQRvPz2S.cjs.map +0 -1
  438. package/dist/credentials-jMJC63qs.mjs +0 -2625
  439. package/dist/credentials-jMJC63qs.mjs.map +0 -1
  440. package/dist/discover-BYHQwQqu.mjs +0 -242
  441. package/dist/discover-BYHQwQqu.mjs.map +0 -1
  442. package/dist/discover-DmW9Bscc.cjs +0 -290
  443. package/dist/discover-DmW9Bscc.cjs.map +0 -1
  444. package/dist/dokploy-api-5cK2InBm.cjs +0 -3
  445. package/dist/dokploy-api-D2Ny4Jrc.mjs +0 -3
  446. package/dist/dokploy-api-pdaBryoY.mjs +0 -706
  447. package/dist/dokploy-api-pdaBryoY.mjs.map +0 -1
  448. package/dist/dokploy-api-zqKe9lHH.cjs +0 -718
  449. package/dist/dokploy-api-zqKe9lHH.cjs.map +0 -1
  450. package/dist/emit-CIlvnDvV.mjs.map +0 -1
  451. package/dist/emit-CUD1BWls.cjs.map +0 -1
  452. package/dist/encryption-D2pL3tHH.cjs +0 -54
  453. package/dist/encryption-D2pL3tHH.cjs.map +0 -1
  454. package/dist/encryption-YDsXXi6w.mjs +0 -3
  455. package/dist/encryption-_4zwjOAR.mjs +0 -42
  456. package/dist/encryption-_4zwjOAR.mjs.map +0 -1
  457. package/dist/encryption-sQ2Oxx0d.cjs +0 -4
  458. package/dist/fullstack-secrets-B6KBHf-g.mjs +0 -87
  459. package/dist/fullstack-secrets-B6KBHf-g.mjs.map +0 -1
  460. package/dist/fullstack-secrets-DL8v0y4D.cjs +0 -99
  461. package/dist/fullstack-secrets-DL8v0y4D.cjs.map +0 -1
  462. package/dist/generator-CNzBw7g5.cjs +0 -289
  463. package/dist/generator-CNzBw7g5.cjs.map +0 -1
  464. package/dist/generator-VE2JrFlY.mjs +0 -253
  465. package/dist/generator-VE2JrFlY.mjs.map +0 -1
  466. package/dist/github-BThvbf2W.cjs +0 -197
  467. package/dist/github-BThvbf2W.cjs.map +0 -1
  468. package/dist/github-DpMZurEK.mjs +0 -196
  469. package/dist/github-DpMZurEK.mjs.map +0 -1
  470. package/dist/index-BzJ7QJ9c.d.mts.map +0 -1
  471. package/dist/index-CfMjtdVC.d.cts.map +0 -1
  472. package/dist/keystore-C9rint2E.cjs +0 -101
  473. package/dist/keystore-C9rint2E.cjs.map +0 -1
  474. package/dist/keystore-TxeYM7an.mjs +0 -83
  475. package/dist/keystore-TxeYM7an.mjs.map +0 -1
  476. package/dist/openapi-Bs3-5q_r.mjs +0 -2021
  477. package/dist/openapi-Bs3-5q_r.mjs.map +0 -1
  478. package/dist/openapi-DWLTsYLL.cjs +0 -2075
  479. package/dist/openapi-DWLTsYLL.cjs.map +0 -1
  480. package/dist/openapi-react-query-Byltvm_7.mjs +0 -167
  481. package/dist/openapi-react-query-Byltvm_7.mjs.map +0 -1
  482. package/dist/openapi-react-query-CmJ1xDbn.cjs +0 -173
  483. package/dist/openapi-react-query-CmJ1xDbn.cjs.map +0 -1
  484. package/dist/openapi-react-query.cjs +0 -4
  485. package/dist/openapi-react-query.d.cts +0 -11
  486. package/dist/openapi-react-query.d.cts.map +0 -1
  487. package/dist/openapi-react-query.d.mts +0 -11
  488. package/dist/openapi-react-query.d.mts.map +0 -1
  489. package/dist/openapi-react-query.mjs +0 -4
  490. package/dist/reconcile-BI0tWkwz.mjs.map +0 -1
  491. package/dist/reconcile-Bhw5fmKu.cjs.map +0 -1
  492. package/dist/setup-BmLoNrDX.mjs +0 -12
  493. package/dist/setup-BrR1_xGy.cjs +0 -12
  494. package/dist/setup-BsNR2LBG.cjs +0 -467
  495. package/dist/setup-BsNR2LBG.cjs.map +0 -1
  496. package/dist/setup-D5-JMknk.mjs +0 -437
  497. package/dist/setup-D5-JMknk.mjs.map +0 -1
  498. package/dist/storage-B020InPW.mjs +0 -222
  499. package/dist/storage-B020InPW.mjs.map +0 -1
  500. package/dist/storage-CSNplaJn.cjs +0 -282
  501. package/dist/storage-CSNplaJn.cjs.map +0 -1
  502. package/dist/storage-DGBzMLZa.mjs +0 -4
  503. package/dist/storage-DlVol_oj.cjs +0 -8
  504. package/dist/sync-0ILCb-1S.cjs +0 -93
  505. package/dist/sync-0ILCb-1S.cjs.map +0 -1
  506. package/dist/sync-CzHXiR9c.mjs +0 -76
  507. package/dist/sync-CzHXiR9c.mjs.map +0 -1
  508. package/dist/sync-DYENfOt4.cjs +0 -4
  509. package/dist/sync-HAau6h_R.mjs +0 -3
  510. package/dist/types-DVIx8I1N.d.mts +0 -1950
  511. package/dist/types-DVIx8I1N.d.mts.map +0 -1
  512. package/dist/types-PMP_qXRY.d.cts +0 -1950
  513. package/dist/types-PMP_qXRY.d.cts.map +0 -1
  514. package/dist/workspace-Cji6lE8E.cjs +0 -10
  515. package/dist/workspace-CkJAtRIX.mjs +0 -9
  516. package/dist/workspace-CtnZnWsa.mjs.map +0 -1
  517. package/dist/workspace-DPV7FtAv.cjs.map +0 -1
@@ -1,2769 +0,0 @@
1
- const require_chunk = require('./chunk-CUT6urMc.cjs');
2
- const require_discover = require('./discover-DmW9Bscc.cjs');
3
- const require_config = require('./config-RYR9j6EF.cjs');
4
- const require_workspace = require('./workspace-DPV7FtAv.cjs');
5
- const require_generator = require('./generator-CNzBw7g5.cjs');
6
- const require_storage = require('./storage-CSNplaJn.cjs');
7
- const node_fs = require_chunk.__toESM(require("node:fs"));
8
- const node_path = require_chunk.__toESM(require("node:path"));
9
- const __geekmidas_manifest = require_chunk.__toESM(require("@geekmidas/manifest"));
10
- const node_fs_promises = require_chunk.__toESM(require("node:fs/promises"));
11
- const node_child_process = require_chunk.__toESM(require("node:child_process"));
12
- const node_net = require_chunk.__toESM(require("node:net"));
13
- const dotenv = require_chunk.__toESM(require("dotenv"));
14
- const yaml = require_chunk.__toESM(require("yaml"));
15
- const node_crypto = require_chunk.__toESM(require("node:crypto"));
16
- const __geekmidas_db_pg_roles = require_chunk.__toESM(require("@geekmidas/db/pg/roles"));
17
- const __aws_sdk_client_s3 = require_chunk.__toESM(require("@aws-sdk/client-s3"));
18
- const pg = require_chunk.__toESM(require("pg"));
19
- const node_util = require_chunk.__toESM(require("node:util"));
20
- const __geekmidas_cache_postgres = require_chunk.__toESM(require("@geekmidas/cache/postgres"));
21
-
22
- //#region src/workspace/backends.ts
23
- /**
24
- * Which family of defaults a workspace's deploy target belongs to.
25
- *
26
- * One question, asked once: **does this target run containers the project
27
- * controls?** Dokploy and a bare server do, so a bucket or a cache can live
28
- * beside the app; AWS, Vercel and Cloudflare do not, so the default has to be
29
- * something managed. That is the whole of the distinction, and it is why
30
- * `MainProvider` is the right axis rather than the deploy target's own name —
31
- * three targets share one answer.
32
- *
33
- * An AWS deploy names no `deploy.default` at all, because it goes through SST,
34
- * which is why the absence is what selects `aws`.
35
- */
36
- function providerOf(workspace) {
37
- const target = workspace.deploy?.default;
38
- return target === "dokploy" || target === "server" ? "server" : "aws";
39
- }
40
- /**
41
- * The cache backend a target implies.
42
- *
43
- * The same answer locally and deployed: a local `gkm dev` for an AWS app still
44
- * uses the Upstash protocol, because a backend that differed between the two
45
- * would be worse than a slower one.
46
- */
47
- function cacheBackendFor(on) {
48
- return require_discover.DEFAULT_CACHE[on];
49
- }
50
- /** Where a declared bucket lives on a target. */
51
- function storageBackendFor(on) {
52
- return require_discover.DEFAULT_STORAGE[on];
53
- }
54
- /**
55
- * Which broker carries declared queues and topics on a target.
56
- *
57
- * Only consulted when something declares one; a project with no `Topic` or
58
- * `Queue` has no events at all, whatever the target.
59
- */
60
- function eventsBackendFor(on) {
61
- return require_discover.DEFAULT_EVENTS[on];
62
- }
63
-
64
- //#endregion
65
- //#region src/reconcile/containers.ts
66
- /**
67
- * What gkm knows about each container it can derive.
68
- *
69
- * Everything provider-specific about the local target lives here: the image, the
70
- * ports the image listens on, and whether its data is worth keeping. The plan
71
- * says *which* containers exist and never says any of this, which is the split
72
- * the design asks for — neutral facts from the declaration, provider detail
73
- * from here and from config.
74
- *
75
- * Shared by allocation and by the compose writer so the two cannot disagree
76
- * about how many ports a container needs.
77
- */
78
- /**
79
- * The Postgres image for a major version.
80
- *
81
- * One place that knows the tag shape, so a declared version reaches the
82
- * container without anyone restating `-alpine` beside it.
83
- */
84
- function postgresImage(version) {
85
- return `postgres:${version}-alpine`;
86
- }
87
- /**
88
- * The default image for each container.
89
- *
90
- * Pinned to a major rather than `latest` where the image publishes one, so a
91
- * rebuild does not silently move a developer's Postgres a version. Overridable
92
- * per project: a project needing `postgis/postgis` says so in config.
93
- */
94
- const DEFAULT_IMAGES = {
95
- postgres: postgresImage(__geekmidas_manifest.DEFAULT_POSTGRES_VERSION),
96
- minio: "pgsty/minio:RELEASE.2026-08-04T00-00-00Z",
97
- mailpit: "axllent/mailpit:latest",
98
- redis: "redis:8-alpine",
99
- "redis-http": "hiett/serverless-redis-http:latest",
100
- rabbitmq: "rabbitmq:4-management-alpine",
101
- localstack: "floci/floci:latest",
102
- caddy: "caddy:2-alpine"
103
- };
104
- /**
105
- * The ports each container listens on.
106
- *
107
- * The first is always the one an app connects to; the rest are consoles and
108
- * management UIs, published because a bucket or an inbox you can look at is most
109
- * of why these are real containers rather than stubs.
110
- */
111
- const PORTS = {
112
- postgres: [{
113
- key: "postgres",
114
- inside: 5432,
115
- label: "postgres"
116
- }],
117
- minio: [{
118
- key: "minio",
119
- inside: 9e3,
120
- label: "minio api"
121
- }, {
122
- key: "minio-console",
123
- inside: 9001,
124
- label: "minio console"
125
- }],
126
- mailpit: [{
127
- key: "mailpit",
128
- inside: 1025,
129
- label: "smtp"
130
- }, {
131
- key: "mailpit-web",
132
- inside: 8025,
133
- label: "mailpit inbox"
134
- }],
135
- redis: [{
136
- key: "redis",
137
- inside: 6379,
138
- label: "redis"
139
- }],
140
- "redis-http": [{
141
- key: "redis-http",
142
- inside: 80,
143
- label: "cache"
144
- }],
145
- rabbitmq: [{
146
- key: "rabbitmq",
147
- inside: 5672,
148
- label: "amqp"
149
- }, {
150
- key: "rabbitmq-management",
151
- inside: 15672,
152
- label: "rabbitmq console"
153
- }],
154
- localstack: [{
155
- key: "localstack",
156
- inside: 4566,
157
- label: "localstack"
158
- }],
159
- caddy: [{
160
- key: "caddy",
161
- inside: 443,
162
- label: "https edge"
163
- }]
164
- };
165
- /** The ports a container needs published. Empty for one gkm does not know. */
166
- function portsOf(container) {
167
- return PORTS[container] ?? [];
168
- }
169
- /** The key a container's primary port is allocated under. */
170
- function primaryPortKey(container) {
171
- return portsOf(container)[0]?.key ?? container;
172
- }
173
- /**
174
- * Every port key a set of containers needs, in a stable order.
175
- *
176
- * What allocation is handed: it assigns ports to names and knows nothing about
177
- * what listens on them.
178
- */
179
- function portKeys(containers) {
180
- return [...containers].sort().flatMap((container) => portsOf(container).map((port) => port.key));
181
- }
182
- /**
183
- * The named volume a container's data lives in.
184
- *
185
- * Mailpit deliberately has none: local mail is disposable, and an inbox that
186
- * survives days of dev is noise rather than state.
187
- */
188
- function volumeOf(container) {
189
- const volumes = {
190
- postgres: "postgres-data",
191
- minio: "minio-data",
192
- redis: "redis-data",
193
- rabbitmq: "rabbitmq-data",
194
- localstack: "localstack-data",
195
- caddy: "caddy-data"
196
- };
197
- return volumes[container];
198
- }
199
-
200
- //#endregion
201
- //#region src/reconcile/caddyfile.ts
202
- /**
203
- * The kinds the edge serves.
204
- *
205
- * Everything that owns a *public address*. Deployed, each of these has a real
206
- * hostname and a certificate, so this is what makes the local shape the same
207
- * one rather than a near-enough one — and the application is indifferent
208
- * either way, because it reads whichever address was injected and never
209
- * composes one.
210
- *
211
- * Adding a kind here is the whole of adding it to the edge.
212
- */
213
- const EDGE_KINDS = {
214
- "file-server": true,
215
- "rest-api": true,
216
- site: true
217
- };
218
- /**
219
- * How the edge reaches the host, from inside its container.
220
- *
221
- * A surface and a site are served by processes `gkm dev` starts on the host,
222
- * not by containers — so the edge has to leave Docker's network to reach them.
223
- * Docker Desktop resolves this name already; on Linux the compose definition
224
- * maps it to the host gateway.
225
- */
226
- const HOST_GATEWAY = "host.docker.internal";
227
- /**
228
- * The suffix every local host shares.
229
- *
230
- * `.localhost` rather than a made-up TLD because it resolves to loopback
231
- * without touching `/etc/hosts` — macOS and systemd-resolved both answer for
232
- * subdomains of it, and Caddy issues internal certificates for it by default.
233
- */
234
- const LOCAL_TLD = "localhost";
235
- /**
236
- * The sites a plan implies, one per file server.
237
- *
238
- * The leading label is the *server's* stage-scoped name rather than the
239
- * bucket's, which is the difference that matters: two servers over one bucket
240
- * are a legitimate arrangement — two cache behaviours, one origin — and naming
241
- * the host after the bucket would make them collide.
242
- */
243
- function sitesFor(plan, project, addresses = {}) {
244
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
245
- const sites = [];
246
- for (const resource of plan.resources) {
247
- if (!EDGE_KINDS[resource.kind]) continue;
248
- const host = hostFor(resource, project);
249
- if (resource.kind === "file-server") {
250
- const origin = resource.of ? byId.get(resource.of) : void 0;
251
- if (!origin) continue;
252
- sites.push({
253
- host,
254
- upstream: "http://minio:9000",
255
- rewrite: `/${origin.name}{uri}`
256
- });
257
- continue;
258
- }
259
- const address = addresses[resource.id];
260
- if (!address) continue;
261
- const port = portOf(address);
262
- if (!port) continue;
263
- sites.push({
264
- host,
265
- upstream: `http://${HOST_GATEWAY}:${port}`
266
- });
267
- }
268
- return sites;
269
- }
270
- /** The port a local address answers on, defaulting by scheme. */
271
- function portOf(address) {
272
- try {
273
- const { port, protocol } = new URL(address);
274
- return port || (protocol === "https:" ? "443" : "80");
275
- } catch {
276
- return void 0;
277
- }
278
- }
279
- /**
280
- * Where one file server answers, including the stage its name carries.
281
- *
282
- * The project is a label rather than a decoration: it is what keeps two
283
- * checkouts from answering on one address. Omitted when there is no project to
284
- * name, because an empty label makes `uploads..localhost` — a host nothing
285
- * resolves and no certificate can be issued for.
286
- */
287
- function hostFor(resource, project) {
288
- return [
289
- resource.name,
290
- project,
291
- LOCAL_TLD
292
- ].filter(Boolean).join(".");
293
- }
294
- /**
295
- * The static root config, which only ever imports.
296
- *
297
- * Written once and identical for every stage, because the *sites* are what
298
- * differ and they live in their own files. That split is not tidiness: one
299
- * container serves every stage — the same way one Postgres holds `orders` and
300
- * `orders_test` — so a single Caddyfile would mean `gkm test` deleting the
301
- * routes `gkm dev` is serving, and each command silently breaking the other.
302
- */
303
- function caddyfileRoot() {
304
- return `${GENERATED}
305
- {
306
- # No ACME, no public DNS: the CA is local and so are the names.
307
- local_certs
308
- auto_https disable_redirects
309
- }
310
-
311
- # One file per stage, so two stages share this edge the way they already share
312
- # one Postgres and one MinIO.
313
- import /etc/caddy/sites/*.caddy
314
- `;
315
- }
316
- /**
317
- * One stage's sites, as the file imported above.
318
- *
319
- * `rewrite` rather than a path prefix on the address: the bucket is the
320
- * origin's business, and the client asks for the key it stored.
321
- *
322
- * `header_up Host {upstream_hostport}` matters more than it looks. MinIO routes
323
- * and signs on the Host header, so forwarding the requested hostname would make
324
- * it look for a bucket named after the domain.
325
- */
326
- function toCaddyfile(sites) {
327
- if (sites.length === 0) return `${GENERATED}
328
- # No file server is declared in this stage, so it routes nothing.
329
- `;
330
- const blocks = sites.map(({ host, upstream, rewrite }) => `
331
- https://${host} {
332
- tls internal
333
-
334
- reverse_proxy ${upstream} {${rewrite ? `
335
- rewrite ${rewrite}
336
- # MinIO routes and signs on the Host header, so forwarding the requested
337
- # hostname would make it look for a bucket named after the domain.
338
- header_up Host {upstream_hostport}` : `
339
- # The application reads whatever address was injected, so it has to see
340
- # the one a caller used — that is what makes a redirect, a cookie domain
341
- # and a generated link point back here rather than at the upstream.
342
- header_up Host {host}
343
- header_up X-Forwarded-Proto {scheme}`}
344
- }
345
- }`);
346
- return `${GENERATED}${blocks.join("\n")}\n`;
347
- }
348
- const GENERATED = `# Generated by gkm from the construct manifest — do not edit.
349
- #
350
- # One host per declared file server, in front of the object store that holds its
351
- # objects. This is the shape a file server has deployed — a domain serving a
352
- # bucket — which MinIO alone cannot produce: its virtual-host mode reads the
353
- # leading label as the bucket name.
354
- #
355
- # Certificates come from Caddy's own CA. "gkm dev" and "gkm test" export its
356
- # root and point Node at it, so nothing has to be installed to use these URLs
357
- # from code; a browser needs the root trusted once.
358
- `;
359
-
360
- //#endregion
361
- //#region src/reconcile/plan.ts
362
- /**
363
- * Which container serves a kind.
364
- *
365
- * Derived kinds map to the same container as their parent — a schema tenant
366
- * lives in its parent's Postgres — so the set is deduplicated rather than
367
- * counted.
368
- */
369
- const CONTAINERS = {
370
- database: "postgres",
371
- "database-reader": "postgres",
372
- "database-schema": "postgres",
373
- objects: "minio",
374
- "file-server": "caddy",
375
- email: "mailpit"
376
- };
377
- /**
378
- * The container a cache backend needs locally.
379
- *
380
- * Each one matches the protocol its deployed form speaks, which is the property
381
- * worth having: a cache that behaves differently in the two places is worse than
382
- * a slower one.
383
- *
384
- * `db` is deliberately absent, the same way `pgboss` is absent from
385
- * `EVENT_CONTAINERS`: the cache is a table in a database the manifest already
386
- * declares, so mapping it here would start a container for a project that needs
387
- * none.
388
- */
389
- const CACHE_CONTAINERS = {
390
- upstash: "redis-http",
391
- elasticache: "redis"
392
- };
393
- /**
394
- * Kinds that resolve a value without anything running.
395
- *
396
- * A secret is the case: it has no address, so there is nothing to start and
397
- * nothing to connect to — but it still appears in the plan, because the target
398
- * still has to resolve it.
399
- */
400
- const CONTAINERLESS = {
401
- secret: true,
402
- credential: true,
403
- "rest-api": true,
404
- site: true
405
- };
406
- /**
407
- * Containers that cannot run alone.
408
- *
409
- * The one case is the cache: `serverless-redis-http` is a proxy and needs the
410
- * Redis it proxies. Kept here rather than in the compose definition so the plan
411
- * -- which is what decides what must be running -- still names everything.
412
- */
413
- const REQUIRES = { "redis-http": ["redis"] };
414
- /**
415
- * The role each kind's one key plays, where it is not a URL.
416
- *
417
- * The twin of `ProvidesByKind` in `@geekmidas/manifest`: that is what a
418
- * construct declares, this is what the local target resolves, and both derive
419
- * the key from the same `provideKey` so they cannot disagree.
420
- */
421
- const ROLES = {
422
- queue: "publisherConnectionString",
423
- topic: "publisherConnectionString",
424
- credential: "credential"
425
- };
426
- /** The kinds whose container is the events backend's rather than their own. */
427
- const EVENT_KINDS = {
428
- queue: true,
429
- topic: true
430
- };
431
- /**
432
- * Which kinds provision something *inside* their container.
433
- *
434
- * A database creates a database, a bucket creates a bucket; mail creates
435
- * nothing — Mailpit accepts whatever is sent to it and has no per-stage object
436
- * to name. Both still appear in the plan, because both still resolve a URL; the
437
- * flag is the difference between "must be running" and "must be created".
438
- */
439
- const PROVISIONS = {
440
- database: true,
441
- "database-reader": true,
442
- "database-schema": true,
443
- objects: true,
444
- cache: true,
445
- "file-server": true
446
- };
447
- /**
448
- * The container each events backend needs, where it needs one of its own.
449
- *
450
- * `pgboss` is deliberately absent rather than mapped to `postgres`: it is a
451
- * schema tenant in a database the manifest already declares, so mapping it here
452
- * would start a Postgres for a project that declared no database at all.
453
- *
454
- * This one comes from config rather than from a declaration because there are
455
- * no `topic` or `queue` kinds yet. When they land the mapping moves to
456
- * {@link CONTAINERS} keyed by kind, and this constant goes with them.
457
- */
458
- const EVENT_CONTAINERS = {
459
- sns: "localstack",
460
- rabbitmq: "rabbitmq"
461
- };
462
- /** The backend a project gets when it declares queues or topics and says nothing. */
463
- const DEFAULT_EVENTS$1 = "pgboss";
464
- /**
465
- * How a resource of each kind separates its stage suffix.
466
- *
467
- * Postgres identifiers are snake_case and a hyphen would need quoting
468
- * everywhere; buckets and queues are kebab and disallow underscores in some
469
- * providers. The suffix is the same word either way.
470
- */
471
- const SEPARATORS = {
472
- database: "_",
473
- "database-reader": "_",
474
- "database-schema": "_",
475
- objects: "-"
476
- };
477
- /**
478
- * The stage-scoped name for a resource.
479
- *
480
- * The local stage carries no suffix, so `gkm dev` keeps using `orders` and a
481
- * developer's psql history, saved connections, and muscle memory survive a
482
- * change of stage name. Every other stage is suffixed.
483
- */
484
- function resourceName(id, kind, stage, localStage) {
485
- const base = id.toLowerCase();
486
- if (stage === localStage) return base;
487
- return `${base}${SEPARATORS[kind] ?? "-"}${stage}`;
488
- }
489
- /**
490
- * The container a kind needs, or `undefined` if it needs none.
491
- *
492
- * Queues and topics have no container of their own — they live in whichever
493
- * broker the project selected, which is why the backend is an argument here
494
- * rather than a second pass that adds containers after the fact.
495
- */
496
- function containerFor(kind, events = DEFAULT_EVENTS$1, cache = require_discover.DEFAULT_CACHE.aws, derived = false, edge = true) {
497
- if (EVENT_KINDS[kind]) return EVENT_CONTAINERS[events] ?? CONTAINERS.database;
498
- if (kind === "file-server") return edge ? "caddy" : CONTAINERS.objects;
499
- if (kind === "cache") {
500
- if (derived) return CONTAINERS.database;
501
- return CACHE_CONTAINERS[cache] ?? CONTAINERS.database;
502
- }
503
- return CONTAINERS[kind];
504
- }
505
- /**
506
- * Build the plan for a manifest and stage.
507
- *
508
- * `order` is the caller's provisioning order — parents before children — which
509
- * `provisionOrder` produces from the manifest. Passing it in keeps this
510
- * function free of the traversal and makes the ordering assertable on its own.
511
- */
512
- function planFor(manifest, stage, order, options = {}) {
513
- const containers = /* @__PURE__ */ new Set();
514
- const resources = [];
515
- const events = options.events ?? DEFAULT_EVENTS$1;
516
- const cache = options.cache ?? require_discover.DEFAULT_CACHE.aws;
517
- for (const id of order) {
518
- const declaration = manifest[id];
519
- if (!declaration) continue;
520
- const container = containerFor(declaration.kind, events, cache, "of" in declaration && typeof declaration.of === "string", options.edge !== false);
521
- if (!container && !CONTAINERLESS[declaration.kind]) continue;
522
- if (container) {
523
- containers.add(container);
524
- for (const required of REQUIRES[container] ?? []) containers.add(required);
525
- }
526
- resources.push({
527
- id,
528
- kind: declaration.kind,
529
- ...container ? { container } : {},
530
- name: resourceName(id, declaration.kind, stage, options.localStage),
531
- envKey: (0, __geekmidas_manifest.providedKeyFor)(id, declaration.kind, ROLES[declaration.kind] ?? "url"),
532
- provisions: PROVISIONS[declaration.kind] === true,
533
- ...declaration.kind === "rest-api" ? { callers: (0, __geekmidas_manifest.dependentsOf)(manifest, id) } : {},
534
- ...declaration.kind === "site" ? { publicEnv: (0, __geekmidas_manifest.publicEnvFor)(declaration, manifest) } : {},
535
- ...declaration.kind === "file-server" && declaration.open?.length ? { open: declaration.open } : {},
536
- ..."of" in declaration ? { of: declaration.of } : {},
537
- ..."schema" in declaration && declaration.schema ? { schema: declaration.schema } : {},
538
- ..."version" in declaration && declaration.version ? { version: declaration.version } : {},
539
- ..."roles" in declaration && declaration.roles === false ? { roles: false } : {},
540
- ..."table" in declaration && declaration.table ? { table: declaration.table } : {}
541
- });
542
- }
543
- if (options.edge !== false && resources.some((r) => EDGE_KINDS[r.kind] === true)) containers.add("caddy");
544
- for (const extra of options.extraContainers ?? []) containers.add(extra);
545
- if (events === "pgboss" && resources.some((r) => EVENT_KINDS[r.kind]) && !resources.some((r) => r.kind === "database")) throw new PgBossNeedsDatabase(resources.filter((r) => EVENT_KINDS[r.kind]).map((r) => r.id));
546
- if (cache === "db") {
547
- const placeless = resources.filter((r) => r.kind === "cache" && !r.of);
548
- if (placeless.length > 0) {
549
- const databases = resources.filter((r) => r.kind === "database");
550
- const [only] = databases;
551
- if (!only) throw new CacheNeedsDatabase(resources.filter((r) => r.kind === "cache").map((r) => r.id));
552
- if (databases.length > 1) throw new CacheIsAmbiguous(placeless.map((r) => r.id), databases.map((r) => r.id));
553
- for (const resource of placeless) resource.of = only.id;
554
- }
555
- }
556
- return {
557
- stage,
558
- events,
559
- cache,
560
- containers: [...containers],
561
- resources
562
- };
563
- }
564
- /**
565
- * Queues or topics were declared with pg-boss and no database to hold them.
566
- *
567
- * Not a reconcile failure but a manifest one: the fix is a line of application
568
- * code either way — declare a database, or select a backend that brings its own
569
- * broker.
570
- */
571
- var CacheNeedsDatabase = class extends Error {
572
- constructor(ids) {
573
- super(`A cache backed by the database needs a declared database, and none was declared, and on this deploy target that is where a cache lives. Declare one. Caches affected: ${ids.join(", ")}.`);
574
- this.ids = ids;
575
- this.name = "CacheNeedsDatabase";
576
- }
577
- };
578
- /**
579
- * A `'db'` cache — a server target's default — in an app that declares more
580
- * than one database.
581
- *
582
- * The target says *a* database and the graph offers several, so there is no
583
- * answer to give — and the wrong kind of failure would be to pick one, since a
584
- * cache silently landing in the wrong database is a bug that surfaces as
585
- * missing rows much later. The fix is a stronger statement in application code:
586
- * `orders.cache('Sessions')` names the database, which is a fact about the
587
- * application rather than a deployment choice.
588
- */
589
- var CacheIsAmbiguous = class extends Error {
590
- constructor(ids, databases) {
591
- super(`A cache backed by the database needs to know which one, and this app declares ${databases.length}: ${databases.join(", ")}. Declare the cache from its database — e.g. ${databases[0]}.cache('Sessions') — rather than as a bare new Cache(). Caches affected: ${ids.join(", ")}.`);
592
- this.ids = ids;
593
- this.databases = databases;
594
- this.name = "CacheIsAmbiguous";
595
- }
596
- };
597
- var PgBossNeedsDatabase = class extends Error {
598
- constructor(ids) {
599
- super(`pg-boss keeps its queues in a declared database, and none was declared. Declare one: on this deploy target, events are carried by pg-boss. Queues and topics affected: ${ids.join(", ")}.`);
600
- this.ids = ids;
601
- this.name = "PgBossNeedsDatabase";
602
- }
603
- };
604
-
605
- //#endregion
606
- //#region src/reconcile/env.ts
607
- /**
608
- * The credential local containers are brought up with.
609
- *
610
- * The design's `roles: false` case — both URLs fall back to the cluster's master
611
- * credential. A deliberate downgrade, not a default: it holds until the role DDL
612
- * lands in `@geekmidas/db`, at which point the runtime role's URL replaces this
613
- * and the owner URL stops being reachable from any manifest edge.
614
- */
615
- const LOCAL_USER$2 = "geekmidas";
616
- /** The host containers are published on. */
617
- const LOCAL_HOST = "localhost";
618
- /** The region local buckets claim, so the client has one to sign with. */
619
- const LOCAL_REGION = "us-east-1";
620
- /**
621
- * The credentials the S3 client resolves for MinIO.
622
- *
623
- * An `s3://` URL deliberately carries none: deployed, the SDK reads them from
624
- * the execution role, so a URL that embedded a key would be one more thing to
625
- * rotate and one more thing to leak into a log. Locally there is no role, and
626
- * the same chain reads these — which is why they are injected beside the URL
627
- * rather than written into it.
628
- */
629
- const STORAGE_CREDENTIALS = {
630
- AWS_ACCESS_KEY_ID: LOCAL_USER$2,
631
- AWS_SECRET_ACCESS_KEY: LOCAL_USER$2,
632
- AWS_REGION: LOCAL_REGION
633
- };
634
- /** The token the local cache proxy accepts. Matches the compose definition. */
635
- const LOCAL_TOKEN$1 = "geekmidas";
636
- /** The schema pg-boss keeps its tables in, inside the declared database. */
637
- const PGBOSS_SCHEMA = "pgboss";
638
- /** The exchange every local topic and queue shares on RabbitMQ. */
639
- const RABBITMQ_EXCHANGE = "geekmidas.events";
640
- /**
641
- * Every env key a reconciled plan resolves, and its value.
642
- *
643
- * Keys come from the declaration rather than being re-derived, so what the build
644
- * publishes and what the app reads cannot drift.
645
- */
646
- function envFor(plan, options) {
647
- const env = {};
648
- const resolved = {};
649
- for (const resource of plan.resources) {
650
- const url = urlFor(resource, plan, options.ports, options.project ?? "", options.addresses);
651
- if (url) resolved[resource.id] = url;
652
- }
653
- for (const resource of plan.resources) {
654
- const url = resolved[resource.id];
655
- if (resource.kind === "rest-api") Object.assign(env, surfaceEnv(resource, url, resolved));
656
- if (url) env[resource.envKey] = url;
657
- if (isDatabase(resource.kind) && resource.roles !== false) {
658
- const owner = ownerUrl(resource, plan, options.ports, options.project ?? "");
659
- if (owner) env[(0, __geekmidas_manifest.provideKey)(resource.id, "ownerUrl")] = owner;
660
- }
661
- if (resource.kind === "email" && url) env[(0, __geekmidas_manifest.provideKey)(resource.id, "from")] = options.mailFrom ?? `noreply@${LOCAL_HOST}`;
662
- }
663
- Object.assign(env, publicEnv(plan, env));
664
- Object.assign(env, brokerEnv(plan, options.ports));
665
- if (plan.resources.some((r) => r.kind === "objects" && env[r.envKey])) Object.assign(env, STORAGE_CREDENTIALS);
666
- return env;
667
- }
668
- /**
669
- * The values a site's bundler inlines, under the names it inlines them by.
670
- *
671
- * A rename and nothing more. `API_URL` was resolved once, by the same code that
672
- * resolved it for the server; a site reads the same value under `VITE_API_URL`
673
- * because that prefix is how its bundler is told to ship it. Nothing is derived
674
- * twice, so a site and its API cannot come to disagree about where the API is.
675
- *
676
- * A source that resolved to nothing is skipped rather than written empty: an
677
- * inlined empty string is a frontend that builds and then fails at runtime
678
- * against `http:///`, where a missing variable fails at build with the name of
679
- * the thing that is missing.
680
- */
681
- function publicEnv(plan, resolved) {
682
- const env = {};
683
- for (const resource of plan.resources) for (const [key, source] of Object.entries(resource.publicEnv ?? {})) {
684
- const value = resolved[source];
685
- if (value) env[key] = value;
686
- }
687
- return env;
688
- }
689
- /**
690
- * What a surface publishes beyond its own address: who may call it, and where
691
- * a cookie set by it is readable.
692
- *
693
- * Both are read off the same list — the constructs that declared an edge to
694
- * this surface — which is why neither appears in application code. A surface
695
- * that listed its own callers would be edited every time something new called
696
- * it, and the thing being edited is already recorded in the graph.
697
- *
698
- * An empty origin list is written, and a surface with no address writes nothing
699
- * at all. The two cases look alike and are not: "nothing depends on this yet" is
700
- * a real state a target should publish, while "this surface has no address here"
701
- * means it is not running in this stage, and keys belong with the address they
702
- * describe.
703
- */
704
- function surfaceEnv(resource, url, resolved = {}) {
705
- if (!url) return {};
706
- const origins = [...new Set((resource.callers ?? []).map((caller) => resolved[caller]).filter((address) => Boolean(address)).map(originOf).filter((origin) => Boolean(origin)))].sort();
707
- const domain = (0, __geekmidas_manifest.cookieDomain)([url, ...origins]);
708
- return {
709
- [(0, __geekmidas_manifest.provideKey)(resource.id, "trustedOrigins")]: origins.join(","),
710
- ...domain ? { [(0, __geekmidas_manifest.provideKey)(resource.id, "cookieDomain")]: domain } : {}
711
- };
712
- }
713
- /** An address reduced to the origin a browser compares against. */
714
- function originOf(address) {
715
- try {
716
- return new URL(address).origin;
717
- } catch {
718
- return void 0;
719
- }
720
- }
721
- /**
722
- * The runtime role of whatever a derived node hangs off.
723
- *
724
- * A reader's parent may itself be a schema tenant, so this follows `of` by one
725
- * hop rather than assuming the cluster — the reader of a tenant reads that
726
- * tenant's schema, not the database's.
727
- */
728
- function parentRole(resource, plan) {
729
- const parent = plan.resources.find((r) => r.id === resource.of);
730
- return parent ? localRole(parent) : resource.name;
731
- }
732
- /** Whether a kind connects to Postgres and therefore has an owner role. */
733
- function isDatabase(kind) {
734
- return kind === "database" || kind === "database-schema";
735
- }
736
- /**
737
- * The URL a migrator connects with — the owner role, which can create, alter
738
- * and drop.
739
- *
740
- * Never in `provides`, which is the whole point. A handler that could reach this
741
- * could `DROP TABLE`, and the security property the role split exists for is
742
- * that it cannot: the value is injected by `gkm exec` for the migrate step and
743
- * by nothing else.
744
- */
745
- function ownerUrl(resource, plan, ports, project) {
746
- if (!resource.container) return void 0;
747
- const port = ports[primaryPortKey(resource.container)];
748
- if (port === void 0) return void 0;
749
- const owner = (0, __geekmidas_db_pg_roles.ownerRole)(localRole(resource));
750
- return postgres(port, rootDatabase(resource, plan), {
751
- user: owner,
752
- password: localRolePassword(project, plan, owner)
753
- });
754
- }
755
- /**
756
- * The shared broker keys, when anything is published or consumed.
757
- *
758
- * A queue's own key is the producer's. These two are the *connection* itself,
759
- * which locally is one broker for every queue and topic in the project: the
760
- * generated pollers open a single connection and subscribe each worker by name
761
- * on it. Deployed there is no such thing — a Lambda is handed its own event
762
- * source — so this pair exists for the local target and says so.
763
- */
764
- function brokerEnv(plan, ports) {
765
- const carrier = plan.resources.find((r) => r.kind === "queue" || r.kind === "topic");
766
- if (!carrier) return {};
767
- const publisher = urlFor(carrier, plan, ports, "");
768
- if (!publisher) return {};
769
- return {
770
- EVENT_PUBLISHER_CONNECTION_STRING: publisher,
771
- EVENT_SUBSCRIBER_CONNECTION_STRING: plan.events === "sns" ? publisher.replace(/^sns:/, "sqs:") : publisher
772
- };
773
- }
774
- /**
775
- * The URL for one planned resource.
776
- *
777
- * Every part of it comes from the resource and the port it was published on.
778
- */
779
- function urlFor(resource, plan, ports, project, addresses = {}) {
780
- if (resource.kind === "secret") return localSecret(project, plan, resource);
781
- if (resource.kind === "credential") return void 0;
782
- if (resource.kind === "rest-api" || resource.kind === "site") {
783
- const address = addresses[resource.id];
784
- const edge = plan.containers.includes("caddy") ? ports[primaryPortKey("caddy")] : void 0;
785
- return address && edge !== void 0 ? `https://${hostFor(resource, project)}:${edge}` : address;
786
- }
787
- if (!resource.container) return void 0;
788
- const port = ports[primaryPortKey(resource.container)];
789
- if (port === void 0) return void 0;
790
- switch (resource.kind) {
791
- case "database":
792
- case "database-schema":
793
- case "database-reader": {
794
- const database = rootDatabase(resource, plan);
795
- if (resource.roles === false) {
796
- const schema = schemaOf(resource, plan);
797
- return schema ? `${postgres(port, database)}?search_path=${schema}` : postgres(port, database);
798
- }
799
- const role = resource.kind === "database-reader" ? (0, __geekmidas_db_pg_roles.readerRole)(parentRole(resource, plan)) : localRole(resource);
800
- return postgres(port, database, {
801
- user: role,
802
- password: localRolePassword(project, plan, role)
803
- });
804
- }
805
- case "email": return `smtp://${LOCAL_HOST}:${port}`;
806
- case "objects": return `s3://${resource.name}?region=${LOCAL_REGION}&endpoint=http://${LOCAL_HOST}:${port}&forcePathStyle=true`;
807
- case "file-server": {
808
- const origin = plan.resources.find((r) => r.id === resource.of);
809
- if (!origin) return void 0;
810
- return plan.containers.includes("caddy") ? `https://${hostFor(resource, project)}:${port}` : `http://${LOCAL_HOST}:${port}/${origin.name}`;
811
- }
812
- case "cache":
813
- if (resource.of) {
814
- const parent = plan.resources.find((r) => r.id === resource.of);
815
- const url = parent ? urlFor(parent, plan, ports, project, addresses) : void 0;
816
- return url ? withTable(url, resource.table ?? (0, __geekmidas_manifest.cacheTable)(resource.id)) : void 0;
817
- }
818
- switch (plan.cache) {
819
- case "elasticache": return `redis://${LOCAL_HOST}:${port}`;
820
- default: return `http://:${LOCAL_TOKEN$1}@${LOCAL_HOST}:${port}`;
821
- }
822
- case "queue":
823
- case "topic": return broker(plan, port);
824
- default: return void 0;
825
- }
826
- }
827
- /**
828
- * The producer's connection string, composed from the backend the plan chose.
829
- *
830
- * The protocol is what picks the transport, so a producer never branches: the
831
- * same `.publish()` reaches pg-boss here and SQS deployed because the string it
832
- * was handed said so.
833
- */
834
- function broker(plan, port) {
835
- switch (plan.events) {
836
- case "pgboss": {
837
- const database = plan.resources.find((r) => r.kind === "database");
838
- if (!database) throw new PgBossNeedsDatabase([]);
839
- return `pgboss://${LOCAL_USER$2}:${LOCAL_USER$2}@${LOCAL_HOST}:${port}/${database.name}?schema=${PGBOSS_SCHEMA}`;
840
- }
841
- case "rabbitmq": return `rabbitmq://${LOCAL_USER$2}:${LOCAL_USER$2}@${LOCAL_HOST}:${port}?exchange=${RABBITMQ_EXCHANGE}`;
842
- case "sns": throw new UnprovisionedEventsBackend("sns");
843
- }
844
- }
845
- /** A local Postgres URL, master credential and all. */
846
- function postgres(port, database, credential = {
847
- user: LOCAL_USER$2,
848
- password: LOCAL_USER$2
849
- }) {
850
- return `postgres://${credential.user}:${credential.password}@${LOCAL_HOST}:${port}/${database}`;
851
- }
852
- /**
853
- * The role a handler connects as, for one database or tenant.
854
- *
855
- * The construct's id, lowercased and stage-scoped exactly as its database or
856
- * schema is — so `Orders` in the `test` stage connects as `orders_test`, and two
857
- * stages sharing one cluster cannot share a credential. Roles are cluster-scoped
858
- * in Postgres, which is why the suffix is not optional here the way it is for a
859
- * schema.
860
- */
861
- function localRole(resource) {
862
- return resource.name;
863
- }
864
- /**
865
- * The password for a derived local role.
866
- *
867
- * Derived rather than random, for the same reason the local secret is: a
868
- * password that changed on every `gkm dev` would lock a developer out of the
869
- * data they had a moment ago. Seeded by the project so two checkouts do not
870
- * share one, and by the stage so `test` and `development` do not.
871
- *
872
- * It is a *local* credential by construction — the cluster is on loopback and
873
- * the seed is a checkout path — and no deployed target uses this function.
874
- */
875
- function localRolePassword(project, plan, role) {
876
- return (0, node_crypto.createHash)("sha256").update(`${project}:${plan.stage}:role:${role}`).digest("base64url").slice(0, 32);
877
- }
878
- /**
879
- * A cache's address: its database's URL, carrying the table it reads.
880
- *
881
- * Appended rather than kept beside the URL as a second key, for the reason the
882
- * design gives everywhere else — an address and what it opens are one fact, and
883
- * two keys are one more thing to keep in step.
884
- */
885
- function withTable(url, table) {
886
- const parsed = new URL(url);
887
- parsed.searchParams.set("table", table);
888
- return parsed.toString();
889
- }
890
- /**
891
- * The physical database a derived resource lives in.
892
- *
893
- * Walks `of` to the top rather than reading the immediate parent, because a
894
- * reader's parent may itself be a schema tenant — two hops from the database
895
- * that actually exists.
896
- */
897
- function rootDatabase(resource, plan) {
898
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
899
- let current = resource;
900
- while (current.of) {
901
- const parent = byId.get(current.of);
902
- if (!parent) break;
903
- current = parent;
904
- }
905
- return current.name;
906
- }
907
- /** The schema a derived resource puts on its search path, if it has one. */
908
- function schemaOf(resource, plan) {
909
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
910
- let current = resource;
911
- while (current) {
912
- if (current.kind === "database-schema") return current.schema;
913
- current = current.of ? byId.get(current.of) : void 0;
914
- }
915
- return void 0;
916
- }
917
- /**
918
- * A backend whose local addresses cannot be derived yet.
919
- *
920
- * SNS and SQS are addressed by ARN, which means the topic and queue have to be
921
- * created in LocalStack before a URL can name them. Until that provisioning
922
- * lands, saying so is better than handing out a string that fails on first use.
923
- */
924
- var UnprovisionedEventsBackend = class extends Error {
925
- constructor(backend) {
926
- super(`The local target cannot derive addresses for '${backend}' yet — its topics and queues are named by ARN, which nothing creates locally. Use 'pgboss' (the default) or 'rabbitmq' for local development.`);
927
- this.backend = backend;
928
- this.name = "UnprovisionedEventsBackend";
929
- }
930
- };
931
- /**
932
- * The value a secret resolves to locally.
933
- *
934
- * A hash of what identifies it, so it is stable, distinct per project, stage
935
- * and construct, and never written to disk as a literal. Deployed this is the
936
- * one kind whose value does *not* come from here — a secret manager generates
937
- * it once and the target reads it back.
938
- */
939
- function localSecret(project, plan, resource) {
940
- return (0, node_crypto.createHash)("sha256").update(`${project}:${plan.stage}:${resource.id}`).digest("base64url").slice(0, 43);
941
- }
942
-
943
- //#endregion
944
- //#region src/reconcile/apps.ts
945
- /** The profile app services carry, so `gkm dev` starts only the containers. */
946
- const APPS_PROFILE = "apps";
947
- /**
948
- * Where an app's image is built from.
949
- *
950
- * An app at the project root is a single-app project, whose `gkm docker`
951
- * writes `.gkm/docker/Dockerfile`; a workspace writes one per app.
952
- */
953
- function dockerfileOf(appName, path) {
954
- return path === "." ? ".gkm/docker/Dockerfile" : `.gkm/docker/Dockerfile.${appName}`;
955
- }
956
- /**
957
- * Every construct key, addressed across the compose network.
958
- *
959
- * `envFor` is asked with a placeholder port for every port key, so each
960
- * `localhost:<placeholder>` in its answer names exactly one container port —
961
- * two containers listening on the same port inside cannot be confused — and is
962
- * rewritten to `<container>:<inside>`.
963
- */
964
- function inNetworkEnv(workspace, manifest) {
965
- const plan = planFor(manifest, workspace.stages.local, (0, __geekmidas_manifest.provisionOrder)(manifest), {
966
- localStage: workspace.stages.local,
967
- ...backendsOf(workspace)
968
- });
969
- const placeholders = {};
970
- const targets = /* @__PURE__ */ new Map();
971
- let next = 49152;
972
- for (const container of [...plan.containers].sort()) for (const port of portsOf(container)) {
973
- placeholders[port.key] = next;
974
- targets.set(next, `${container}:${port.inside}`);
975
- next += 1;
976
- }
977
- for (const key of portKeys(plan.containers)) placeholders[key] ??= next++;
978
- const env = envFor(plan, {
979
- ports: placeholders,
980
- project: workspace.name,
981
- addresses: surfaceAddresses(workspace, manifest, (app, port) => `http://${app}:${port}`)
982
- });
983
- const rewrite = (value) => value.replace(/(?:localhost|127\.0\.0\.1):(\d+)/g, (match, port) => {
984
- return targets.get(Number(port)) ?? match;
985
- });
986
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, rewrite(value)]));
987
- }
988
- /** One compose service per app the workspace runs, behind the apps profile. */
989
- function appServices(workspace, manifest, containers) {
990
- const env = inNetworkEnv(workspace, manifest);
991
- const services = {};
992
- for (const [name, app] of Object.entries(workspace.apps)) {
993
- if (app.type === "mobile" || !app.port) continue;
994
- const key = require_config.appKey(name);
995
- const health = app.type === "web" ? "/" : "/health";
996
- services[key] = {
997
- image: `${key}:\${TAG:-latest}`,
998
- build: {
999
- context: ".",
1000
- dockerfile: dockerfileOf(name, app.path)
1001
- },
1002
- profiles: [APPS_PROFILE],
1003
- ports: [`${app.port}:${app.port}`],
1004
- environment: {
1005
- NODE_ENV: "production",
1006
- PORT: String(app.port),
1007
- ...env
1008
- },
1009
- ...containers.some((c) => c !== "caddy") ? { depends_on: containers.filter((c) => c !== "caddy") } : {},
1010
- healthcheck: {
1011
- test: [
1012
- "CMD",
1013
- "wget",
1014
- "-q",
1015
- "--spider",
1016
- `http://localhost:${app.port}${health}`
1017
- ],
1018
- interval: "10s",
1019
- timeout: "5s",
1020
- retries: 5
1021
- }
1022
- };
1023
- }
1024
- return services;
1025
- }
1026
-
1027
- //#endregion
1028
- //#region src/reconcile/clients.ts
1029
- /** The credential local containers are brought up with. */
1030
- const LOCAL_USER$1 = "geekmidas";
1031
- /**
1032
- * A Postgres client that opens one connection per database it is asked about.
1033
- *
1034
- * `CREATE DATABASE` cannot run from a connection to the database being created,
1035
- * and a schema must be created from inside its own database — so the database is
1036
- * part of each query rather than fixed when the client is built.
1037
- */
1038
- function pgClient(port) {
1039
- return { async query(database, sql, values) {
1040
- const client = new pg.Client({
1041
- host: "localhost",
1042
- port,
1043
- user: LOCAL_USER$1,
1044
- password: LOCAL_USER$1,
1045
- database: database ?? LOCAL_USER$1
1046
- });
1047
- await client.connect();
1048
- try {
1049
- const result = await client.query(sql, values);
1050
- return result.rows;
1051
- } finally {
1052
- await client.end();
1053
- }
1054
- } };
1055
- }
1056
- /** A bucket client pointed at the local MinIO. */
1057
- function bucketClient(port) {
1058
- const s3 = new __aws_sdk_client_s3.S3Client({
1059
- region: "us-east-1",
1060
- endpoint: `http://localhost:${port}`,
1061
- forcePathStyle: true,
1062
- credentials: {
1063
- accessKeyId: LOCAL_USER$1,
1064
- secretAccessKey: LOCAL_USER$1
1065
- }
1066
- });
1067
- return {
1068
- async exists(bucket) {
1069
- try {
1070
- await s3.send(new __aws_sdk_client_s3.HeadBucketCommand({ Bucket: bucket }));
1071
- return true;
1072
- } catch {
1073
- return false;
1074
- }
1075
- },
1076
- async create(bucket) {
1077
- await s3.send(new __aws_sdk_client_s3.CreateBucketCommand({ Bucket: bucket }));
1078
- },
1079
- async policy(bucket) {
1080
- try {
1081
- const result = await s3.send(new __aws_sdk_client_s3.GetBucketPolicyCommand({ Bucket: bucket }));
1082
- return result.Policy;
1083
- } catch {
1084
- return void 0;
1085
- }
1086
- },
1087
- async setPolicy(bucket, policy) {
1088
- await s3.send(new __aws_sdk_client_s3.PutBucketPolicyCommand({
1089
- Bucket: bucket,
1090
- Policy: policy
1091
- }));
1092
- }
1093
- };
1094
- }
1095
-
1096
- //#endregion
1097
- //#region src/reconcile/compose.ts
1098
- /** The credential every derived container is brought up with locally. */
1099
- const LOCAL_USER = "geekmidas";
1100
- /**
1101
- * The token the local cache accepts.
1102
- *
1103
- * Fixed rather than generated: it is only ever reachable on a port this project
1104
- * published, and the URL that carries it is derived, so nothing is made safer
1105
- * by making it unguessable and a stable one keeps `redis-cli` sessions working.
1106
- */
1107
- const LOCAL_TOKEN = "geekmidas";
1108
- /**
1109
- * Build the compose document for a plan.
1110
- *
1111
- * Every container is published on its assigned port, never on the image's
1112
- * default: the point of allocation is that two projects can run at once, and
1113
- * one container publishing 5432 puts that back.
1114
- */
1115
- function composeFor(plan, options) {
1116
- const services = {};
1117
- const volumes = {};
1118
- for (const container of [...plan.containers].sort()) {
1119
- const declared = container === "postgres" ? plan.resources.find((r) => r.version)?.version : void 0;
1120
- const image = declared ? postgresImage(declared) : DEFAULT_IMAGES[container];
1121
- if (!image) throw new UnknownContainer(container);
1122
- services[container] = define(container, image, publish(container, options.ports));
1123
- const volume = volumeOf(container);
1124
- if (volume) volumes[volume] = {};
1125
- }
1126
- return {
1127
- name: options.project,
1128
- services: {
1129
- ...services,
1130
- ...options.apps
1131
- },
1132
- ...Object.keys(volumes).length ? { volumes } : {}
1133
- };
1134
- }
1135
- /** Render a compose document as the file it becomes. */
1136
- function toYaml(file) {
1137
- return `# Generated by gkm from the construct manifest — do not edit.
1138
- # Containers are derived from what the app declares. Image pins and anything
1139
- # no construct implies go in your own docker-compose.yml, which is merged over
1140
- # this file and wins:
1141
- #
1142
- # docker compose -f docker-compose.constructs.yml -f docker-compose.yml …
1143
- #
1144
- # "gkm dev" and "gkm test" start the containers. The apps sit behind the
1145
- # "apps" profile: run "gkm setup", then
1146
- # docker compose -f docker-compose.constructs.yml --profile apps up --build
1147
- ${(0, yaml.stringify)(file, { lineWidth: 0 })}`;
1148
- }
1149
- /** A container with no image, from config or from the defaults. */
1150
- var UnknownContainer = class extends Error {
1151
- /** The container that could not be resolved. */
1152
- container;
1153
- /** The containers that have a default, so the caller can see the set. */
1154
- known = Object.keys(DEFAULT_IMAGES).sort();
1155
- constructor(container) {
1156
- super("No image is known for this container; pin one in config");
1157
- this.name = "UnknownContainer";
1158
- this.container = container;
1159
- }
1160
- };
1161
- /** One container's definition, published on the port it was assigned. */
1162
- function define(container, image, published) {
1163
- switch (container) {
1164
- case "postgres": return {
1165
- image,
1166
- restart: "unless-stopped",
1167
- ports: published,
1168
- environment: {
1169
- POSTGRES_USER: LOCAL_USER,
1170
- POSTGRES_PASSWORD: LOCAL_USER,
1171
- POSTGRES_DB: LOCAL_USER
1172
- },
1173
- volumes: ["postgres-data:/var/lib/postgresql"],
1174
- healthcheck: {
1175
- test: ["CMD-SHELL", `pg_isready -U ${LOCAL_USER}`],
1176
- interval: "5s",
1177
- timeout: "3s",
1178
- retries: 10,
1179
- start_period: "10s"
1180
- }
1181
- };
1182
- case "minio": return {
1183
- image,
1184
- restart: "unless-stopped",
1185
- ports: published,
1186
- environment: {
1187
- MINIO_ROOT_USER: LOCAL_USER,
1188
- MINIO_ROOT_PASSWORD: LOCAL_USER
1189
- },
1190
- command: "server --console-address \":9001\" /data",
1191
- volumes: ["minio-data:/data"],
1192
- healthcheck: {
1193
- test: [
1194
- "CMD",
1195
- "mc",
1196
- "ready",
1197
- "local"
1198
- ],
1199
- interval: "10s",
1200
- timeout: "5s",
1201
- retries: 5,
1202
- start_period: "10s"
1203
- }
1204
- };
1205
- case "caddy": return {
1206
- image,
1207
- restart: "unless-stopped",
1208
- ports: published,
1209
- volumes: [
1210
- "./.gkm/Caddyfile:/etc/caddy/Caddyfile:ro",
1211
- "./.gkm/caddy-sites:/etc/caddy/sites:ro",
1212
- "caddy-data:/data"
1213
- ],
1214
- extra_hosts: ["host.docker.internal:host-gateway"],
1215
- healthcheck: {
1216
- test: [
1217
- "CMD",
1218
- "caddy",
1219
- "version"
1220
- ],
1221
- interval: "10s",
1222
- timeout: "5s",
1223
- retries: 5
1224
- }
1225
- };
1226
- case "mailpit": return {
1227
- image,
1228
- restart: "unless-stopped",
1229
- ports: published,
1230
- environment: {
1231
- MP_SMTP_AUTH_ACCEPT_ANY: "1",
1232
- MP_SMTP_AUTH_ALLOW_INSECURE: "1"
1233
- },
1234
- healthcheck: {
1235
- test: [
1236
- "CMD",
1237
- "wget",
1238
- "-q",
1239
- "--spider",
1240
- "http://localhost:8025"
1241
- ],
1242
- interval: "10s",
1243
- timeout: "5s",
1244
- retries: 5
1245
- }
1246
- };
1247
- case "redis": return {
1248
- image,
1249
- restart: "unless-stopped",
1250
- ports: published,
1251
- volumes: ["redis-data:/data"],
1252
- healthcheck: {
1253
- test: [
1254
- "CMD",
1255
- "redis-cli",
1256
- "ping"
1257
- ],
1258
- interval: "5s",
1259
- timeout: "3s",
1260
- retries: 5
1261
- }
1262
- };
1263
- case "redis-http": return {
1264
- image,
1265
- restart: "unless-stopped",
1266
- ports: published,
1267
- environment: {
1268
- SRH_MODE: "env",
1269
- SRH_TOKEN: LOCAL_TOKEN,
1270
- SRH_CONNECTION_STRING: "redis://redis:6379"
1271
- },
1272
- depends_on: ["redis"],
1273
- healthcheck: {
1274
- test: [
1275
- "CMD",
1276
- "wget",
1277
- "-q",
1278
- "-O",
1279
- "/dev/null",
1280
- "http://127.0.0.1:80/"
1281
- ],
1282
- interval: "5s",
1283
- timeout: "3s",
1284
- retries: 10
1285
- }
1286
- };
1287
- case "rabbitmq": return {
1288
- image,
1289
- restart: "unless-stopped",
1290
- ports: published,
1291
- environment: {
1292
- RABBITMQ_DEFAULT_USER: LOCAL_USER,
1293
- RABBITMQ_DEFAULT_PASS: LOCAL_USER
1294
- },
1295
- volumes: ["rabbitmq-data:/var/lib/rabbitmq"],
1296
- healthcheck: {
1297
- test: [
1298
- "CMD",
1299
- "rabbitmq-diagnostics",
1300
- "-q",
1301
- "ping"
1302
- ],
1303
- interval: "10s",
1304
- timeout: "5s",
1305
- retries: 5
1306
- }
1307
- };
1308
- case "localstack": return {
1309
- image,
1310
- restart: "unless-stopped",
1311
- ports: published,
1312
- environment: {
1313
- AWS_DEFAULT_REGION: "us-east-1",
1314
- AWS_ACCESS_KEY_ID: "LSIAQAAAAAAVNCBMPNSG",
1315
- AWS_SECRET_ACCESS_KEY: LOCAL_USER
1316
- },
1317
- volumes: ["localstack-data:/var/lib/localstack"],
1318
- healthcheck: {
1319
- test: [
1320
- "CMD",
1321
- "curl",
1322
- "-f",
1323
- "http://localhost:4566/_localstack/health"
1324
- ],
1325
- interval: "10s",
1326
- timeout: "5s",
1327
- retries: 5,
1328
- start_period: "10s"
1329
- }
1330
- };
1331
- default: throw new UnknownContainer(container);
1332
- }
1333
- }
1334
- /**
1335
- * The published port mappings for a container.
1336
- *
1337
- * Every port is looked up by its own key rather than being derived as an offset
1338
- * from the container's first, so MinIO's console cannot land on whatever was
1339
- * allocated to the next container.
1340
- */
1341
- function publish(container, ports) {
1342
- return portsOf(container).map((port) => {
1343
- const assigned = ports[port.key];
1344
- if (assigned === void 0) throw new UnassignedPort(port.key);
1345
- return `${assigned}:${port.inside}`;
1346
- });
1347
- }
1348
- /** A planned port that allocation never assigned. */
1349
- var UnassignedPort = class extends Error {
1350
- /** The port key that went unassigned, e.g. `minio-console`. */
1351
- key;
1352
- constructor(key) {
1353
- super("No port was assigned for this container port");
1354
- this.name = "UnassignedPort";
1355
- this.key = key;
1356
- }
1357
- };
1358
-
1359
- //#endregion
1360
- //#region src/reconcile/docker.ts
1361
- const run = (0, node_util.promisify)(node_child_process.execFile);
1362
- /**
1363
- * The generated file, then the project's own if it has one.
1364
- *
1365
- * Merged in that order so the project's wins — an `image:` there pins a
1366
- * container this file derived, and a service there is added beside them.
1367
- */
1368
- function composeFiles(composePath) {
1369
- const project = (0, node_path.join)((0, node_path.dirname)(composePath), "docker-compose.yml");
1370
- return [
1371
- "-f",
1372
- composePath,
1373
- ...(0, node_fs.existsSync)(project) ? ["-f", project] : []
1374
- ];
1375
- }
1376
- /** How long to wait for containers to pass their health checks. */
1377
- const HEALTH_TIMEOUT_MS = 12e4;
1378
- const dockerCli = {
1379
- async publishedPort(composePath, service, inside) {
1380
- try {
1381
- const { stdout } = await run("docker", [
1382
- "compose",
1383
- ...composeFiles(composePath),
1384
- "port",
1385
- service,
1386
- String(inside)
1387
- ]);
1388
- const port = Number(stdout.trim().split(":").pop());
1389
- return Number.isFinite(port) && port > 0 ? port : void 0;
1390
- } catch {
1391
- return void 0;
1392
- }
1393
- },
1394
- async up(composePath, services) {
1395
- await run("docker", [
1396
- "compose",
1397
- ...composeFiles(composePath),
1398
- "up",
1399
- "-d",
1400
- "--remove-orphans",
1401
- "--wait",
1402
- `--wait-timeout=${Math.floor(HEALTH_TIMEOUT_MS / 1e3)}`,
1403
- ...services
1404
- ]);
1405
- },
1406
- async copyOut(composePath, service, from, to) {
1407
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(to), { recursive: true });
1408
- await run("docker", [
1409
- "compose",
1410
- ...composeFiles(composePath),
1411
- "cp",
1412
- `${service}:${from}`,
1413
- to
1414
- ]);
1415
- },
1416
- async reload(composePath, service) {
1417
- await run("docker", [
1418
- "compose",
1419
- ...composeFiles(composePath),
1420
- "exec",
1421
- "-T",
1422
- service,
1423
- "caddy",
1424
- "reload",
1425
- "--config",
1426
- "/etc/caddy/Caddyfile"
1427
- ]);
1428
- },
1429
- async healthy(composePath, services) {
1430
- if (services.length === 0) return true;
1431
- try {
1432
- const { stdout } = await run("docker", [
1433
- "compose",
1434
- ...composeFiles(composePath),
1435
- "ps",
1436
- "--format",
1437
- "json",
1438
- ...services
1439
- ]);
1440
- const running = /* @__PURE__ */ new Set();
1441
- for (const line of stdout.trim().split("\n").filter(Boolean)) {
1442
- const entry = JSON.parse(line);
1443
- const ok = entry.State === "running" && (entry.Health === void 0 || entry.Health === "" || entry.Health === "healthy");
1444
- if (ok && entry.Service) running.add(entry.Service);
1445
- }
1446
- return services.every((service) => running.has(service));
1447
- } catch {
1448
- return false;
1449
- }
1450
- }
1451
- };
1452
-
1453
- //#endregion
1454
- //#region src/reconcile/ports.ts
1455
- /**
1456
- * The window ports are drawn from.
1457
- *
1458
- * Above the registered range so nothing here needs privileges, and below the
1459
- * ephemeral range both Linux (32768+) and macOS (49152+) allocate from — a port
1460
- * the kernel might hand to an outgoing connection is one that is free when
1461
- * checked and taken by the time it is bound.
1462
- */
1463
- const WINDOW = {
1464
- min: 2e4,
1465
- max: 32e3
1466
- };
1467
- /**
1468
- * How far apart two projects start.
1469
- *
1470
- * Wide enough that a project can add containers without walking into its
1471
- * neighbour's block, narrow enough that the window holds many projects.
1472
- */
1473
- const BLOCK = 50;
1474
- /**
1475
- * Where a project's ports start.
1476
- *
1477
- * Derived from the name rather than assigned sequentially so that a fresh clone
1478
- * of the same project on the same machine lands on the same block — the first
1479
- * run has nothing persisted to read, and hashing is what keeps that first run
1480
- * from colliding with whatever else is already allocated.
1481
- *
1482
- * @example startingPort('toolbox') // stable for a given name
1483
- */
1484
- function startingPort(project) {
1485
- const digest = (0, node_crypto.createHash)("sha256").update(project).digest();
1486
- const blocks = Math.floor((WINDOW.max - WINDOW.min) / BLOCK);
1487
- return WINDOW.min + digest.readUInt32BE(0) % blocks * BLOCK;
1488
- }
1489
- /**
1490
- * Assign a port to every container that has none, keeping the ones that do.
1491
- *
1492
- * Existing assignments are returned untouched even when the container is no
1493
- * longer in the plan: removing a construct must not renumber what is left, and
1494
- * keeping the entry means re-adding it later restores the same port rather than
1495
- * inventing a new one.
1496
- *
1497
- * @param probe - reports what is actually listening. A port assigned to this
1498
- * project is skipped without probing, because on a converged reconcile our own
1499
- * container is the thing listening on it.
1500
- * @throws {NoPortAvailable} when the window is exhausted.
1501
- */
1502
- async function allocate(project, containers, existing = {}, probe = isPortFree) {
1503
- const assignments = { ...existing };
1504
- const taken = new Set(Object.values(assignments));
1505
- for (const container of [...containers].sort()) {
1506
- if (assignments[container] !== void 0) continue;
1507
- const port = await nextFree(startingPort(project), taken, probe);
1508
- assignments[container] = port;
1509
- taken.add(port);
1510
- }
1511
- return assignments;
1512
- }
1513
- /** The window was exhausted. */
1514
- var NoPortAvailable = class extends Error {
1515
- /** Where the search started. */
1516
- from;
1517
- /** The window searched, so the caller can report what was full. */
1518
- window = WINDOW;
1519
- constructor(from) {
1520
- super("No free port is available in the local port range");
1521
- this.name = "NoPortAvailable";
1522
- this.from = from;
1523
- }
1524
- };
1525
- /**
1526
- * The first port at or after `from` that is neither ours nor in use.
1527
- *
1528
- * Wraps at the top of the window rather than stopping, so a project whose block
1529
- * sits near the end is not the one that fails.
1530
- */
1531
- async function nextFree(from, taken, probe) {
1532
- const span = WINDOW.max - WINDOW.min;
1533
- for (let offset = 0; offset < span; offset++) {
1534
- const port = WINDOW.min + (from - WINDOW.min + offset) % span;
1535
- if (taken.has(port)) continue;
1536
- if (await probe(port)) return port;
1537
- }
1538
- throw new NoPortAvailable(from);
1539
- }
1540
- /**
1541
- * Whether nothing is listening on a port.
1542
- *
1543
- * Binds rather than connects: a refused connection says nothing about whether
1544
- * the port can be *published*, which is the question Docker will ask. Binds on
1545
- * `0.0.0.0` for the same reason — a port free on loopback can still be taken on
1546
- * the address Docker publishes to.
1547
- *
1548
- * Inherently racy, and that is acceptable: Docker failing to bind stays the real
1549
- * check. This exists so the common case surfaces as a message at reconcile
1550
- * rather than as a connection failure ten minutes later.
1551
- */
1552
- function isPortFree(port) {
1553
- return new Promise((resolve$1) => {
1554
- const server = (0, node_net.createServer)();
1555
- server.once("error", () => resolve$1(false));
1556
- server.once("listening", () => server.close(() => resolve$1(true)));
1557
- server.listen(port, "0.0.0.0");
1558
- });
1559
- }
1560
-
1561
- //#endregion
1562
- //#region src/reconcile/provision.ts
1563
- /**
1564
- * The Postgres work a plan implies.
1565
- *
1566
- * Databases before the schemas inside them, which `provisionOrder` already
1567
- * guarantees by putting parents first.
1568
- */
1569
- function postgresStatements(plan, project = "") {
1570
- const statements = [];
1571
- for (const resource of plan.resources) {
1572
- if (!resource.provisions || resource.container !== "postgres") continue;
1573
- if (resource.kind === "database") {
1574
- statements.push({
1575
- id: resource.id,
1576
- describe: `database ${resource.name}`,
1577
- exists: {
1578
- sql: "SELECT 1 FROM pg_database WHERE datname = $1",
1579
- values: [resource.name]
1580
- },
1581
- create: `CREATE DATABASE ${quoteIdentifier(resource.name)}`
1582
- });
1583
- if (resource.schema) statements.push(...rolesFor(resource, resource.schema, plan, project));
1584
- continue;
1585
- }
1586
- if (resource.kind === "database-schema" && resource.schema) statements.push(...rolesFor(resource, resource.schema, plan, project));
1587
- const cacheHome = resource.kind === "cache" && resource.of ? plan.resources.find((r) => r.id === resource.of) : void 0;
1588
- if (cacheHome) statements.push(...cacheTableDdl(resource, cacheHome, plan));
1589
- }
1590
- return statements;
1591
- }
1592
- /**
1593
- * A cache's table, in the schema the role that reads it resolves names in.
1594
- *
1595
- * Two things have to line up, and neither is the table's contents. The driver
1596
- * names the table unqualified and lets the connection's `search_path` place it
1597
- * — which the role carries — so creating it from the master connection, whose
1598
- * path is `public`, leaves a table the application cannot see and a
1599
- * `relation "cache" does not exist` on the first request. And the default
1600
- * privileges that make a tenant's tables reachable are granted *for the owner
1601
- * role*, so nothing covers a table the master created.
1602
- *
1603
- * Hence: qualified with the tenant's schema, handed to its owner, and granted
1604
- * explicitly — `roleStatements` grants what exists at the time it runs, and
1605
- * this table does not exist yet.
1606
- *
1607
- * A database that opted out of roles needs none of it: everything connects as
1608
- * the master, whose `search_path` finds `public`, and the table it creates
1609
- * there is the table it reads.
1610
- */
1611
- function cacheTableDdl(cache, home, plan) {
1612
- const database = rootDatabase(home, plan);
1613
- const schema = home.roles === false ? void 0 : home.schema;
1614
- const name = cache.table ?? (0, __geekmidas_manifest.cacheTable)(cache.id);
1615
- const table = schema ? `${schema}.${name}` : name;
1616
- const created = (0, __geekmidas_cache_postgres.cacheTableStatements)({ table }).map((statement) => ({
1617
- id: cache.id,
1618
- describe: statement.describe,
1619
- database,
1620
- ...statement.exists ? { exists: statement.exists } : {},
1621
- create: statement.sql
1622
- }));
1623
- if (!schema) return created;
1624
- const runtime = localRole(home);
1625
- const owner = (0, __geekmidas_db_pg_roles.ownerRole)(runtime);
1626
- const qualified = table.split(".").map((part) => quoteIdentifier(part)).join(".");
1627
- return [
1628
- ...created,
1629
- {
1630
- id: cache.id,
1631
- describe: `cache table ${table} is owned by ${owner}`,
1632
- database,
1633
- create: `ALTER TABLE ${qualified} OWNER TO ${quoteIdentifier(owner)}`
1634
- },
1635
- {
1636
- id: cache.id,
1637
- describe: `${runtime} may read and write ${table}`,
1638
- database,
1639
- create: `GRANT SELECT, INSERT, UPDATE, DELETE ON ${qualified} TO ${quoteIdentifier(runtime)}`
1640
- }
1641
- ];
1642
- }
1643
- /**
1644
- * The roles and schema for one database or tenant.
1645
- *
1646
- * Skipped entirely when the construct declared `roles: false` — the documented
1647
- * downgrade, where both URLs fall back to the cluster's master credential. It
1648
- * is a choice someone made rather than a default they got.
1649
- */
1650
- function rolesFor(resource, schema, plan, project) {
1651
- if (resource.roles === false) return [];
1652
- const runtime = localRole(resource);
1653
- const owner = (0, __geekmidas_db_pg_roles.ownerRole)(runtime);
1654
- const reader = plan.resources.some((r) => r.kind === "database-reader" && r.of === resource.id) ? (0, __geekmidas_db_pg_roles.readerRole)(runtime) : void 0;
1655
- return (0, __geekmidas_db_pg_roles.roleStatements)({
1656
- runtime,
1657
- owner,
1658
- ...reader ? { reader } : {},
1659
- schema,
1660
- passwords: {
1661
- runtime: localRolePassword(project, plan, runtime),
1662
- owner: localRolePassword(project, plan, owner),
1663
- ...reader ? { reader: localRolePassword(project, plan, reader) } : {}
1664
- }
1665
- }).map((statement) => ({
1666
- id: resource.id,
1667
- describe: statement.describe,
1668
- database: rootDatabase(resource, plan),
1669
- ...statement.exists ? { exists: statement.exists } : {},
1670
- create: statement.sql
1671
- }));
1672
- }
1673
- /** The buckets a plan implies. */
1674
- function bucketNames(plan) {
1675
- return plan.resources.filter((r) => r.provisions && r.kind === "objects").map((r) => r.name);
1676
- }
1677
- /**
1678
- * Quote an identifier for use in DDL.
1679
- *
1680
- * Names reaching here are already canonical and stage-suffixed, so this is
1681
- * defence rather than sanitisation — but DDL cannot be parameterised, and an
1682
- * unquoted identifier is the one place a name could ever be more than a name.
1683
- */
1684
- function quoteIdentifier(name) {
1685
- return `"${name.replace(/"/g, "\"\"")}"`;
1686
- }
1687
- /**
1688
- * Apply the plan's Postgres statements.
1689
- *
1690
- * Each is checked before it is run, so this converges rather than erroring on a
1691
- * second pass.
1692
- */
1693
- async function applyPostgres(client, statements) {
1694
- const applied = [];
1695
- for (const statement of statements) {
1696
- if (!statement.exists) {
1697
- await client.query(statement.database, statement.create);
1698
- applied.push({
1699
- id: statement.id,
1700
- describe: statement.describe,
1701
- created: false
1702
- });
1703
- continue;
1704
- }
1705
- const rows = await client.query(statement.database, statement.exists.sql, statement.exists.values);
1706
- if (rows.length > 0) {
1707
- applied.push({
1708
- id: statement.id,
1709
- describe: statement.describe,
1710
- created: false
1711
- });
1712
- continue;
1713
- }
1714
- await client.query(statement.database, statement.create);
1715
- applied.push({
1716
- id: statement.id,
1717
- describe: statement.describe,
1718
- created: true
1719
- });
1720
- }
1721
- return applied;
1722
- }
1723
- /**
1724
- * What each bucket's open paths are, if anything serves it.
1725
- *
1726
- * Keyed by the *origin*, because that is where the policy lives: two servers
1727
- * over one bucket contribute to one policy, so the patterns are unioned rather
1728
- * than the last one winning.
1729
- */
1730
- function bucketPolicies(plan) {
1731
- const byBucket = /* @__PURE__ */ new Map();
1732
- for (const resource of plan.resources) {
1733
- if (resource.kind !== "file-server" || !resource.open?.length) continue;
1734
- const origin = plan.resources.find((r) => r.id === resource.of);
1735
- if (!origin) continue;
1736
- const patterns = byBucket.get(origin.name) ?? /* @__PURE__ */ new Set();
1737
- for (const pattern of resource.open) patterns.add(pattern);
1738
- byBucket.set(origin.name, patterns);
1739
- }
1740
- return [...byBucket].map(([bucket, open]) => ({
1741
- bucket,
1742
- open: [...open].sort()
1743
- })).sort((a, b) => a.bucket.localeCompare(b.bucket));
1744
- }
1745
- /**
1746
- * One bucket's open paths as an S3 bucket policy.
1747
- *
1748
- * Anonymous `s3:GetObject` on the named prefixes and nothing else — which is
1749
- * what "open" means everywhere: the server serves that path without a
1750
- * signature, and the bucket stays private for everything else.
1751
- *
1752
- * One fidelity note, stated rather than discovered: an S3 policy resource's `*`
1753
- * crosses `/`, so a single-star pattern is *wider* here than the construct's own
1754
- * runtime check, which stops at a segment boundary. The construct is the
1755
- * stricter of the two, so a key it refuses to serve unsigned is never one this
1756
- * policy was relied on to refuse — but a key fetched directly, bypassing the
1757
- * client, can be admitted by the policy where the client would have said no.
1758
- * Prefer `**` where crossing segments is what you meant.
1759
- */
1760
- function bucketPolicy(bucket, open) {
1761
- return JSON.stringify({
1762
- Version: "2012-10-17",
1763
- Statement: [{
1764
- Sid: "GkmOpenPaths",
1765
- Effect: "Allow",
1766
- Principal: { AWS: ["*"] },
1767
- Action: ["s3:GetObject"],
1768
- Resource: open.map((pattern) => `arn:aws:s3:::${bucket}/${pattern.replace(/\*\*/g, "*")}`)
1769
- }]
1770
- });
1771
- }
1772
- /**
1773
- * Apply each served bucket's open-path policy, skipping those already correct.
1774
- *
1775
- * Compared as parsed JSON rather than as text: the same policy re-serialised
1776
- * with different key order is the same policy, and rewriting it every reconcile
1777
- * would report a change on every start.
1778
- */
1779
- async function applyPolicies(client, policies) {
1780
- const applied = [];
1781
- for (const { bucket, open } of policies) {
1782
- const wanted = bucketPolicy(bucket, open);
1783
- const describe = `open paths on ${bucket}`;
1784
- if (equivalent(await client.policy(bucket), wanted)) {
1785
- applied.push({
1786
- id: `${bucket}:policy`,
1787
- describe,
1788
- created: false
1789
- });
1790
- continue;
1791
- }
1792
- await client.setPolicy(bucket, wanted);
1793
- applied.push({
1794
- id: `${bucket}:policy`,
1795
- describe,
1796
- created: true
1797
- });
1798
- }
1799
- return applied;
1800
- }
1801
- /** Whether two policy documents say the same thing. */
1802
- function equivalent(current, wanted) {
1803
- if (!current) return false;
1804
- try {
1805
- return JSON.stringify(JSON.parse(current)) === JSON.stringify(JSON.parse(wanted));
1806
- } catch {
1807
- return false;
1808
- }
1809
- }
1810
- /** Create every bucket the plan names, skipping those that exist. */
1811
- async function applyBuckets(client, buckets) {
1812
- const applied = [];
1813
- for (const bucket of buckets) {
1814
- if (await client.exists(bucket)) {
1815
- applied.push({
1816
- id: bucket,
1817
- describe: `bucket ${bucket}`,
1818
- created: false
1819
- });
1820
- continue;
1821
- }
1822
- await client.create(bucket);
1823
- applied.push({
1824
- id: bucket,
1825
- describe: `bucket ${bucket}`,
1826
- created: true
1827
- });
1828
- }
1829
- return applied;
1830
- }
1831
-
1832
- //#endregion
1833
- //#region src/reconcile/state.ts
1834
- const STATE_DIR = ".gkm/reconcile";
1835
- /**
1836
- * The hash of everything a reconcile would act on.
1837
- *
1838
- * Covers the compose document rather than the plan alone, because the plan is
1839
- * unchanged when only an image pin moves — and a changed image is exactly a
1840
- * container that must be recreated. `stringify` is stable here because
1841
- * `composeFor` sorts its containers, which is what makes the hash meaningful.
1842
- *
1843
- * Deliberately a plain function over serialisable input: the deployed target
1844
- * keys its provisioner invocation on the same idea, and the two must not be able
1845
- * to disagree about what counts as a change.
1846
- */
1847
- function planHash(plan, compose, generated = {}) {
1848
- return (0, node_crypto.createHash)("sha256").update(JSON.stringify({
1849
- stage: plan.stage,
1850
- plan,
1851
- compose,
1852
- generated
1853
- })).digest("hex");
1854
- }
1855
- /** Read the recorded state, or nothing if this stage has never reconciled. */
1856
- async function loadState(root, stage) {
1857
- try {
1858
- const raw = await (0, node_fs_promises.readFile)(statePath(root, stage), "utf-8");
1859
- const state = JSON.parse(raw);
1860
- return state.stage === stage ? state : void 0;
1861
- } catch {
1862
- return void 0;
1863
- }
1864
- }
1865
- /** Record what was applied, so the next run can skip it. */
1866
- async function saveState(root, state) {
1867
- const path = statePath(root, state.stage);
1868
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
1869
- await (0, node_fs_promises.writeFile)(path, `${JSON.stringify(state, null, 2)}\n`);
1870
- }
1871
- function statePath(root, stage) {
1872
- return (0, node_path.join)(root, STATE_DIR, `${stage}.json`);
1873
- }
1874
-
1875
- //#endregion
1876
- //#region src/reconcile/index.ts
1877
- /**
1878
- * Where the generated compose file is written, relative to the project root.
1879
- *
1880
- * At the root, beside the project's own `docker-compose.yml`, because the two
1881
- * are one stack: this file is everything the constructs imply and is never
1882
- * edited, that one is anything they cannot express — an image pin, an extra
1883
- * service — and is merged over it, so it wins.
1884
- */
1885
- const COMPOSE_PATH = "docker-compose.constructs.yml";
1886
- /**
1887
- * The local edge's config, beside the compose file that mounts it.
1888
- *
1889
- * Relative in the compose volume, so it resolves against `.gkm/` wherever the
1890
- * project lives.
1891
- */
1892
- const CADDYFILE_PATH = ".gkm/Caddyfile";
1893
- /**
1894
- * Where one stage's routes live, imported by the file above.
1895
- *
1896
- * Per stage because one edge serves every stage, the same way one Postgres
1897
- * holds `orders` and `orders_test`. A single file would mean `gkm test`
1898
- * deleting the routes `gkm dev` is serving.
1899
- */
1900
- const caddySitesPath = (stage) => `.gkm/caddy-sites/${stage}.caddy`;
1901
- /**
1902
- * Where the local edge's root certificate is copied to.
1903
- *
1904
- * Exported so a process can be pointed at it without installing anything:
1905
- * `NODE_EXTRA_CA_CERTS` is the whole of the trust story for Node, and it needs
1906
- * no sudo. A browser is the case that still wants the root in the system store,
1907
- * which is a one-time `caddy trust` rather than something a reconcile should do
1908
- * on a developer's behalf.
1909
- */
1910
- const LOCAL_CA_PATH = ".gkm/caddy-root.crt";
1911
- /** Where Caddy keeps the root of the CA it generated. */
1912
- const CADDY_ROOT_IN_CONTAINER = "/data/caddy/pki/authorities/local/root.crt";
1913
- /**
1914
- * Converge the local target on what the manifest declares.
1915
- *
1916
- * Cheap when there is nothing to do: the hash is compared before the compose
1917
- * file is written or a container is touched, and a converged project pays one
1918
- * hash and one health check.
1919
- */
1920
- async function reconcile(options) {
1921
- const { root, project, manifest, stage, start = true, provision = true, docker = dockerCli, probe = isPortFree, sql = pgClient, buckets = bucketClient } = options;
1922
- const plan = planFor(manifest, stage, (0, __geekmidas_manifest.provisionOrder)(manifest), {
1923
- localStage: options.localStage,
1924
- events: options.events,
1925
- cache: options.cache,
1926
- extraContainers: options.extraContainers,
1927
- ...options.edge === void 0 ? {} : { edge: options.edge }
1928
- });
1929
- const composePath = (0, node_path.join)(root, COMPOSE_PATH);
1930
- const observed = await observedPorts(docker, composePath, plan.containers);
1931
- const ports = await allocate(project, portKeys(plan.containers), {
1932
- ...options.saved,
1933
- ...observed
1934
- }, probe);
1935
- const compose = composeFor(plan, {
1936
- project,
1937
- ports,
1938
- ...options.apps ? { apps: options.apps(plan.containers) } : {}
1939
- });
1940
- const caddyfile = toCaddyfile(sitesFor(plan, project, options.addresses));
1941
- const hash = planHash(plan, compose, { caddyfile });
1942
- const addresses = addressesFor(plan.containers, ports);
1943
- const env = envFor(plan, {
1944
- ports,
1945
- project,
1946
- ...options.mailFrom ? { mailFrom: options.mailFrom } : {},
1947
- ...options.addresses ? { addresses: options.addresses } : {}
1948
- });
1949
- if (plan.containers.includes("caddy")) env.NODE_EXTRA_CA_CERTS = (0, node_path.join)(root, LOCAL_CA_PATH);
1950
- const result = {
1951
- stage,
1952
- plan,
1953
- compose,
1954
- ports,
1955
- addresses,
1956
- env,
1957
- provisioned: [],
1958
- hash,
1959
- changed: false
1960
- };
1961
- const recorded = await loadState(root, stage);
1962
- const converged = recorded?.hash === hash && (0, node_fs.existsSync)(composePath) && (!start || await docker.healthy(composePath, plan.containers));
1963
- if (converged) return result;
1964
- await write(composePath, toYaml(compose));
1965
- if (plan.containers.includes("caddy")) {
1966
- await write((0, node_path.join)(root, CADDYFILE_PATH), caddyfileRoot());
1967
- await write((0, node_path.join)(root, caddySitesPath(stage)), caddyfile);
1968
- }
1969
- if (start && plan.containers.length > 0) await docker.up(composePath, plan.containers);
1970
- if (start && plan.containers.includes("caddy")) await docker.reload(composePath, "caddy").catch(() => {});
1971
- if (start && plan.containers.includes("caddy")) await docker.copyOut(composePath, "caddy", CADDY_ROOT_IN_CONTAINER, (0, node_path.join)(root, LOCAL_CA_PATH)).catch(() => {});
1972
- const provisioned = start && provision ? await create(plan, ports, sql, buckets, project) : [];
1973
- await saveState(root, {
1974
- hash,
1975
- stage
1976
- });
1977
- return {
1978
- ...result,
1979
- provisioned,
1980
- changed: true
1981
- };
1982
- }
1983
- /**
1984
- * Create the databases, schemas, and buckets the plan names.
1985
- *
1986
- * Idempotent throughout, so this runs on every non-converged reconcile rather
1987
- * than being something to remember.
1988
- */
1989
- async function create(plan, ports, sql, buckets, project) {
1990
- const applied = [];
1991
- const postgresPort = ports[primaryPortKey("postgres")];
1992
- const statements = postgresStatements(plan, project);
1993
- if (postgresPort !== void 0 && statements.length > 0) applied.push(...await applyPostgres(sql(postgresPort), statements));
1994
- const minioPort = ports[primaryPortKey("minio")];
1995
- const names = bucketNames(plan);
1996
- const policies = bucketPolicies(plan);
1997
- if (minioPort !== void 0 && (names.length > 0 || policies.length > 0)) {
1998
- const client = buckets(minioPort);
1999
- if (names.length > 0) applied.push(...await applyBuckets(client, names));
2000
- if (policies.length > 0) applied.push(...await applyPolicies(client, policies));
2001
- }
2002
- return applied;
2003
- }
2004
- /**
2005
- * The host ports of containers already running.
2006
- *
2007
- * Keyed the same way allocation keys them, so the two merge without either
2008
- * knowing about the other.
2009
- */
2010
- async function observedPorts(docker, composePath, containers) {
2011
- const observed = {};
2012
- for (const container of containers) for (const port of portsOf(container)) {
2013
- const running = await docker.publishedPort(composePath, container, port.inside);
2014
- if (running !== void 0) observed[port.key] = running;
2015
- }
2016
- return observed;
2017
- }
2018
- /**
2019
- * Where each container can be reached on this machine.
2020
- *
2021
- * The primary port only — a container's console is for a human to open, not
2022
- * something an app connects to.
2023
- */
2024
- function addressesFor(containers, ports) {
2025
- const addresses = {};
2026
- for (const container of containers) {
2027
- const port = ports[primaryPortKey(container)];
2028
- if (port !== void 0) addresses[container] = `localhost:${port}`;
2029
- }
2030
- return addresses;
2031
- }
2032
- /** Write a file only when its content would change, so mtimes stay meaningful. */
2033
- async function write(path, content) {
2034
- try {
2035
- if (await (0, node_fs_promises.readFile)(path, "utf-8") === content) return;
2036
- } catch {}
2037
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
2038
- await (0, node_fs_promises.writeFile)(path, content);
2039
- }
2040
-
2041
- //#endregion
2042
- //#region src/reconcile/workspace.ts
2043
- /**
2044
- * Every constructs glob in the workspace, resolved against its app.
2045
- *
2046
- * Absolute because discovery globs from a single cwd while apps live in
2047
- * different directories.
2048
- */
2049
- function constructGlobs(workspace) {
2050
- return require_workspace.allConstructGlobs(workspace);
2051
- }
2052
- /** Whether any app has adopted the constructs glob. */
2053
- function usesConstructs(workspace) {
2054
- return constructGlobs(workspace).length > 0;
2055
- }
2056
- /** The backends a workspace's target implies, as the plan takes them. */
2057
- function backendsOf(workspace) {
2058
- const on = providerOf(workspace);
2059
- return {
2060
- events: eventsBackendFor(on),
2061
- cache: cacheBackendFor(on)
2062
- };
2063
- }
2064
- /**
2065
- * The containers a workspace's declarations imply, without reconciling.
2066
- *
2067
- * The same derivation `reconcileWorkspace` makes, available to callers that
2068
- * need to know *what would run* without starting anything or writing ports —
2069
- * `gkm setup` deciding which credentials to generate, `gkm docker` writing a
2070
- * compose file. Those used to each read a boolean per service out of config,
2071
- * which is how a container could exist because config asked for one rather than
2072
- * because something declared it.
2073
- */
2074
- async function derivedContainers(workspace, stage, manifest) {
2075
- const found = manifest ?? await require_discover.discover({
2076
- patterns: constructGlobs(workspace),
2077
- cwd: workspace.root
2078
- });
2079
- return planFor(found, stage, (0, __geekmidas_manifest.provisionOrder)(found), {
2080
- localStage: workspace.stages.local,
2081
- ...backendsOf(workspace)
2082
- }).containers;
2083
- }
2084
- /**
2085
- * Reconcile a workspace for one stage.
2086
- *
2087
- * Ports are loaded and saved around the call rather than inside it, so the loop
2088
- * stays a pure-ish function of its inputs and the store keeps its single owner.
2089
- */
2090
- async function reconcileWorkspace(workspace, options) {
2091
- const manifest = options.manifest ?? await require_discover.discover({
2092
- patterns: constructGlobs(workspace),
2093
- cwd: workspace.root
2094
- });
2095
- const result = await reconcile({
2096
- root: workspace.root,
2097
- project: workspace.name,
2098
- manifest,
2099
- stage: options.stage,
2100
- localStage: workspace.stages.local,
2101
- ...backendsOf(workspace),
2102
- saved: await loadPortState(workspace.root),
2103
- addresses: surfaceAddresses(workspace, manifest),
2104
- apps: (containers) => appServices(workspace, manifest, containers),
2105
- ...options.start === void 0 ? {} : { start: options.start }
2106
- });
2107
- await savePortState(workspace.root, { ...result.ports });
2108
- return result;
2109
- }
2110
- /**
2111
- * Where each declared surface and site answers locally.
2112
- *
2113
- * The addresses come from the ports the workspace already assigns; which
2114
- * construct sits at which one comes from the manifest. That split is the point:
2115
- * this used to answer "who may call whom" by listing every app the workspace
2116
- * runs, which is a different question that happened to give the same answer in
2117
- * a single-repo workspace and no answer at all deployed. Now it answers only
2118
- * "where does this construct answer", and the graph answers the rest.
2119
- *
2120
- * A site is matched to its app by `path`, because that is the one thing a site
2121
- * declaration and a workspace app both name. Surfaces are matched to the
2122
- * backend app: every `rest-api` in a process answers on that process's port, so
2123
- * an app serving both its own API and an auth server publishes one address
2124
- * twice — which is exactly what it does at runtime.
2125
- */
2126
- function surfaceAddresses(workspace, manifest, at = (_app, port) => localAddress(port)) {
2127
- const addresses = {};
2128
- for (const [id, declaration] of Object.entries(manifest)) {
2129
- if (declaration.kind !== "rest-api" && declaration.kind !== "site") continue;
2130
- const host = declaration.kind === "site" ? require_config.appKey(id) : appKeyOfHost(manifest, id);
2131
- const app = host ? workspace.apps[host] : void 0;
2132
- if (host && app?.port) addresses[id] = at(host, app.port);
2133
- }
2134
- return addresses;
2135
- }
2136
- /** The app key serving a surface, following a mount to its host. */
2137
- function appKeyOfHost(manifest, id) {
2138
- const host = require_config.hostOf(manifest, id);
2139
- return host ? require_config.appKey(host) : void 0;
2140
- }
2141
- /** Where a local process answers, given the port the workspace gave it. */
2142
- function localAddress(port) {
2143
- return `http://localhost:${port}`;
2144
- }
2145
-
2146
- //#endregion
2147
- //#region src/credentials/index.ts
2148
- const logger = console;
2149
- /**
2150
- * Load environment files
2151
- * @internal Exported for testing
2152
- */
2153
- function loadEnvFiles(envConfig, cwd = process.cwd()) {
2154
- const loaded = [];
2155
- const missing = [];
2156
- const envFiles = envConfig ? Array.isArray(envConfig) ? envConfig : [envConfig] : [".env"];
2157
- for (const envFile of envFiles) {
2158
- const envPath = (0, node_path.resolve)(cwd, envFile);
2159
- if ((0, node_fs.existsSync)(envPath)) {
2160
- (0, dotenv.config)({
2161
- path: envPath,
2162
- override: true,
2163
- quiet: true
2164
- });
2165
- loaded.push(envFile);
2166
- } else if (envConfig) missing.push(envFile);
2167
- }
2168
- return {
2169
- loaded,
2170
- missing
2171
- };
2172
- }
2173
- /**
2174
- * Check if a port is available
2175
- * @internal Exported for testing
2176
- */
2177
- async function isPortAvailable(port) {
2178
- return new Promise((resolve$1) => {
2179
- const server = (0, node_net.createServer)();
2180
- server.once("error", (err) => {
2181
- if (err.code === "EADDRINUSE") resolve$1(false);
2182
- else resolve$1(false);
2183
- });
2184
- server.once("listening", () => {
2185
- server.close();
2186
- resolve$1(true);
2187
- });
2188
- server.listen(port);
2189
- });
2190
- }
2191
- /**
2192
- * Find an available port starting from the preferred port
2193
- * @internal Exported for testing
2194
- */
2195
- async function findAvailablePort(preferredPort, maxAttempts = 10) {
2196
- for (let i = 0; i < maxAttempts; i++) {
2197
- const port = preferredPort + i;
2198
- if (await isPortAvailable(port)) return port;
2199
- logger.log(`⚠️ Port ${port} is in use, trying ${port + 1}...`);
2200
- }
2201
- throw new Error(`Could not find an available port after trying ${maxAttempts} ports starting from ${preferredPort}`);
2202
- }
2203
- const PORT_STATE_PATH = ".gkm/ports.json";
2204
- /**
2205
- * Parse docker-compose.yml and extract all port mappings that use env var interpolation.
2206
- * Entries like `'${POSTGRES_HOST_PORT:-5432}:5432'` are captured.
2207
- * Fixed port mappings like `'5050:80'` are skipped.
2208
- * @internal Exported for testing
2209
- */
2210
- function parseComposePortMappings(composePath) {
2211
- if (!(0, node_fs.existsSync)(composePath)) return [];
2212
- const content = (0, node_fs.readFileSync)(composePath, "utf-8");
2213
- const compose = (0, yaml.parse)(content);
2214
- if (!compose?.services) return [];
2215
- const results = [];
2216
- for (const [serviceName, serviceConfig] of Object.entries(compose.services)) for (const portMapping of serviceConfig?.ports ?? []) {
2217
- const match = String(portMapping).match(/\$\{(\w+):-(\d+)\}:(\d+)/);
2218
- if (match?.[1] && match[2] && match[3]) results.push({
2219
- service: serviceName,
2220
- envVar: match[1],
2221
- defaultPort: Number(match[2]),
2222
- containerPort: Number(match[3])
2223
- });
2224
- }
2225
- return results;
2226
- }
2227
- /**
2228
- * Load saved port state from .gkm/ports.json.
2229
- * @internal Exported for testing
2230
- */
2231
- async function loadPortState(workspaceRoot) {
2232
- try {
2233
- const raw = await (0, node_fs_promises.readFile)((0, node_path.join)(workspaceRoot, PORT_STATE_PATH), "utf-8");
2234
- return JSON.parse(raw);
2235
- } catch {
2236
- return {};
2237
- }
2238
- }
2239
- /**
2240
- * Save port state to .gkm/ports.json.
2241
- * @internal Exported for testing
2242
- */
2243
- async function savePortState(workspaceRoot, ports) {
2244
- const dir = (0, node_path.join)(workspaceRoot, ".gkm");
2245
- await (0, node_fs_promises.mkdir)(dir, { recursive: true });
2246
- await (0, node_fs_promises.writeFile)((0, node_path.join)(workspaceRoot, PORT_STATE_PATH), `${JSON.stringify(ports, null, 2)}\n`);
2247
- }
2248
- /**
2249
- * Check if a project's own Docker container is running and return its host port.
2250
- * Uses `docker compose port` scoped to the project's compose file.
2251
- * @internal Exported for testing
2252
- */
2253
- function getContainerHostPort(workspaceRoot, service, containerPort) {
2254
- try {
2255
- const result = (0, node_child_process.execSync)(`docker compose port ${service} ${containerPort}`, {
2256
- cwd: workspaceRoot,
2257
- stdio: "pipe"
2258
- }).toString().trim();
2259
- const match = result.match(/:(\d+)$/);
2260
- return match ? Number(match[1]) : null;
2261
- } catch {
2262
- return null;
2263
- }
2264
- }
2265
- /**
2266
- * Resolve host ports for Docker services by parsing docker-compose.yml.
2267
- * Priority: running container → saved state → find available port.
2268
- * Persists resolved ports to .gkm/ports.json.
2269
- * @internal Exported for testing
2270
- */
2271
- async function resolveServicePorts(workspaceRoot) {
2272
- const composePath = (0, node_path.join)(workspaceRoot, "docker-compose.yml");
2273
- const mappings = parseComposePortMappings(composePath);
2274
- if (mappings.length === 0) return {
2275
- dockerEnv: {},
2276
- ports: {},
2277
- mappings: []
2278
- };
2279
- const savedState = await loadPortState(workspaceRoot);
2280
- const dockerEnv = {};
2281
- const ports = {};
2282
- const assignedPorts = /* @__PURE__ */ new Set();
2283
- logger.log("\n🔌 Resolving service ports...");
2284
- for (const mapping of mappings) {
2285
- const containerPort = getContainerHostPort(workspaceRoot, mapping.service, mapping.containerPort);
2286
- if (containerPort !== null) {
2287
- ports[mapping.envVar] = containerPort;
2288
- dockerEnv[mapping.envVar] = String(containerPort);
2289
- assignedPorts.add(containerPort);
2290
- logger.log(` 🔄 ${mapping.service}:${mapping.containerPort}: reusing existing container on port ${containerPort}`);
2291
- continue;
2292
- }
2293
- const savedPort = savedState[mapping.envVar];
2294
- if (savedPort && !assignedPorts.has(savedPort) && await isPortAvailable(savedPort)) {
2295
- ports[mapping.envVar] = savedPort;
2296
- dockerEnv[mapping.envVar] = String(savedPort);
2297
- assignedPorts.add(savedPort);
2298
- logger.log(` 💾 ${mapping.service}:${mapping.containerPort}: using saved port ${savedPort}`);
2299
- continue;
2300
- }
2301
- let resolvedPort = await findAvailablePort(mapping.defaultPort);
2302
- while (assignedPorts.has(resolvedPort)) resolvedPort = await findAvailablePort(resolvedPort + 1);
2303
- ports[mapping.envVar] = resolvedPort;
2304
- dockerEnv[mapping.envVar] = String(resolvedPort);
2305
- assignedPorts.add(resolvedPort);
2306
- if (resolvedPort !== mapping.defaultPort) logger.log(` ⚡ ${mapping.service}:${mapping.containerPort}: port ${mapping.defaultPort} occupied, using port ${resolvedPort}`);
2307
- else logger.log(` ✅ ${mapping.service}:${mapping.containerPort}: using default port ${resolvedPort}`);
2308
- }
2309
- await savePortState(workspaceRoot, ports);
2310
- return {
2311
- dockerEnv,
2312
- ports,
2313
- mappings
2314
- };
2315
- }
2316
- /**
2317
- * Replace a port in a URL string.
2318
- * Handles both `hostname:port` and `localhost:port` patterns.
2319
- * @internal Exported for testing
2320
- */
2321
- function replacePortInUrl(url, oldPort, newPort) {
2322
- if (oldPort === newPort) return url;
2323
- let result = url.replace(new RegExp(`:${oldPort}(?=[/?#]|$)`, "g"), `:${newPort}`);
2324
- result = result.replace(new RegExp(`%3A${oldPort}(?=[%/?#&]|$)`, "gi"), `%3A${newPort}`);
2325
- return result;
2326
- }
2327
- /**
2328
- * Rewrite connection URLs and port vars in secrets with resolved ports.
2329
- * Uses the parsed compose mappings to determine which default ports to replace.
2330
- * Pure transform — does not modify secrets on disk.
2331
- * @internal Exported for testing
2332
- */
2333
- function rewriteUrlsWithPorts(secrets, resolvedPorts) {
2334
- const { ports, mappings } = resolvedPorts;
2335
- const result = { ...secrets };
2336
- const portReplacements = [];
2337
- const serviceNames = /* @__PURE__ */ new Set();
2338
- for (const mapping of mappings) {
2339
- serviceNames.add(mapping.service);
2340
- const resolved = ports[mapping.envVar];
2341
- if (resolved !== void 0) portReplacements.push({
2342
- defaultPort: mapping.defaultPort,
2343
- resolvedPort: resolved
2344
- });
2345
- }
2346
- for (const [key, value] of Object.entries(result)) {
2347
- if (!key.endsWith("_HOST")) continue;
2348
- if (serviceNames.has(value)) result[key] = "localhost";
2349
- }
2350
- for (const [key, value] of Object.entries(result)) {
2351
- if (!key.endsWith("_PORT")) continue;
2352
- for (const { defaultPort, resolvedPort } of portReplacements) if (value === String(defaultPort)) result[key] = String(resolvedPort);
2353
- }
2354
- for (const [key, value] of Object.entries(result)) {
2355
- if (!key.endsWith("_URL") && !key.endsWith("_ENDPOINT") && !key.endsWith("_CONNECTION_STRING") && key !== "DATABASE_URL") continue;
2356
- let rewritten = value;
2357
- for (const name of serviceNames) rewritten = rewritten.replace(new RegExp(`@${name}:`, "g"), "@localhost:");
2358
- for (const { defaultPort, resolvedPort } of portReplacements) rewritten = replacePortInUrl(rewritten, defaultPort, resolvedPort);
2359
- result[key] = rewritten;
2360
- }
2361
- return result;
2362
- }
2363
- /**
2364
- * Build the environment variables to pass to `docker compose up`.
2365
- * Merges process.env, secrets, and port mappings so that Docker Compose
2366
- * can interpolate variables like ${POSTGRES_USER} correctly.
2367
- * @internal Exported for testing
2368
- */
2369
- function buildDockerComposeEnv(secretsEnv, portEnv) {
2370
- return {
2371
- ...process.env,
2372
- ...secretsEnv,
2373
- ...portEnv
2374
- };
2375
- }
2376
- /**
2377
- * Parse all service names from a docker-compose.yml file.
2378
- * @internal Exported for testing
2379
- */
2380
- function parseComposeServiceNames(composePath) {
2381
- if (!(0, node_fs.existsSync)(composePath)) return [];
2382
- const content = (0, node_fs.readFileSync)(composePath, "utf-8");
2383
- const compose = (0, yaml.parse)(content);
2384
- return Object.keys(compose?.services ?? {});
2385
- }
2386
- /**
2387
- * Start docker-compose services for a single-app project (no workspace config).
2388
- * Starts all services defined in docker-compose.yml.
2389
- */
2390
- async function startComposeServices(cwd, portEnv, secretsEnv) {
2391
- const composeFile = (0, node_path.join)(cwd, "docker-compose.yml");
2392
- if (!(0, node_fs.existsSync)(composeFile)) return;
2393
- const servicesToStart = parseComposeServiceNames(composeFile);
2394
- if (servicesToStart.length === 0) return;
2395
- logger.log(`🐳 Starting services: ${servicesToStart.join(", ")}`);
2396
- try {
2397
- (0, node_child_process.execSync)(`docker compose up -d ${servicesToStart.join(" ")}`, {
2398
- cwd,
2399
- stdio: "inherit",
2400
- env: buildDockerComposeEnv(secretsEnv, portEnv)
2401
- });
2402
- logger.log("✅ Services started");
2403
- } catch (error) {
2404
- logger.error("❌ Failed to start services:", error.message);
2405
- throw error;
2406
- }
2407
- }
2408
- /**
2409
- * Start docker-compose services for a workspace.
2410
- * Discovers all services from docker-compose.yml and starts everything
2411
- * except app services (which are managed by turbo).
2412
- * @internal Exported for testing
2413
- */
2414
- async function startWorkspaceServices(workspace, portEnv, secretsEnv) {
2415
- const composeFile = (0, node_path.join)(workspace.root, "docker-compose.yml");
2416
- if (!(0, node_fs.existsSync)(composeFile)) return;
2417
- const allServices = parseComposeServiceNames(composeFile);
2418
- const appNames = new Set(Object.keys(workspace.apps));
2419
- const servicesToStart = allServices.filter((name) => !appNames.has(name));
2420
- if (servicesToStart.length === 0) return;
2421
- logger.log(`🐳 Starting services: ${servicesToStart.join(", ")}`);
2422
- try {
2423
- (0, node_child_process.execSync)(`docker compose up -d ${servicesToStart.join(" ")}`, {
2424
- cwd: workspace.root,
2425
- stdio: "inherit",
2426
- env: buildDockerComposeEnv(secretsEnv, portEnv)
2427
- });
2428
- logger.log("✅ Services started");
2429
- } catch (error) {
2430
- logger.error("❌ Failed to start services:", error.message);
2431
- throw error;
2432
- }
2433
- }
2434
- /**
2435
- * Load and flatten secrets for an app from encrypted storage.
2436
- * For workspace app: maps {APP}_DATABASE_URL → DATABASE_URL.
2437
- * @internal Exported for testing
2438
- */
2439
- async function loadSecretsForApp(secretsRoot, stage, appName) {
2440
- let secrets = {};
2441
- if (require_storage.secretsExist(stage, secretsRoot)) {
2442
- const stageSecrets = await require_storage.readStageSecrets(stage, secretsRoot);
2443
- if (stageSecrets) {
2444
- logger.log(`🔐 Loading secrets from stage: ${stage}`);
2445
- secrets = require_storage.toEmbeddableSecrets(stageSecrets);
2446
- }
2447
- }
2448
- if (Object.keys(secrets).length === 0) return {};
2449
- if (!appName) return secrets;
2450
- const prefix = appName.toUpperCase();
2451
- const mapped = { ...secrets };
2452
- const appDbUrl = secrets[`${prefix}_DATABASE_URL`];
2453
- if (appDbUrl) mapped.DATABASE_URL = appDbUrl;
2454
- return mapped;
2455
- }
2456
- /**
2457
- * Walk up the directory tree to find the root containing .gkm/secrets/.
2458
- * @internal Exported for testing
2459
- */
2460
- function findSecretsRoot(startDir) {
2461
- let dir = startDir;
2462
- while (dir !== "/") {
2463
- if ((0, node_fs.existsSync)((0, node_path.join)(dir, ".gkm", "secrets"))) return dir;
2464
- const parent = (0, node_path.dirname)(dir);
2465
- if (parent === dir) break;
2466
- dir = parent;
2467
- }
2468
- return startDir;
2469
- }
2470
- /**
2471
- * Generate the credentials injection code snippet.
2472
- * This is the common logic used by both entry wrapper and exec preload.
2473
- * @internal
2474
- */
2475
- function generateCredentialsInjection(secretsJsonPath) {
2476
- return `import { existsSync, readFileSync } from 'node:fs';
2477
-
2478
- // Inject dev secrets via globalThis and process.env
2479
- // Using globalThis.__gkm_credentials__ avoids CJS/ESM interop issues where
2480
- // Object.assign on the Credentials export only mutates one module copy.
2481
- const secretsPath = '${secretsJsonPath}';
2482
- if (existsSync(secretsPath)) {
2483
- const secrets = JSON.parse(readFileSync(secretsPath, 'utf-8'));
2484
- globalThis.__gkm_credentials__ = secrets;
2485
- Object.assign(process.env, secrets);
2486
- }
2487
- `;
2488
- }
2489
- /**
2490
- * Create a preload script that injects secrets into Credentials.
2491
- * Used by `gkm exec` to inject secrets before running any command.
2492
- * @internal Exported for testing
2493
- */
2494
- async function createCredentialsPreload(preloadPath, secretsJsonPath) {
2495
- const content = `/**
2496
- * Credentials preload generated by 'gkm exec'
2497
- * This file is loaded via NODE_OPTIONS="--import <path>"
2498
- */
2499
- ${generateCredentialsInjection(secretsJsonPath)}`;
2500
- await (0, node_fs_promises.writeFile)(preloadPath, content);
2501
- }
2502
- /**
2503
- * Create a wrapper script that injects secrets before importing the entry file.
2504
- * @internal Exported for testing
2505
- */
2506
- async function createEntryWrapper(wrapperPath, entryPath, secretsJsonPath) {
2507
- const credentialsInjection = secretsJsonPath ? `${generateCredentialsInjection(secretsJsonPath)}
2508
- ` : "";
2509
- const content = `#!/usr/bin/env node
2510
- /**
2511
- * Entry wrapper generated by 'gkm dev --entry'
2512
- */
2513
- ${credentialsInjection}// Import and run the user's entry file (dynamic import ensures secrets load first)
2514
- await import('${entryPath}');
2515
- `;
2516
- await (0, node_fs_promises.writeFile)(wrapperPath, content);
2517
- }
2518
- /**
2519
- * Prepare credentials for dev/exec/test modes.
2520
- * Loads workspace config, secrets, resolves Docker ports, rewrites URLs,
2521
- * injects PORT, dependency URLs, and writes credentials JSON.
2522
- *
2523
- * @param options.resolveDockerPorts - How to resolve Docker ports:
2524
- * - `'full'` (default): probe running containers, saved state, then find available ports. Used by dev/test.
2525
- * - `'readonly'`: check running containers and saved state only, never probe for new ports. Used by exec.
2526
- * @param options.stage - The stage whose secrets to load. Default: the project's `stages.local`.
2527
- * @param options.startDocker - Start Docker Compose services after port resolution. Default: false.
2528
- * @param options.secretsFileName - Custom secrets JSON filename. Default: 'dev-secrets-{appName}.json' or 'dev-secrets.json'.
2529
- * @internal Exported for testing
2530
- */
2531
- async function prepareEntryCredentials(options) {
2532
- const cwd = options.cwd ?? process.cwd();
2533
- const portMode = options.resolveDockerPorts ?? "full";
2534
- let workspaceAppPort;
2535
- let secretsRoot = cwd;
2536
- let appName;
2537
- let appInfo;
2538
- try {
2539
- appInfo = await require_config.loadWorkspaceAppInfo(cwd);
2540
- workspaceAppPort = appInfo.app.port;
2541
- secretsRoot = appInfo.workspaceRoot;
2542
- appName = appInfo.appName;
2543
- } catch {
2544
- secretsRoot = findSecretsRoot(cwd);
2545
- appName = require_config.getAppNameFromCwd(cwd) ?? void 0;
2546
- }
2547
- const resolvedPort = options.explicitPort ?? workspaceAppPort ?? 3e3;
2548
- const stage = options.stage ?? appInfo?.workspace.stages.local;
2549
- const credentials = stage ? await loadSecretsForApp(secretsRoot, stage, appName) : {};
2550
- credentials.PORT = String(resolvedPort);
2551
- const declaredKeys = [];
2552
- if (appInfo && usesConstructs(appInfo.workspace)) {
2553
- const { reconcileWorkspace: reconcileWorkspace$1 } = await Promise.resolve().then(() => require("./workspace-Cji6lE8E.cjs"));
2554
- const reconciled = await reconcileWorkspace$1(appInfo.workspace, {
2555
- stage: options.reconcileStage ?? appInfo.workspace.stages.local,
2556
- start: options.startDocker ?? false
2557
- });
2558
- Object.assign(credentials, reconciled.env);
2559
- declaredKeys.push(...Object.keys(reconciled.env));
2560
- if (Object.keys(reconciled.env).length > 0) logger.log(`🔌 Resolved ${Object.keys(reconciled.env).length} declared URL(s)`);
2561
- } else {
2562
- const composePath = (0, node_path.join)(secretsRoot, "docker-compose.yml");
2563
- const mappings = parseComposePortMappings(composePath);
2564
- if (mappings.length > 0) {
2565
- let resolvedPorts;
2566
- if (portMode === "full") resolvedPorts = await resolveServicePorts(secretsRoot);
2567
- else {
2568
- const savedPorts = await loadPortState(secretsRoot);
2569
- const ports = {};
2570
- for (const mapping of mappings) {
2571
- const containerPort = getContainerHostPort(secretsRoot, mapping.service, mapping.containerPort);
2572
- if (containerPort !== null) ports[mapping.envVar] = containerPort;
2573
- else {
2574
- const saved = savedPorts[mapping.envVar];
2575
- if (saved !== void 0) ports[mapping.envVar] = saved;
2576
- }
2577
- }
2578
- resolvedPorts = {
2579
- dockerEnv: {},
2580
- ports,
2581
- mappings
2582
- };
2583
- }
2584
- if (options.startDocker) if (appInfo) await startWorkspaceServices(appInfo.workspace, resolvedPorts.dockerEnv, credentials);
2585
- else await startComposeServices(secretsRoot, resolvedPorts.dockerEnv, credentials);
2586
- if (Object.keys(resolvedPorts.ports).length > 0) {
2587
- const rewritten = rewriteUrlsWithPorts(credentials, resolvedPorts);
2588
- Object.assign(credentials, rewritten);
2589
- logger.log(`🔌 Applied ${Object.keys(resolvedPorts.ports).length} port mapping(s)`);
2590
- }
2591
- }
2592
- }
2593
- if (appInfo?.appName) {
2594
- const depEnv = require_workspace.getDependencyEnvVars(appInfo.workspace, appInfo.appName);
2595
- Object.assign(credentials, depEnv);
2596
- }
2597
- if (!credentials.EVENT_PUBLISHER_CONNECTION_STRING && !credentials.EVENT_SUBSCRIBER_CONNECTION_STRING && credentials.PGBOSS_DB_USER) {
2598
- const pgbossUrl = require_generator.generatePgBossUrl({
2599
- username: credentials.PGBOSS_DB_USER,
2600
- password: credentials.PGBOSS_DB_PASSWORD ?? "",
2601
- host: credentials.POSTGRES_HOST ?? "localhost",
2602
- port: Number(credentials.POSTGRES_PORT ?? "5432"),
2603
- database: credentials.POSTGRES_DB ?? "app"
2604
- });
2605
- credentials.EVENT_PUBLISHER_CONNECTION_STRING = pgbossUrl;
2606
- credentials.EVENT_SUBSCRIBER_CONNECTION_STRING = pgbossUrl;
2607
- }
2608
- const secretsDir = (0, node_path.join)(secretsRoot, ".gkm");
2609
- await (0, node_fs_promises.mkdir)(secretsDir, { recursive: true });
2610
- const secretsFileName = options.secretsFileName ?? (appName ? `dev-secrets-${appName}.json` : "dev-secrets.json");
2611
- const secretsJsonPath = (0, node_path.join)(secretsDir, secretsFileName);
2612
- await (0, node_fs_promises.writeFile)(secretsJsonPath, JSON.stringify(credentials, null, 2));
2613
- return {
2614
- credentials,
2615
- resolvedPort,
2616
- secretsJsonPath,
2617
- appName,
2618
- secretsRoot,
2619
- appInfo,
2620
- declaredKeys
2621
- };
2622
- }
2623
-
2624
- //#endregion
2625
- Object.defineProperty(exports, 'COMPOSE_PATH', {
2626
- enumerable: true,
2627
- get: function () {
2628
- return COMPOSE_PATH;
2629
- }
2630
- });
2631
- Object.defineProperty(exports, 'LOCAL_CA_PATH', {
2632
- enumerable: true,
2633
- get: function () {
2634
- return LOCAL_CA_PATH;
2635
- }
2636
- });
2637
- Object.defineProperty(exports, 'applyPostgres', {
2638
- enumerable: true,
2639
- get: function () {
2640
- return applyPostgres;
2641
- }
2642
- });
2643
- Object.defineProperty(exports, 'backendsOf', {
2644
- enumerable: true,
2645
- get: function () {
2646
- return backendsOf;
2647
- }
2648
- });
2649
- Object.defineProperty(exports, 'cacheBackendFor', {
2650
- enumerable: true,
2651
- get: function () {
2652
- return cacheBackendFor;
2653
- }
2654
- });
2655
- Object.defineProperty(exports, 'constructGlobs', {
2656
- enumerable: true,
2657
- get: function () {
2658
- return constructGlobs;
2659
- }
2660
- });
2661
- Object.defineProperty(exports, 'createCredentialsPreload', {
2662
- enumerable: true,
2663
- get: function () {
2664
- return createCredentialsPreload;
2665
- }
2666
- });
2667
- Object.defineProperty(exports, 'createEntryWrapper', {
2668
- enumerable: true,
2669
- get: function () {
2670
- return createEntryWrapper;
2671
- }
2672
- });
2673
- Object.defineProperty(exports, 'derivedContainers', {
2674
- enumerable: true,
2675
- get: function () {
2676
- return derivedContainers;
2677
- }
2678
- });
2679
- Object.defineProperty(exports, 'eventsBackendFor', {
2680
- enumerable: true,
2681
- get: function () {
2682
- return eventsBackendFor;
2683
- }
2684
- });
2685
- Object.defineProperty(exports, 'findAvailablePort', {
2686
- enumerable: true,
2687
- get: function () {
2688
- return findAvailablePort;
2689
- }
2690
- });
2691
- Object.defineProperty(exports, 'isPortAvailable', {
2692
- enumerable: true,
2693
- get: function () {
2694
- return isPortAvailable;
2695
- }
2696
- });
2697
- Object.defineProperty(exports, 'loadEnvFiles', {
2698
- enumerable: true,
2699
- get: function () {
2700
- return loadEnvFiles;
2701
- }
2702
- });
2703
- Object.defineProperty(exports, 'loadSecretsForApp', {
2704
- enumerable: true,
2705
- get: function () {
2706
- return loadSecretsForApp;
2707
- }
2708
- });
2709
- Object.defineProperty(exports, 'prepareEntryCredentials', {
2710
- enumerable: true,
2711
- get: function () {
2712
- return prepareEntryCredentials;
2713
- }
2714
- });
2715
- Object.defineProperty(exports, 'providerOf', {
2716
- enumerable: true,
2717
- get: function () {
2718
- return providerOf;
2719
- }
2720
- });
2721
- Object.defineProperty(exports, 'reconcileWorkspace', {
2722
- enumerable: true,
2723
- get: function () {
2724
- return reconcileWorkspace;
2725
- }
2726
- });
2727
- Object.defineProperty(exports, 'resolveServicePorts', {
2728
- enumerable: true,
2729
- get: function () {
2730
- return resolveServicePorts;
2731
- }
2732
- });
2733
- Object.defineProperty(exports, 'resourceName', {
2734
- enumerable: true,
2735
- get: function () {
2736
- return resourceName;
2737
- }
2738
- });
2739
- Object.defineProperty(exports, 'rewriteUrlsWithPorts', {
2740
- enumerable: true,
2741
- get: function () {
2742
- return rewriteUrlsWithPorts;
2743
- }
2744
- });
2745
- Object.defineProperty(exports, 'startWorkspaceServices', {
2746
- enumerable: true,
2747
- get: function () {
2748
- return startWorkspaceServices;
2749
- }
2750
- });
2751
- Object.defineProperty(exports, 'storageBackendFor', {
2752
- enumerable: true,
2753
- get: function () {
2754
- return storageBackendFor;
2755
- }
2756
- });
2757
- Object.defineProperty(exports, 'surfaceAddresses', {
2758
- enumerable: true,
2759
- get: function () {
2760
- return surfaceAddresses;
2761
- }
2762
- });
2763
- Object.defineProperty(exports, 'usesConstructs', {
2764
- enumerable: true,
2765
- get: function () {
2766
- return usesConstructs;
2767
- }
2768
- });
2769
- //# sourceMappingURL=credentials-DQRvPz2S.cjs.map