@geekmidas/cli 10.0.0-alpha.5 → 10.0.0-alpha.51

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 (267) hide show
  1. package/README.md +196 -257
  2. package/bin/adjacent-tsconfig.mjs +97 -0
  3. package/bin/gkm.mjs +16 -2
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/{HostingerProvider-h3EbEp-Z.cjs → HostingerProvider-BZFGYYVA.cjs} +21 -22
  7. package/dist/HostingerProvider-BZFGYYVA.cjs.map +1 -0
  8. package/dist/{HostingerProvider-Cft7lEYr.mjs → HostingerProvider-GF6NAZAK.mjs} +20 -21
  9. package/dist/HostingerProvider-GF6NAZAK.mjs.map +1 -0
  10. package/dist/{LocalStateProvider-Db9SEjyH.cjs → LocalStateProvider-7HR6SS2t.cjs} +11 -6
  11. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +1 -0
  12. package/dist/{LocalStateProvider-Bn6tS-oL.mjs → LocalStateProvider-D7QyJoLM.mjs} +10 -4
  13. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +1 -0
  14. package/dist/{openapi-CA0yJUTN.cjs → OpenApiTsGenerator-BN0PIZxd.cjs} +157 -372
  15. package/dist/OpenApiTsGenerator-BN0PIZxd.cjs.map +1 -0
  16. package/dist/{openapi-kkQbsRVj.mjs → OpenApiTsGenerator-BzIGy8KE.mjs} +128 -324
  17. package/dist/OpenApiTsGenerator-BzIGy8KE.mjs.map +1 -0
  18. package/dist/{Route53Provider-RdpUDJQk.mjs → Route53Provider-Cvj40A8I.mjs} +12 -12
  19. package/dist/Route53Provider-Cvj40A8I.mjs.map +1 -0
  20. package/dist/{Route53Provider-di2fMM5N.cjs → Route53Provider-DVILBsvV.cjs} +20 -21
  21. package/dist/Route53Provider-DVILBsvV.cjs.map +1 -0
  22. package/dist/{SSMStateProvider-BRt2py-A.mjs → SSMStateProvider-B0Hu1MKZ.mjs} +13 -4
  23. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +1 -0
  24. package/dist/{SSMStateProvider-DyX8s9HI.cjs → SSMStateProvider-VrQ-yeqd.cjs} +17 -9
  25. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +1 -0
  26. package/dist/aws-DkHdTV-p.cjs +61 -0
  27. package/dist/aws-DkHdTV-p.cjs.map +1 -0
  28. package/dist/aws-DojzQnLd.mjs +61 -0
  29. package/dist/aws-DojzQnLd.mjs.map +1 -0
  30. package/dist/backends-B9V2XD2M.cjs +82 -0
  31. package/dist/backends-B9V2XD2M.cjs.map +1 -0
  32. package/dist/backends-CSuLl0YP.mjs +59 -0
  33. package/dist/backends-CSuLl0YP.mjs.map +1 -0
  34. package/dist/{backup-provisioner-BrsHwYG0.cjs → backup-provisioner-BmhIO_Yr.cjs} +21 -19
  35. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +1 -0
  36. package/dist/{backup-provisioner-Bgj5Vi_L.mjs → backup-provisioner-DIVCbfee.mjs} +10 -7
  37. package/dist/backup-provisioner-DIVCbfee.mjs.map +1 -0
  38. package/dist/{bundler-Be8Zg4Wd.mjs → bundler--fyybf1N.mjs} +19 -30
  39. package/dist/bundler--fyybf1N.mjs.map +1 -0
  40. package/dist/{bundler-BY1OmV1e.cjs → bundler-By6_sXiL.cjs} +20 -32
  41. package/dist/bundler-By6_sXiL.cjs.map +1 -0
  42. package/dist/{config-C21ocYNd.cjs → config-Cvr5fCbn.cjs} +210 -210
  43. package/dist/config-Cvr5fCbn.cjs.map +1 -0
  44. package/dist/{config-WRdsQYZK.mjs → config-SOkDH-n1.mjs} +143 -154
  45. package/dist/config-SOkDH-n1.mjs.map +1 -0
  46. package/dist/config.cjs +9 -6
  47. package/dist/config.d.cts +62 -33
  48. package/dist/config.d.cts.map +1 -1
  49. package/dist/config.d.mts +62 -33
  50. package/dist/config.d.mts.map +1 -1
  51. package/dist/config.mjs +3 -5
  52. package/dist/deploy/sniffer-envkit-patch.cjs +18 -10
  53. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  54. package/dist/deploy/sniffer-envkit-patch.d.cts +0 -2
  55. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  56. package/dist/deploy/sniffer-envkit-patch.d.mts +0 -2
  57. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  58. package/dist/deploy/sniffer-envkit-patch.mjs +10 -2
  59. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  60. package/dist/deploy/sniffer-hooks.cjs +13 -7
  61. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  62. package/dist/deploy/sniffer-hooks.d.cts +1 -2
  63. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  64. package/dist/deploy/sniffer-hooks.d.mts +1 -2
  65. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  66. package/dist/deploy/sniffer-hooks.mjs +9 -2
  67. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  68. package/dist/deploy/sniffer-loader.cjs +16 -7
  69. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  70. package/dist/deploy/sniffer-loader.d.cts +1 -1
  71. package/dist/deploy/sniffer-loader.d.mts +1 -1
  72. package/dist/deploy/sniffer-loader.mjs +13 -2
  73. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  74. package/dist/deploy/sniffer-routes-worker.cjs +11 -11
  75. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  76. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  77. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  78. package/dist/deploy/sniffer-routes-worker.mjs +3 -3
  79. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  80. package/dist/deploy/sniffer-worker.cjs +15 -6
  81. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  82. package/dist/deploy/sniffer-worker.d.cts +1 -3
  83. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  84. package/dist/deploy/sniffer-worker.d.mts +1 -3
  85. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  86. package/dist/deploy/sniffer-worker.mjs +15 -4
  87. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  88. package/dist/{discover-CAlFgYec.mjs → discover-Cf2jAcgF.mjs} +56 -63
  89. package/dist/discover-Cf2jAcgF.mjs.map +1 -0
  90. package/dist/{discover-DTmFeloL.cjs → discover-DXNviAh-.cjs} +86 -110
  91. package/dist/discover-DXNviAh-.cjs.map +1 -0
  92. package/dist/{emit-CiZS_5Ub.mjs → emit-C1e8qD08.mjs} +13 -26
  93. package/dist/emit-C1e8qD08.mjs.map +1 -0
  94. package/dist/{emit-CbcRolsa.cjs → emit-Dmc1nvdS.cjs} +31 -57
  95. package/dist/emit-Dmc1nvdS.cjs.map +1 -0
  96. package/dist/encryption-Bt8SHRI6.cjs +91 -0
  97. package/dist/encryption-Bt8SHRI6.cjs.map +1 -0
  98. package/dist/encryption-DRCXp-U4.mjs +90 -0
  99. package/dist/encryption-DRCXp-U4.mjs.map +1 -0
  100. package/dist/github-BGx4U61b.cjs +213 -0
  101. package/dist/github-BGx4U61b.cjs.map +1 -0
  102. package/dist/github-U_frvZgD.mjs +213 -0
  103. package/dist/github-U_frvZgD.mjs.map +1 -0
  104. package/dist/{index-CHB4tSzX.d.cts → index-DYh5TrsZ.d.mts} +4 -23
  105. package/dist/index-DYh5TrsZ.d.mts.map +1 -0
  106. package/dist/{index-BThUzEIp.d.mts → index-fU3qHy7c.d.cts} +4 -23
  107. package/dist/index-fU3qHy7c.d.cts.map +1 -0
  108. package/dist/index.cjs +9561 -7232
  109. package/dist/index.cjs.map +1 -1
  110. package/dist/index.d.cts +1 -1
  111. package/dist/index.d.mts +1 -1
  112. package/dist/index.mjs +9479 -7177
  113. package/dist/index.mjs.map +1 -1
  114. package/dist/migrate-dx4I0epp.cjs +743 -0
  115. package/dist/migrate-dx4I0epp.cjs.map +1 -0
  116. package/dist/migrate-soUQtku3.mjs +736 -0
  117. package/dist/migrate-soUQtku3.mjs.map +1 -0
  118. package/dist/openapi.cjs +198 -8
  119. package/dist/openapi.cjs.map +1 -0
  120. package/dist/openapi.d.cts +53 -15
  121. package/dist/openapi.d.cts.map +1 -1
  122. package/dist/openapi.d.mts +53 -15
  123. package/dist/openapi.d.mts.map +1 -1
  124. package/dist/openapi.mjs +193 -5
  125. package/dist/openapi.mjs.map +1 -0
  126. package/dist/ready-WfT-eWlm.mjs +861 -0
  127. package/dist/ready-WfT-eWlm.mjs.map +1 -0
  128. package/dist/ready-lr2Fm-ep.cjs +932 -0
  129. package/dist/ready-lr2Fm-ep.cjs.map +1 -0
  130. package/dist/reconcile/public.cjs +3 -5
  131. package/dist/reconcile/public.d.cts +30 -33
  132. package/dist/reconcile/public.d.cts.map +1 -1
  133. package/dist/reconcile/public.d.mts +30 -33
  134. package/dist/reconcile/public.d.mts.map +1 -1
  135. package/dist/reconcile/public.mjs +3 -4
  136. package/dist/{reconcile-CFs8C_1a.mjs → reconcile--I7V4Klj.mjs} +4 -7
  137. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  138. package/dist/{reconcile-D0pimNiy.cjs → reconcile-CuCQBa5-.cjs} +5 -8
  139. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  140. package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
  141. package/dist/{chunk-CUT6urMc.cjs → rolldown-runtime-C0BPl7ul.cjs} +23 -10
  142. package/dist/storage-BzaUxmqe.mjs +124 -0
  143. package/dist/storage-BzaUxmqe.mjs.map +1 -0
  144. package/dist/storage-CSGoC3bK.cjs +152 -0
  145. package/dist/storage-CSGoC3bK.cjs.map +1 -0
  146. package/dist/store-DQgxT_WR.cjs +211 -0
  147. package/dist/store-DQgxT_WR.cjs.map +1 -0
  148. package/dist/store-DeGATCS-.mjs +182 -0
  149. package/dist/store-DeGATCS-.mjs.map +1 -0
  150. package/dist/types-CT0ymlBk.d.mts +6230 -0
  151. package/dist/types-CT0ymlBk.d.mts.map +1 -0
  152. package/dist/types-DYDT4FfE.d.cts +6231 -0
  153. package/dist/types-DYDT4FfE.d.cts.map +1 -0
  154. package/dist/vitest.cjs +65 -0
  155. package/dist/vitest.cjs.map +1 -0
  156. package/dist/vitest.d.cts +29 -0
  157. package/dist/vitest.d.cts.map +1 -0
  158. package/dist/vitest.d.mts +29 -0
  159. package/dist/vitest.d.mts.map +1 -0
  160. package/dist/vitest.mjs +65 -0
  161. package/dist/vitest.mjs.map +1 -0
  162. package/dist/workspace/index.cjs +3 -4
  163. package/dist/workspace/index.d.cts +3 -3
  164. package/dist/workspace/index.d.mts +3 -3
  165. package/dist/workspace/index.mjs +2 -3
  166. package/dist/{workspace-BcucjwvA.cjs → workspace-BcCiLzTO.cjs} +1040 -1120
  167. package/dist/workspace-BcCiLzTO.cjs.map +1 -0
  168. package/dist/{credentials-BBIRJVp4.mjs → workspace-Dp2zK_Nk.mjs} +2212 -1732
  169. package/dist/workspace-Dp2zK_Nk.mjs.map +1 -0
  170. package/dist/{credentials-G1JwBoXH.cjs → workspace-GBzR_hID.cjs} +2348 -1849
  171. package/dist/workspace-GBzR_hID.cjs.map +1 -0
  172. package/dist/{workspace-BFMrAKqI.mjs → workspace-bOsks1uk.mjs} +871 -974
  173. package/dist/workspace-bOsks1uk.mjs.map +1 -0
  174. package/package.json +29 -20
  175. package/dist/CachedStateProvider-BLo7zv7S.cjs +0 -3
  176. package/dist/CachedStateProvider-BxoAm-B2.mjs +0 -3
  177. package/dist/CachedStateProvider-CqPdW7CB.cjs +0 -60
  178. package/dist/CachedStateProvider-CqPdW7CB.cjs.map +0 -1
  179. package/dist/CachedStateProvider-DTniehMP.mjs +0 -54
  180. package/dist/CachedStateProvider-DTniehMP.mjs.map +0 -1
  181. package/dist/HostingerProvider-Cft7lEYr.mjs.map +0 -1
  182. package/dist/HostingerProvider-h3EbEp-Z.cjs.map +0 -1
  183. package/dist/LocalStateProvider-Bn6tS-oL.mjs.map +0 -1
  184. package/dist/LocalStateProvider-Db9SEjyH.cjs.map +0 -1
  185. package/dist/Route53Provider-RdpUDJQk.mjs.map +0 -1
  186. package/dist/Route53Provider-di2fMM5N.cjs.map +0 -1
  187. package/dist/SSMStateProvider-BRt2py-A.mjs.map +0 -1
  188. package/dist/SSMStateProvider-DyX8s9HI.cjs.map +0 -1
  189. package/dist/backup-provisioner-Bgj5Vi_L.mjs.map +0 -1
  190. package/dist/backup-provisioner-BrsHwYG0.cjs.map +0 -1
  191. package/dist/bundler-BY1OmV1e.cjs.map +0 -1
  192. package/dist/bundler-Be8Zg4Wd.mjs.map +0 -1
  193. package/dist/chunk-Duj1WY3L.mjs +0 -7
  194. package/dist/config-C21ocYNd.cjs.map +0 -1
  195. package/dist/config-WRdsQYZK.mjs.map +0 -1
  196. package/dist/credentials-B5zRHdAl.mjs +0 -141
  197. package/dist/credentials-B5zRHdAl.mjs.map +0 -1
  198. package/dist/credentials-BBIRJVp4.mjs.map +0 -1
  199. package/dist/credentials-BapzjyV5.cjs +0 -195
  200. package/dist/credentials-BapzjyV5.cjs.map +0 -1
  201. package/dist/credentials-G1JwBoXH.cjs.map +0 -1
  202. package/dist/discover-CAlFgYec.mjs.map +0 -1
  203. package/dist/discover-DTmFeloL.cjs.map +0 -1
  204. package/dist/dokploy-api-BS2xnJLZ.mjs +0 -3
  205. package/dist/dokploy-api-BsVH0y_s.cjs +0 -718
  206. package/dist/dokploy-api-BsVH0y_s.cjs.map +0 -1
  207. package/dist/dokploy-api-BuxDRo3l.cjs +0 -3
  208. package/dist/dokploy-api-aTFPz7_4.mjs +0 -706
  209. package/dist/dokploy-api-aTFPz7_4.mjs.map +0 -1
  210. package/dist/emit-CbcRolsa.cjs.map +0 -1
  211. package/dist/emit-CiZS_5Ub.mjs.map +0 -1
  212. package/dist/encryption-C6jaU0hE.cjs +0 -54
  213. package/dist/encryption-C6jaU0hE.cjs.map +0 -1
  214. package/dist/encryption-CHzzeR8a.cjs +0 -4
  215. package/dist/encryption-CQUncu7v.mjs +0 -3
  216. package/dist/encryption-D-abyhZx.mjs +0 -42
  217. package/dist/encryption-D-abyhZx.mjs.map +0 -1
  218. package/dist/fullstack-secrets-C-GGohke.cjs +0 -111
  219. package/dist/fullstack-secrets-C-GGohke.cjs.map +0 -1
  220. package/dist/fullstack-secrets-D1o9-G5l.mjs +0 -87
  221. package/dist/fullstack-secrets-D1o9-G5l.mjs.map +0 -1
  222. package/dist/generator-CNzBw7g5.cjs +0 -289
  223. package/dist/generator-CNzBw7g5.cjs.map +0 -1
  224. package/dist/generator-VE2JrFlY.mjs +0 -253
  225. package/dist/generator-VE2JrFlY.mjs.map +0 -1
  226. package/dist/index-BThUzEIp.d.mts.map +0 -1
  227. package/dist/index-CHB4tSzX.d.cts.map +0 -1
  228. package/dist/openapi-CA0yJUTN.cjs.map +0 -1
  229. package/dist/openapi-kkQbsRVj.mjs.map +0 -1
  230. package/dist/openapi-react-query-Byltvm_7.mjs +0 -167
  231. package/dist/openapi-react-query-Byltvm_7.mjs.map +0 -1
  232. package/dist/openapi-react-query-CmJ1xDbn.cjs +0 -173
  233. package/dist/openapi-react-query-CmJ1xDbn.cjs.map +0 -1
  234. package/dist/openapi-react-query.cjs +0 -4
  235. package/dist/openapi-react-query.d.cts +0 -11
  236. package/dist/openapi-react-query.d.cts.map +0 -1
  237. package/dist/openapi-react-query.d.mts +0 -11
  238. package/dist/openapi-react-query.d.mts.map +0 -1
  239. package/dist/openapi-react-query.mjs +0 -4
  240. package/dist/reconcile-CFs8C_1a.mjs.map +0 -1
  241. package/dist/reconcile-D0pimNiy.cjs.map +0 -1
  242. package/dist/setup-B5_oHHUj.cjs +0 -11
  243. package/dist/setup-Cm2UnAdh.cjs +0 -473
  244. package/dist/setup-Cm2UnAdh.cjs.map +0 -1
  245. package/dist/setup-DXvRLTZN.mjs +0 -443
  246. package/dist/setup-DXvRLTZN.mjs.map +0 -1
  247. package/dist/setup-ZijS4qeC.mjs +0 -11
  248. package/dist/storage-BJmzYxt8.cjs +0 -363
  249. package/dist/storage-BJmzYxt8.cjs.map +0 -1
  250. package/dist/storage-BM9hGpgv.cjs +0 -7
  251. package/dist/storage-Bi24WfoW.mjs +0 -297
  252. package/dist/storage-Bi24WfoW.mjs.map +0 -1
  253. package/dist/storage-CYlGwWTj.mjs +0 -3
  254. package/dist/sync-CmEuNZsB.mjs +0 -76
  255. package/dist/sync-CmEuNZsB.mjs.map +0 -1
  256. package/dist/sync-D306yOWu.cjs +0 -4
  257. package/dist/sync-SizaChmC.cjs +0 -93
  258. package/dist/sync-SizaChmC.cjs.map +0 -1
  259. package/dist/sync-hOqAWHR6.mjs +0 -3
  260. package/dist/types-C-arnQ1r.d.mts +0 -2184
  261. package/dist/types-C-arnQ1r.d.mts.map +0 -1
  262. package/dist/types-abJQuk7m.d.cts +0 -2184
  263. package/dist/types-abJQuk7m.d.cts.map +0 -1
  264. package/dist/workspace-BFMrAKqI.mjs.map +0 -1
  265. package/dist/workspace-BcucjwvA.cjs.map +0 -1
  266. package/dist/workspace-DdJss8I6.cjs +0 -9
  267. package/dist/workspace-k4l3rsFh.mjs +0 -8
@@ -1,322 +1,268 @@
1
- const require_chunk = require('./chunk-CUT6urMc.cjs');
2
- const require_discover = require('./discover-DTmFeloL.cjs');
3
- const require_config = require('./config-C21ocYNd.cjs');
4
- const require_workspace = require('./workspace-BcucjwvA.cjs');
5
- const require_generator = require('./generator-CNzBw7g5.cjs');
6
- const require_storage = require('./storage-BJmzYxt8.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 __aws_sdk_client_s3 = require_chunk.__toESM(require("@aws-sdk/client-s3"));
16
- const pg = require_chunk.__toESM(require("pg"));
17
- const node_util = require_chunk.__toESM(require("node:util"));
18
- const node_crypto = require_chunk.__toESM(require("node:crypto"));
19
- const __geekmidas_db_pg_roles = require_chunk.__toESM(require("@geekmidas/db/pg/roles"));
20
- const __geekmidas_cache_postgres = require_chunk.__toESM(require("@geekmidas/cache/postgres"));
21
-
22
- //#region src/workspace/backends.ts
23
- const CACHE_BACKENDS = [
24
- "upstash",
25
- "elasticache",
26
- "db"
27
- ];
28
- const EMAIL_BACKENDS = [
29
- "resend",
30
- "ses",
31
- "smtp"
32
- ];
33
- const STORAGE_BACKENDS = [
34
- "minio",
35
- "s3",
36
- "r2"
37
- ];
38
- /**
39
- * The cache backend a workspace selected, or the one its target implies.
40
- *
41
- * Defaulted here rather than by every caller, so "what happens when nobody
42
- * said" is answered once and the answer is greppable — and now answered by
43
- * *where it deploys*, because there is no single right answer for both a
44
- * Lambda and a box running its own Postgres.
45
- *
46
- * `on` is the deploy target, not where this code happens to be running. A
47
- * local `gkm dev` for an AWS app still defaults to Upstash, because a backend
48
- * that differed between local and deployed would be worse than a slower one —
49
- * which is the property the type's own documentation asks for.
50
- */
51
- function cacheBackendOf(value, on = "aws") {
52
- return isBackend(value, CACHE_BACKENDS) ? value : require_discover.DEFAULT_CACHE[on];
53
- }
54
- /** The email backend a workspace selected, defaulting to SES on every target. */
55
- function emailBackendOf(value) {
56
- return isBackend(value, EMAIL_BACKENDS) ? value : require_discover.DEFAULT_EMAIL;
57
- }
58
- /** The storage backend a workspace selected, or the one its target implies. */
59
- function storageBackendOf(value, on = "aws") {
60
- return isBackend(value, STORAGE_BACKENDS) ? value : require_discover.DEFAULT_STORAGE[on];
61
- }
62
- /**
63
- * Which family of defaults a workspace's deploy target belongs to.
64
- *
65
- * One question, asked once: **does this target run containers the project
66
- * controls?** Dokploy and a bare server do, so a bucket or a cache can live
67
- * beside the app; AWS, Vercel and Cloudflare do not, so the default has to be
68
- * something managed. That is the whole of the distinction, and it is why
69
- * `MainProvider` is the right axis rather than the deploy target's own name —
70
- * three targets share one answer.
71
- *
72
- * An AWS deploy names no `deploy.default` at all, because it goes through SST,
73
- * which is why the absence is what selects `aws`.
74
- */
75
- function providerOf(workspace) {
76
- const target = workspace.deploy?.default;
77
- return target === "dokploy" || target === "server" ? "server" : "aws";
78
- }
79
- /**
80
- * Whether a string names a backend, as opposed to being one of the other things
81
- * a `services:` value can be.
82
- *
83
- * A misspelling falls through to the default rather than throwing, which is the
84
- * wrong trade for something with a cost attached — so callers that can report it
85
- * should use {@link unknownBackend} to say so.
86
- */
87
- function isBackend(value, backends) {
88
- return typeof value === "string" && backends.includes(value);
89
- }
90
-
91
- //#endregion
92
- //#region src/reconcile/caddyfile.ts
93
- /**
94
- * The kinds the edge serves.
95
- *
96
- * Everything that owns a *public address*. Deployed, each of these has a real
97
- * hostname and a certificate, so this is what makes the local shape the same
98
- * one rather than a near-enough one — and the application is indifferent
99
- * either way, because it reads whichever address was injected and never
100
- * composes one.
101
- *
102
- * Adding a kind here is the whole of adding it to the edge.
103
- */
104
- const EDGE_KINDS = {
105
- "file-server": true,
106
- "rest-api": true,
107
- site: true
108
- };
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_discover = require("./discover-DXNviAh-.cjs");
3
+ const require_config = require("./config-Cvr5fCbn.cjs");
4
+ const require_workspace = require("./workspace-BcCiLzTO.cjs");
5
+ const require_storage = require("./storage-CSGoC3bK.cjs");
6
+ const require_store = require("./store-DQgxT_WR.cjs");
7
+ const require_ready = require("./ready-lr2Fm-ep.cjs");
8
+ const require_backends = require("./backends-B9V2XD2M.cjs");
9
+ let node_fs = require("node:fs");
10
+ let node_fs_promises = require("node:fs/promises");
11
+ let node_os = require("node:os");
12
+ let node_path = require("node:path");
13
+ let node_child_process = require("node:child_process");
14
+ let _geekmidas_manifest = require("@geekmidas/manifest");
15
+ let node_net = require("node:net");
16
+ let dotenv = require("dotenv");
17
+ let node_crypto = require("node:crypto");
18
+ let _geekmidas_constructs_encryption = require("@geekmidas/constructs/encryption");
19
+ let _geekmidas_db_pg_roles = require("@geekmidas/db/pg/roles");
20
+ let _geekmidas_events_sns_url = require("@geekmidas/events/sns/url");
21
+ _geekmidas_events_sns_url = require_rolldown_runtime.__toESM(_geekmidas_events_sns_url, 1);
22
+ let _geekmidas_events_sqs_url = require("@geekmidas/events/sqs/url");
23
+ _geekmidas_events_sqs_url = require_rolldown_runtime.__toESM(_geekmidas_events_sqs_url, 1);
24
+ let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
25
+ let _aws_sdk_client_sns = require("@aws-sdk/client-sns");
26
+ let _aws_sdk_client_sqs = require("@aws-sdk/client-sqs");
27
+ let pg = require("pg");
28
+ let yaml = require("yaml");
29
+ let node_util = require("node:util");
30
+ let _geekmidas_cache_postgres = require("@geekmidas/cache/postgres");
31
+ //#region src/credentials/index.ts
32
+ const logger = console;
109
33
  /**
110
- * How the edge reaches the host, from inside its container.
111
- *
112
- * A surface and a site are served by processes `gkm dev` starts on the host,
113
- * not by containers — so the edge has to leave Docker's network to reach them.
114
- * Docker Desktop resolves this name already; on Linux the compose definition
115
- * maps it to the host gateway.
34
+ * Load environment files
35
+ * @internal Exported for testing
116
36
  */
117
- const HOST_GATEWAY = "host.docker.internal";
37
+ function loadEnvFiles(envConfig, cwd = process.cwd()) {
38
+ const loaded = [];
39
+ const missing = [];
40
+ const envFiles = envConfig ? Array.isArray(envConfig) ? envConfig : [envConfig] : [".env"];
41
+ for (const envFile of envFiles) {
42
+ const envPath = (0, node_path.resolve)(cwd, envFile);
43
+ if ((0, node_fs.existsSync)(envPath)) {
44
+ (0, dotenv.config)({
45
+ path: envPath,
46
+ override: true,
47
+ quiet: true
48
+ });
49
+ loaded.push(envFile);
50
+ } else if (envConfig) missing.push(envFile);
51
+ }
52
+ return {
53
+ loaded,
54
+ missing
55
+ };
56
+ }
118
57
  /**
119
- * The suffix every local host shares.
120
- *
121
- * `.localhost` rather than a made-up TLD because it resolves to loopback
122
- * without touching `/etc/hosts` — macOS and systemd-resolved both answer for
123
- * subdomains of it, and Caddy issues internal certificates for it by default.
58
+ * Check if a port is available
59
+ * @internal Exported for testing
124
60
  */
125
- const LOCAL_TLD = "localhost";
61
+ async function isPortAvailable(port) {
62
+ return new Promise((resolve) => {
63
+ const server = (0, node_net.createServer)();
64
+ server.once("error", (err) => {
65
+ if (err.code === "EADDRINUSE") resolve(false);
66
+ else resolve(false);
67
+ });
68
+ server.once("listening", () => {
69
+ server.close();
70
+ resolve(true);
71
+ });
72
+ server.listen(port);
73
+ });
74
+ }
126
75
  /**
127
- * The sites a plan implies, one per file server.
128
- *
129
- * The leading label is the *server's* stage-scoped name rather than the
130
- * bucket's, which is the difference that matters: two servers over one bucket
131
- * are a legitimate arrangement — two cache behaviours, one origin — and naming
132
- * the host after the bucket would make them collide.
76
+ * Find an available port starting from the preferred port
77
+ * @internal Exported for testing
133
78
  */
134
- function sitesFor(plan, project, addresses = {}) {
135
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
136
- const sites = [];
137
- for (const resource of plan.resources) {
138
- if (!EDGE_KINDS[resource.kind]) continue;
139
- const host = hostFor(resource, project);
140
- if (resource.kind === "file-server") {
141
- const origin = resource.of ? byId.get(resource.of) : void 0;
142
- if (!origin) continue;
143
- sites.push({
144
- host,
145
- upstream: "http://minio:9000",
146
- rewrite: `/${origin.name}{uri}`
147
- });
148
- continue;
149
- }
150
- const address = addresses[resource.id];
151
- if (!address) continue;
152
- const port = portOf(address);
153
- if (!port) continue;
154
- sites.push({
155
- host,
156
- upstream: `http://${HOST_GATEWAY}:${port}`
157
- });
79
+ async function findAvailablePort(preferredPort, maxAttempts = 10) {
80
+ for (let i = 0; i < maxAttempts; i++) {
81
+ const port = preferredPort + i;
82
+ if (await isPortAvailable(port)) return port;
83
+ logger.log(`⚠️ Port ${port} is in use, trying ${port + 1}...`);
158
84
  }
159
- return sites;
85
+ throw new Error(`Could not find an available port after trying ${maxAttempts} ports starting from ${preferredPort}`);
160
86
  }
161
- /** The port a local address answers on, defaulting by scheme. */
162
- function portOf(address) {
87
+ const PORT_STATE_PATH = ".gkm/ports.json";
88
+ /**
89
+ * Load saved port state from .gkm/ports.json.
90
+ * @internal Exported for testing
91
+ */
92
+ async function loadPortState(workspaceRoot) {
163
93
  try {
164
- const { port, protocol } = new URL(address);
165
- return port || (protocol === "https:" ? "443" : "80");
94
+ const raw = await (0, node_fs_promises.readFile)((0, node_path.join)(workspaceRoot, PORT_STATE_PATH), "utf-8");
95
+ return JSON.parse(raw);
166
96
  } catch {
167
- return void 0;
97
+ return {};
168
98
  }
169
99
  }
170
100
  /**
171
- * Where one file server answers, including the stage its name carries.
172
- *
173
- * The project is a label rather than a decoration: it is what keeps two
174
- * checkouts from answering on one address. Omitted when there is no project to
175
- * name, because an empty label makes `uploads..localhost` — a host nothing
176
- * resolves and no certificate can be issued for.
101
+ * Save port state to .gkm/ports.json.
102
+ * @internal Exported for testing
177
103
  */
178
- function hostFor(resource, project) {
179
- return [
180
- resource.name,
181
- project,
182
- LOCAL_TLD
183
- ].filter(Boolean).join(".");
104
+ async function savePortState(workspaceRoot, ports) {
105
+ const dir = (0, node_path.join)(workspaceRoot, ".gkm");
106
+ await (0, node_fs_promises.mkdir)(dir, { recursive: true });
107
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(workspaceRoot, PORT_STATE_PATH), `${JSON.stringify(ports, null, 2)}\n`);
184
108
  }
185
109
  /**
186
- * The static root config, which only ever imports.
187
- *
188
- * Written once and identical for every stage, because the *sites* are what
189
- * differ and they live in their own files. That split is not tidiness: one
190
- * container serves every stage — the same way one Postgres holds `orders` and
191
- * `orders_test` — so a single Caddyfile would mean `gkm test` deleting the
192
- * routes `gkm dev` is serving, and each command silently breaking the other.
110
+ * Load and flatten secrets for an app from encrypted storage.
111
+ * For workspace app: maps {APP}_DATABASE_URL → DATABASE_URL.
112
+ * @internal Exported for testing
193
113
  */
194
- function caddyfileRoot() {
195
- return `${GENERATED}
196
- {
197
- # No ACME, no public DNS: the CA is local and so are the names.
198
- local_certs
199
- auto_https disable_redirects
114
+ async function loadSecretsForApp(store, stage, appName) {
115
+ let secrets = {};
116
+ const stageSecrets = await store.read(stage);
117
+ if (stageSecrets) {
118
+ logger.log(`🔐 Loading secrets from stage: ${stage}`);
119
+ secrets = require_storage.toEmbeddableSecrets(stageSecrets);
120
+ }
121
+ if (Object.keys(secrets).length === 0) return {};
122
+ if (!appName) return secrets;
123
+ const prefix = appName.toUpperCase();
124
+ const mapped = { ...secrets };
125
+ const appDbUrl = secrets[`${prefix}_DATABASE_URL`];
126
+ if (appDbUrl) mapped.DATABASE_URL = appDbUrl;
127
+ return mapped;
200
128
  }
201
-
202
- # One file per stage, so two stages share this edge the way they already share
203
- # one Postgres and one MinIO.
204
- import /etc/caddy/sites/*.caddy
205
- `;
129
+ /**
130
+ * Walk up the directory tree to find the root containing .gkm/secrets/.
131
+ * @internal Exported for testing
132
+ */
133
+ function findSecretsRoot(startDir) {
134
+ let dir = startDir;
135
+ while (dir !== "/") {
136
+ if ((0, node_fs.existsSync)((0, node_path.join)(dir, ".gkm", "secrets"))) return dir;
137
+ const parent = (0, node_path.dirname)(dir);
138
+ if (parent === dir) break;
139
+ dir = parent;
140
+ }
141
+ return startDir;
206
142
  }
207
143
  /**
208
- * One stage's sites, as the file imported above.
209
- *
210
- * `rewrite` rather than a path prefix on the address: the bucket is the
211
- * origin's business, and the client asks for the key it stored.
212
- *
213
- * `header_up Host {upstream_hostport}` matters more than it looks. MinIO routes
214
- * and signs on the Host header, so forwarding the requested hostname would make
215
- * it look for a bucket named after the domain.
144
+ * Generate the credentials injection code snippet.
145
+ * This is the common logic used by both entry wrapper and exec preload.
146
+ * @internal
216
147
  */
217
- function toCaddyfile(sites) {
218
- if (sites.length === 0) return `${GENERATED}
219
- # No file server is declared in this stage, so it routes nothing.
220
- `;
221
- const blocks = sites.map(({ host, upstream, rewrite }) => `
222
- https://${host} {
223
- tls internal
148
+ function generateCredentialsInjection(secretsJsonPath) {
149
+ return `import { existsSync, readFileSync } from 'node:fs';
224
150
 
225
- reverse_proxy ${upstream} {${rewrite ? `
226
- rewrite ${rewrite}
227
- # MinIO routes and signs on the Host header, so forwarding the requested
228
- # hostname would make it look for a bucket named after the domain.
229
- header_up Host {upstream_hostport}` : `
230
- # The application reads whatever address was injected, so it has to see
231
- # the one a caller used — that is what makes a redirect, a cookie domain
232
- # and a generated link point back here rather than at the upstream.
233
- header_up Host {host}
234
- header_up X-Forwarded-Proto {scheme}`}
235
- }
236
- }`);
237
- return `${GENERATED}${blocks.join("\n")}\n`;
151
+ // Inject dev secrets via globalThis and process.env
152
+ // Using globalThis.__gkm_credentials__ avoids CJS/ESM interop issues where
153
+ // Object.assign on the Credentials export only mutates one module copy.
154
+ const secretsPath = '${secretsJsonPath}';
155
+ if (existsSync(secretsPath)) {
156
+ const secrets = JSON.parse(readFileSync(secretsPath, 'utf-8'));
157
+ globalThis.__gkm_credentials__ = secrets;
158
+ Object.assign(process.env, secrets);
238
159
  }
239
- const GENERATED = `# Generated by gkm from the construct manifest — do not edit.
240
- #
241
- # One host per declared file server, in front of the object store that holds its
242
- # objects. This is the shape a file server has deployed — a domain serving a
243
- # bucket — which MinIO alone cannot produce: its virtual-host mode reads the
244
- # leading label as the bucket name.
245
- #
246
- # Certificates come from Caddy's own CA. "gkm dev" and "gkm test" export its
247
- # root and point Node at it, so nothing has to be installed to use these URLs
248
- # from code; a browser needs the root trusted once.
249
160
  `;
250
-
251
- //#endregion
252
- //#region src/reconcile/clients.ts
253
- /** The credential local containers are brought up with. */
254
- const LOCAL_USER$2 = "geekmidas";
161
+ }
255
162
  /**
256
- * A Postgres client that opens one connection per database it is asked about.
257
- *
258
- * `CREATE DATABASE` cannot run from a connection to the database being created,
259
- * and a schema must be created from inside its own database — so the database is
260
- * part of each query rather than fixed when the client is built.
163
+ * Create a preload script that injects secrets into Credentials.
164
+ * Used by `gkm exec` to inject secrets before running any command.
165
+ * @internal Exported for testing
261
166
  */
262
- function pgClient(port) {
263
- return { async query(database, sql, values) {
264
- const client = new pg.Client({
265
- host: "localhost",
266
- port,
267
- user: LOCAL_USER$2,
268
- password: LOCAL_USER$2,
269
- database: database ?? LOCAL_USER$2
270
- });
271
- await client.connect();
272
- try {
273
- const result = await client.query(sql, values);
274
- return result.rows;
275
- } finally {
276
- await client.end();
277
- }
278
- } };
167
+ async function createCredentialsPreload(preloadPath, secretsJsonPath) {
168
+ const content = `/**
169
+ * Credentials preload generated by 'gkm exec'
170
+ * This file is loaded via NODE_OPTIONS="--import <path>"
171
+ */
172
+ ${generateCredentialsInjection(secretsJsonPath)}`;
173
+ await (0, node_fs_promises.writeFile)(preloadPath, content);
279
174
  }
280
- /** A bucket client pointed at the local MinIO. */
281
- function bucketClient(port) {
282
- const s3 = new __aws_sdk_client_s3.S3Client({
283
- region: "us-east-1",
284
- endpoint: `http://localhost:${port}`,
285
- forcePathStyle: true,
286
- credentials: {
287
- accessKeyId: LOCAL_USER$2,
288
- secretAccessKey: LOCAL_USER$2
289
- }
290
- });
175
+ /**
176
+ * Create a wrapper script that injects secrets before importing the entry file.
177
+ * @internal Exported for testing
178
+ */
179
+ async function createEntryWrapper(wrapperPath, entryPath, secretsJsonPath) {
180
+ const content = `#!/usr/bin/env node
181
+ /**
182
+ * Entry wrapper generated by 'gkm dev --entry'
183
+ */
184
+ ${secretsJsonPath ? `${generateCredentialsInjection(secretsJsonPath)}
185
+ ` : ""}// Import and run the user's entry file (dynamic import ensures secrets load first)
186
+ await import('${entryPath}');
187
+ `;
188
+ await (0, node_fs_promises.writeFile)(wrapperPath, content);
189
+ }
190
+ /**
191
+ * Prepare credentials for dev/exec/test modes.
192
+ * Loads workspace config, secrets, resolves Docker ports, rewrites URLs,
193
+ * injects PORT, dependency URLs, and writes credentials JSON.
194
+ *
195
+ * @param options.stage - The stage whose secrets to load. Default: the project's `stages.local`.
196
+ * @param options.startDocker - Start Docker Compose services after port resolution. Default: false.
197
+ * @param options.secretsFileName - Custom secrets JSON filename. Default: 'dev-secrets-{appName}.json' or 'dev-secrets.json'.
198
+ * @internal Exported for testing
199
+ */
200
+ async function prepareEntryCredentials(options) {
201
+ const cwd = options.cwd ?? process.cwd();
202
+ let workspaceAppPort;
203
+ let secretsRoot = cwd;
204
+ let appName;
205
+ let appInfo;
206
+ let workspace;
207
+ try {
208
+ appInfo = await require_config.loadWorkspaceAppInfo(cwd);
209
+ workspace = appInfo.workspace;
210
+ workspaceAppPort = appInfo.app.port;
211
+ secretsRoot = appInfo.workspaceRoot;
212
+ appName = appInfo.appName;
213
+ } catch (error) {
214
+ if (!(error instanceof require_config.NotInAnApp || error instanceof require_config.ConfigNotFound)) throw error;
215
+ workspace = await require_config.loadWorkspaceConfig(cwd).then((loaded) => loaded.workspace).catch(() => void 0);
216
+ secretsRoot = workspace?.root ?? findSecretsRoot(cwd);
217
+ }
218
+ if (appName && workspace && options.explicitPort === void 0) {
219
+ const { assignAppPorts, describeHolder, holderOf, withAppPorts } = await Promise.resolve().then(() => require("./index.cjs")).then((n) => n.appPorts_exports);
220
+ const assigned = await assignAppPorts(workspace, [appName], {
221
+ free: isPortAvailable,
222
+ holder: holderOf
223
+ });
224
+ for (const { app, from, to, holder } of assigned.moved) logger.log(`↪️ ${app}: ${from} is held by ${describeHolder(holder)}, which is not this workspace's — using ${to}`);
225
+ workspace = withAppPorts(workspace, assigned.ports);
226
+ workspaceAppPort = assigned.ports[appName] ?? workspaceAppPort;
227
+ }
228
+ if (appName) {
229
+ const { APP_TAG_ENV, appTag } = await Promise.resolve().then(() => require("./index.cjs")).then((n) => n.appPorts_exports);
230
+ process.env[APP_TAG_ENV] = appTag(secretsRoot, appName);
231
+ }
232
+ const resolvedPort = options.explicitPort ?? workspaceAppPort ?? 3e3;
233
+ const stage = options.stage ?? workspace?.stages.local;
234
+ const store = stage ? workspace ? await require_store.secretsStoreFor(workspace, stage) : new require_store.FileSecretsStore(secretsRoot) : void 0;
235
+ const credentials = store && stage ? await loadSecretsForApp(store, stage, appName) : {};
236
+ credentials.PORT = String(resolvedPort);
237
+ if (appInfo?.app.type === "mobile") credentials.RCT_METRO_PORT = String(resolvedPort);
238
+ const declaredKeys = [];
239
+ let reconciled;
240
+ if (workspace) {
241
+ const { reconcileWorkspace } = await Promise.resolve().then(() => workspace_exports);
242
+ reconciled = await reconcileWorkspace(workspace, {
243
+ stage: options.reconcileStage ?? workspace.stages.local,
244
+ start: options.startDocker ?? false
245
+ });
246
+ Object.assign(credentials, reconciled.env);
247
+ declaredKeys.push(...Object.keys(reconciled.env));
248
+ if (Object.keys(reconciled.env).length > 0) logger.log(`🔌 Resolved ${Object.keys(reconciled.env).length} declared URL(s)`);
249
+ }
250
+ const secretsDir = (0, node_path.join)(secretsRoot, ".gkm");
251
+ await (0, node_fs_promises.mkdir)(secretsDir, { recursive: true });
252
+ const secretsFileName = options.secretsFileName ?? (appName ? `dev-secrets-${appName}.json` : "dev-secrets.json");
253
+ const secretsJsonPath = (0, node_path.join)(secretsDir, secretsFileName);
254
+ await (0, node_fs_promises.writeFile)(secretsJsonPath, JSON.stringify(credentials, null, 2));
291
255
  return {
292
- async exists(bucket) {
293
- try {
294
- await s3.send(new __aws_sdk_client_s3.HeadBucketCommand({ Bucket: bucket }));
295
- return true;
296
- } catch {
297
- return false;
298
- }
299
- },
300
- async create(bucket) {
301
- await s3.send(new __aws_sdk_client_s3.CreateBucketCommand({ Bucket: bucket }));
302
- },
303
- async policy(bucket) {
304
- try {
305
- const result = await s3.send(new __aws_sdk_client_s3.GetBucketPolicyCommand({ Bucket: bucket }));
306
- return result.Policy;
307
- } catch {
308
- return void 0;
309
- }
310
- },
311
- async setPolicy(bucket, policy) {
312
- await s3.send(new __aws_sdk_client_s3.PutBucketPolicyCommand({
313
- Bucket: bucket,
314
- Policy: policy
315
- }));
316
- }
256
+ credentials,
257
+ resolvedPort,
258
+ secretsJsonPath,
259
+ appName,
260
+ secretsRoot,
261
+ appInfo,
262
+ declaredKeys,
263
+ ...reconciled ? { reconciled } : {}
317
264
  };
318
265
  }
319
-
320
266
  //#endregion
321
267
  //#region src/reconcile/containers.ts
322
268
  /**
@@ -348,8 +294,8 @@ function postgresImage(version) {
348
294
  * per project: a project needing `postgis/postgis` says so in config.
349
295
  */
350
296
  const DEFAULT_IMAGES = {
351
- postgres: postgresImage(__geekmidas_manifest.DEFAULT_POSTGRES_VERSION),
352
- minio: "quay.io/minio/minio:RELEASE.2025-09-07T16-13-09Z",
297
+ postgres: postgresImage(_geekmidas_manifest.DEFAULT_POSTGRES_VERSION),
298
+ minio: "pgsty/minio:RELEASE.2026-08-04T00-00-00Z",
353
299
  mailpit: "axllent/mailpit:latest",
354
300
  redis: "redis:8-alpine",
355
301
  "redis-http": "hiett/serverless-redis-http:latest",
@@ -377,7 +323,8 @@ const PORTS = {
377
323
  }, {
378
324
  key: "minio-console",
379
325
  inside: 9001,
380
- label: "minio console"
326
+ label: "minio console",
327
+ web: true
381
328
  }],
382
329
  mailpit: [{
383
330
  key: "mailpit",
@@ -386,7 +333,8 @@ const PORTS = {
386
333
  }, {
387
334
  key: "mailpit-web",
388
335
  inside: 8025,
389
- label: "mailpit inbox"
336
+ label: "mailpit inbox",
337
+ web: true
390
338
  }],
391
339
  redis: [{
392
340
  key: "redis",
@@ -405,7 +353,8 @@ const PORTS = {
405
353
  }, {
406
354
  key: "rabbitmq-management",
407
355
  inside: 15672,
408
- label: "rabbitmq console"
356
+ label: "rabbitmq console",
357
+ web: true
409
358
  }],
410
359
  localstack: [{
411
360
  key: "localstack",
@@ -418,10 +367,48 @@ const PORTS = {
418
367
  label: "https edge"
419
368
  }]
420
369
  };
421
- /** The ports a container needs published. Empty for one gkm does not know. */
422
- function portsOf(container) {
370
+ /** The port key — and container name, for an image — of an API's fake. */
371
+ function fakeKey(id) {
372
+ return `${(0, _geekmidas_manifest.kebabCase)(id)}-fake`;
373
+ }
374
+ /**
375
+ * The ports a container needs published. Empty for one gkm does not know.
376
+ *
377
+ * `fakes` answers for the containers no table can: an external API's fake
378
+ * listens wherever its declaration says.
379
+ */
380
+ function portsOf(container, fakes = {}) {
381
+ const fake = fakes[container];
382
+ if (fake?.port !== void 0) return [{
383
+ key: container,
384
+ inside: fake.port,
385
+ label: `${fake.id} fake`
386
+ }];
423
387
  return PORTS[container] ?? [];
424
388
  }
389
+ /**
390
+ * Every port the containers publish — not only the one an app connects to.
391
+ *
392
+ * The consoles and the inbox are most of why these are real containers, and an
393
+ * inbox nobody can find is an inbox nobody opens: a sign-in link gets fished
394
+ * out of `docker ps` instead.
395
+ */
396
+ function serviceAddresses(containers, ports, fakes = {}) {
397
+ return containers.flatMap((container) => portsOf(container, fakes).flatMap((port) => {
398
+ const assigned = ports[port.key];
399
+ if (assigned === void 0) return [];
400
+ return [{
401
+ container,
402
+ label: port.label,
403
+ address: port.web ? `http://localhost:${assigned}` : `localhost:${assigned}`
404
+ }];
405
+ }));
406
+ }
407
+ /** The lines `gkm dev` and `gkm setup` print under the services heading. */
408
+ function describeServices(services) {
409
+ const width = Math.max(0, ...services.map(({ label }) => label.length));
410
+ return services.map(({ label, address }) => ` ${label.padEnd(width)} ${address}`);
411
+ }
425
412
  /** The key a container's primary port is allocated under. */
426
413
  function primaryPortKey(container) {
427
414
  return portsOf(container)[0]?.key ?? container;
@@ -432,8 +419,9 @@ function primaryPortKey(container) {
432
419
  * What allocation is handed: it assigns ports to names and knows nothing about
433
420
  * what listens on them.
434
421
  */
435
- function portKeys(containers) {
436
- return [...containers].sort().flatMap((container) => portsOf(container).map((port) => port.key));
422
+ function portKeys(containers, fakes = {}) {
423
+ const keys = [...containers].sort().flatMap((container) => portsOf(container, fakes).map((port) => port.key));
424
+ return [.../* @__PURE__ */ new Set([...keys, ...Object.keys(fakes).sort()])];
437
425
  }
438
426
  /**
439
427
  * The named volume a container's data lives in.
@@ -442,945 +430,1716 @@ function portKeys(containers) {
442
430
  * survives days of dev is noise rather than state.
443
431
  */
444
432
  function volumeOf(container) {
445
- const volumes = {
433
+ return {
446
434
  postgres: "postgres-data",
447
435
  minio: "minio-data",
448
436
  redis: "redis-data",
449
437
  rabbitmq: "rabbitmq-data",
450
438
  localstack: "localstack-data",
451
439
  caddy: "caddy-data"
452
- };
453
- return volumes[container];
440
+ }[container];
454
441
  }
455
-
456
442
  //#endregion
457
- //#region src/reconcile/compose.ts
458
- /** The credential every derived container is brought up with locally. */
459
- const LOCAL_USER$1 = "geekmidas";
443
+ //#region src/reconcile/caddyfile.ts
460
444
  /**
461
- * The token the local cache accepts.
445
+ * The kinds the edge serves.
462
446
  *
463
- * Fixed rather than generated: it is only ever reachable on a port this project
464
- * published, and the URL that carries it is derived, so nothing is made safer
465
- * by making it unguessable and a stable one keeps `redis-cli` sessions working.
447
+ * Everything that owns a *public address*. Deployed, each of these has a real
448
+ * hostname and a certificate, so this is what makes the local shape the same
449
+ * one rather than a near-enough one — and the application is indifferent
450
+ * either way, because it reads whichever address was injected and never
451
+ * composes one.
452
+ *
453
+ * Adding a kind here is the whole of adding it to the edge.
466
454
  */
467
- const LOCAL_TOKEN$1 = "geekmidas";
455
+ const EDGE_KINDS = {
456
+ "file-server": true,
457
+ "rest-api": true,
458
+ site: true
459
+ };
468
460
  /**
469
- * Build the compose document for a plan.
461
+ * How the edge reaches the host, from inside its container.
470
462
  *
471
- * Every container is published on its assigned port, never on the image's
472
- * default: the point of allocation is that two projects can run at once, and
473
- * one container publishing 5432 puts that back.
463
+ * A surface and a site are served by processes `gkm dev` starts on the host,
464
+ * not by containers — so the edge has to leave Docker's network to reach them.
465
+ * Docker Desktop resolves this name already; on Linux the compose definition
466
+ * maps it to the host gateway.
474
467
  */
475
- function composeFor(plan, options) {
476
- const services = {};
477
- const volumes = {};
478
- for (const container of [...plan.containers].sort()) {
479
- const declared = container === "postgres" ? plan.resources.find((r) => r.version)?.version : void 0;
480
- const image = options.images?.[container] ?? (declared ? postgresImage(declared) : DEFAULT_IMAGES[container]);
481
- if (!image) throw new UnknownContainer(container);
482
- services[container] = define(container, image, publish(container, options.ports));
483
- const volume = volumeOf(container);
484
- if (volume) volumes[volume] = {};
468
+ const HOST_GATEWAY = "host.docker.internal";
469
+ /**
470
+ * The suffix every local host shares.
471
+ *
472
+ * `.localhost` rather than a made-up TLD because it resolves to loopback
473
+ * without touching `/etc/hosts` — macOS and systemd-resolved both answer for
474
+ * subdomains of it, and Caddy issues internal certificates for it by default.
475
+ */
476
+ const LOCAL_TLD = "localhost";
477
+ /**
478
+ * The sites a plan implies, one per file server.
479
+ *
480
+ * The leading label is the *server's* stage-scoped name rather than the
481
+ * bucket's, which is the difference that matters: two servers over one bucket
482
+ * are a legitimate arrangement — two cache behaviours, one origin — and naming
483
+ * the host after the bucket would make them collide.
484
+ */
485
+ function sitesFor(plan, project, addresses = {}) {
486
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
487
+ const sites = [];
488
+ for (const resource of plan.resources) {
489
+ if (!EDGE_KINDS[resource.kind]) continue;
490
+ const host = hostFor(resource, project);
491
+ if (resource.kind === "file-server") {
492
+ const origin = resource.of ? byId.get(resource.of) : void 0;
493
+ if (!origin) continue;
494
+ sites.push({
495
+ host,
496
+ upstream: "http://minio:9000",
497
+ rewrite: `/${origin.name}{uri}`
498
+ });
499
+ continue;
500
+ }
501
+ const address = addresses[resource.id];
502
+ if (!address) continue;
503
+ const port = portOf(address);
504
+ if (!port) continue;
505
+ sites.push({
506
+ host,
507
+ upstream: `http://${HOST_GATEWAY}:${port}`
508
+ });
485
509
  }
486
- return {
487
- name: options.project,
488
- services,
489
- ...Object.keys(volumes).length ? { volumes } : {}
490
- };
491
- }
492
- /** Render a compose document as the file it becomes. */
493
- function toYaml(file) {
494
- return `# Generated by gkm from the construct manifest — do not edit.
495
- # Containers are derived from what the app declares; images and anything no
496
- # construct implies are yours, in gkm.config.ts.
497
- #
498
- # Use "gkm dev" or "gkm test" to start these. Running "docker compose up"
499
- # directly will not inject secrets.
500
- ${(0, yaml.stringify)(file, { lineWidth: 0 })}`;
510
+ return sites;
501
511
  }
502
- /** A container with no image, from config or from the defaults. */
503
- var UnknownContainer = class extends Error {
504
- /** The container that could not be resolved. */
505
- container;
506
- /** The containers that have a default, so the caller can see the set. */
507
- known = Object.keys(DEFAULT_IMAGES).sort();
508
- constructor(container) {
509
- super("No image is known for this container; pin one in config");
510
- this.name = "UnknownContainer";
511
- this.container = container;
512
+ /** The port a local address answers on, defaulting by scheme. */
513
+ function portOf(address) {
514
+ try {
515
+ const { port, protocol } = new URL(address);
516
+ return port || (protocol === "https:" ? "443" : "80");
517
+ } catch {
518
+ return;
512
519
  }
513
- };
514
- /** One container's definition, published on the port it was assigned. */
515
- function define(container, image, published) {
516
- switch (container) {
517
- case "postgres": return {
518
- image,
519
- restart: "unless-stopped",
520
- ports: published,
521
- environment: {
522
- POSTGRES_USER: LOCAL_USER$1,
523
- POSTGRES_PASSWORD: LOCAL_USER$1,
524
- POSTGRES_DB: LOCAL_USER$1
525
- },
526
- volumes: ["postgres-data:/var/lib/postgresql"],
527
- healthcheck: {
528
- test: ["CMD-SHELL", `pg_isready -U ${LOCAL_USER$1}`],
529
- interval: "5s",
530
- timeout: "3s",
531
- retries: 10,
532
- start_period: "10s"
533
- }
534
- };
535
- case "minio": return {
536
- image,
537
- restart: "unless-stopped",
538
- ports: published,
539
- environment: {
540
- MINIO_ROOT_USER: LOCAL_USER$1,
541
- MINIO_ROOT_PASSWORD: LOCAL_USER$1
542
- },
543
- command: "server --console-address \":9001\" /data",
544
- volumes: ["minio-data:/data"],
545
- healthcheck: {
546
- test: [
547
- "CMD",
548
- "mc",
549
- "ready",
550
- "local"
551
- ],
552
- interval: "10s",
553
- timeout: "5s",
554
- retries: 5,
555
- start_period: "10s"
556
- }
557
- };
558
- case "caddy": return {
559
- image,
560
- restart: "unless-stopped",
561
- ports: published,
562
- volumes: [
563
- "./Caddyfile:/etc/caddy/Caddyfile:ro",
564
- "./caddy-sites:/etc/caddy/sites:ro",
565
- "caddy-data:/data"
566
- ],
567
- extra_hosts: ["host.docker.internal:host-gateway"],
568
- healthcheck: {
569
- test: [
570
- "CMD",
571
- "caddy",
572
- "version"
573
- ],
574
- interval: "10s",
575
- timeout: "5s",
576
- retries: 5
577
- }
578
- };
579
- case "mailpit": return {
580
- image,
581
- restart: "unless-stopped",
582
- ports: published,
583
- environment: {
584
- MP_SMTP_AUTH_ACCEPT_ANY: "1",
585
- MP_SMTP_AUTH_ALLOW_INSECURE: "1"
586
- },
587
- healthcheck: {
588
- test: [
589
- "CMD",
590
- "wget",
591
- "-q",
592
- "--spider",
593
- "http://localhost:8025"
594
- ],
595
- interval: "10s",
596
- timeout: "5s",
597
- retries: 5
598
- }
599
- };
600
- case "redis": return {
601
- image,
602
- restart: "unless-stopped",
603
- ports: published,
604
- volumes: ["redis-data:/data"],
605
- healthcheck: {
606
- test: [
607
- "CMD",
608
- "redis-cli",
609
- "ping"
610
- ],
611
- interval: "5s",
612
- timeout: "3s",
613
- retries: 5
614
- }
615
- };
616
- case "redis-http": return {
617
- image,
618
- restart: "unless-stopped",
619
- ports: published,
620
- environment: {
621
- SRH_MODE: "env",
622
- SRH_TOKEN: LOCAL_TOKEN$1,
623
- SRH_CONNECTION_STRING: "redis://redis:6379"
624
- },
625
- depends_on: ["redis"],
626
- healthcheck: {
627
- test: [
628
- "CMD",
629
- "wget",
630
- "-q",
631
- "-O",
632
- "/dev/null",
633
- "http://127.0.0.1:80/"
634
- ],
635
- interval: "5s",
636
- timeout: "3s",
637
- retries: 10
638
- }
639
- };
640
- case "rabbitmq": return {
641
- image,
642
- restart: "unless-stopped",
643
- ports: published,
644
- environment: {
645
- RABBITMQ_DEFAULT_USER: LOCAL_USER$1,
646
- RABBITMQ_DEFAULT_PASS: LOCAL_USER$1
647
- },
648
- volumes: ["rabbitmq-data:/var/lib/rabbitmq"],
649
- healthcheck: {
650
- test: [
651
- "CMD",
652
- "rabbitmq-diagnostics",
653
- "-q",
654
- "ping"
655
- ],
656
- interval: "10s",
657
- timeout: "5s",
658
- retries: 5
659
- }
520
+ }
521
+ /**
522
+ * Where one file server answers, including the stage its name carries.
523
+ *
524
+ * The project is a label rather than a decoration: it is what keeps two
525
+ * checkouts from answering on one address. Omitted when there is no project to
526
+ * name, because an empty label makes `uploads..localhost` — a host nothing
527
+ * resolves and no certificate can be issued for.
528
+ */
529
+ function hostFor(resource, project) {
530
+ return [
531
+ resource.root && project ? stageOf(resource) : labelOf(resource),
532
+ project,
533
+ LOCAL_TLD
534
+ ].filter(Boolean).join(".");
535
+ }
536
+ /**
537
+ * A resource's own label: its `subdomain` where it declared one — the label a
538
+ * deploy uses too — with the stage it carries kept, so `gkm test` and `gkm dev`
539
+ * still answer on different hosts.
540
+ */
541
+ function labelOf(resource) {
542
+ if (!resource.subdomain) return resource.name;
543
+ const stage = stageOf(resource);
544
+ return stage ? `${resource.subdomain}-${stage}` : resource.subdomain;
545
+ }
546
+ /** The stage a resource's name carries, or nothing for the local stage's. */
547
+ function stageOf(resource) {
548
+ const base = resource.id.toLowerCase();
549
+ return resource.name === base ? void 0 : resource.name.slice(base.length + 1);
550
+ }
551
+ /**
552
+ * The static root config, which only ever imports.
553
+ *
554
+ * Written once and identical for every stage, because the *sites* are what
555
+ * differ and they live in their own files. That split is not tidiness: one
556
+ * container serves every stage — the same way one Postgres holds `orders` and
557
+ * `orders_test` — so a single Caddyfile would mean `gkm test` deleting the
558
+ * routes `gkm dev` is serving, and each command silently breaking the other.
559
+ */
560
+ function caddyfileRoot() {
561
+ return `${GENERATED}
562
+ {
563
+ # No ACME, no public DNS: the CA is local and so are the names.
564
+ local_certs
565
+ auto_https disable_redirects
566
+ }
567
+
568
+ # One file per stage, so two stages share this edge the way they already share
569
+ # one Postgres and one MinIO.
570
+ import /etc/caddy/sites/*.caddy
571
+ `;
572
+ }
573
+ /**
574
+ * One stage's sites, as the file imported above.
575
+ *
576
+ * `rewrite` rather than a path prefix on the address: the bucket is the
577
+ * origin's business, and the client asks for the key it stored.
578
+ *
579
+ * `header_up Host {upstream_hostport}` matters more than it looks. MinIO routes
580
+ * and signs on the Host header, so forwarding the requested hostname would make
581
+ * it look for a bucket named after the domain.
582
+ */
583
+ function toCaddyfile(sites) {
584
+ if (sites.length === 0) return `${GENERATED}
585
+ # No file server is declared in this stage, so it routes nothing.
586
+ `;
587
+ const blocks = sites.map(({ host, upstream, rewrite }) => `
588
+ https://${host} {
589
+ tls internal
590
+
591
+ reverse_proxy ${upstream} {${rewrite ? `
592
+ rewrite ${rewrite}
593
+ # MinIO routes and signs on the Host header, so forwarding the requested
594
+ # hostname would make it look for a bucket named after the domain.
595
+ header_up Host {upstream_hostport}` : `
596
+ # The application reads whatever address was injected, so it has to see
597
+ # the one a caller used — that is what makes a redirect, a cookie domain
598
+ # and a generated link point back here rather than at the upstream.
599
+ header_up Host {host}
600
+ header_up X-Forwarded-Proto {scheme}`}
601
+ }
602
+ }`);
603
+ return `${GENERATED}${blocks.join("\n")}\n`;
604
+ }
605
+ const GENERATED = `# Generated by gkm from the construct manifest — do not edit.
606
+ #
607
+ # One host per declared file server, in front of the object store that holds its
608
+ # objects. This is the shape a file server has deployed — a domain serving a
609
+ # bucket — which MinIO alone cannot produce: its virtual-host mode reads the
610
+ # leading label as the bucket name.
611
+ #
612
+ # Certificates come from Caddy's own CA. "gkm dev" and "gkm test" export its
613
+ # root and point Node at it, so nothing has to be installed to use these URLs
614
+ # from code; a browser needs the root trusted once.
615
+ `;
616
+ //#endregion
617
+ //#region src/reconcile/emulator.ts
618
+ /**
619
+ * The AWS emulator (floci, LocalStack-compatible) the `sns` backend runs on
620
+ * locally — the facts the compose file, the env writer and the applier must
621
+ * agree on.
622
+ *
623
+ * The emulator has one account and answers with deterministic ARNs and queue
624
+ * URLs, which is what lets a connection string be composed before the topic
625
+ * or queue it names has been created.
626
+ */
627
+ /** The emulator's single account. */
628
+ const EMULATOR_ACCOUNT = "000000000000";
629
+ const EMULATOR_REGION = "us-east-1";
630
+ /**
631
+ * The emulator's credential. The `LSIA` prefix is what LocalStack required on
632
+ * issued keys; floci does not care, and keeping it means a project that pins
633
+ * the old image still works.
634
+ */
635
+ const EMULATOR_CREDENTIALS = {
636
+ accessKeyId: "LSIAQAAAAAAVNCBMPNSG",
637
+ secretAccessKey: "geekmidas"
638
+ };
639
+ /** The emulator's address from the host, on the port it was published on. */
640
+ function emulatorEndpoint(port) {
641
+ return `http://localhost:${port}`;
642
+ }
643
+ function emulatorTopicArn(name) {
644
+ return `arn:aws:sns:${EMULATOR_REGION}:${EMULATOR_ACCOUNT}:${name}`;
645
+ }
646
+ function emulatorQueueUrl(name, port) {
647
+ return `${emulatorEndpoint(port)}/${EMULATOR_ACCOUNT}/${name}`;
648
+ }
649
+ //#endregion
650
+ //#region src/workspace/rootSite.ts
651
+ /**
652
+ * Which site the base domain points at — deployed and locally alike.
653
+ *
654
+ * Three rules, in order, and the last one is the point:
655
+ *
656
+ * 1. **One site** — it is the root. Unambiguous, so nothing has to be said.
657
+ * 2. **Named `web`** — the convention wins, because people already rely on it.
658
+ * 3. **Declared `root: true`** — the site says so itself.
659
+ *
660
+ * Anything else throws. It used to take the *first* site it iterated, and that
661
+ * order came from the manifest, which is built in glob traversal order — so two
662
+ * sites with neither named `web` meant renaming a file could move the root
663
+ * domain, silently.
664
+ *
665
+ * One rule for both targets: deployed the root site gets the base domain, and
666
+ * locally it gets the project's bare host behind the edge. Before this was
667
+ * shared, the local edge put every site on a subdomain, so what a developer
668
+ * browsed was not the shape production served.
669
+ *
670
+ * @returns the root site's name, or `undefined` when there are no sites
671
+ * @throws {AmbiguousRootSite} when several sites could be the root and none says it is
672
+ */
673
+ function rootSite(sites) {
674
+ if (sites.length === 0) return void 0;
675
+ if (sites.length === 1) return sites[0].name;
676
+ if (sites.some(({ name }) => name === "web")) return "web";
677
+ const declared = sites.filter(({ root }) => root === true);
678
+ if (declared.length === 1) return declared[0].name;
679
+ throw new AmbiguousRootSite(sites.map(({ name }) => name), declared.length > 1);
680
+ }
681
+ /** Several sites could hold the base domain, and none of them says it does. */
682
+ var AmbiguousRootSite = class extends Error {
683
+ sites;
684
+ tooMany;
685
+ constructor(sites, tooMany = false) {
686
+ super(tooMany ? `More than one site declares \`root: true\` — ${sites.join(", ")}. The base domain points at one of them.` : `${sites.length} sites and nothing says which holds the base domain: ${sites.join(", ")}. Name one of them \`web\`, or declare \`root: true\` on the one the base domain points at. It used to be whichever the glob reached first, which is not a thing to decide a hostname.`);
687
+ this.sites = sites;
688
+ this.tooMany = tooMany;
689
+ this.name = "AmbiguousRootSite";
690
+ }
691
+ };
692
+ //#endregion
693
+ //#region src/reconcile/plan.ts
694
+ /**
695
+ * The reconcile plan — what a manifest wants to exist, for one stage.
696
+ *
697
+ * Pure. Turning the plan into running containers and provisioned resources is
698
+ * the applier's job; deciding *what* should exist is this, so the decisions can
699
+ * be asserted as data rather than by starting Docker.
700
+ *
701
+ * One plan serves every stage. `gkm dev` reconciles `development` and `gkm test`
702
+ * reconciles `test`; they differ only in what the resources are called, never in
703
+ * what infrastructure exists. Roles are cluster-scoped in Postgres while grants
704
+ * are per-object, so one container and one role pair serve both.
705
+ */
706
+ /**
707
+ * Which container serves a kind.
708
+ *
709
+ * Derived kinds map to the same container as their parent — a schema tenant
710
+ * lives in its parent's Postgres — so the set is deduplicated rather than
711
+ * counted.
712
+ */
713
+ const CONTAINERS = {
714
+ database: "postgres",
715
+ "database-reader": "postgres",
716
+ "database-schema": "postgres",
717
+ objects: "minio",
718
+ "file-server": "caddy",
719
+ email: "mailpit"
720
+ };
721
+ /**
722
+ * The container a cache backend needs locally.
723
+ *
724
+ * Each one matches the protocol its deployed form speaks, which is the property
725
+ * worth having: a cache that behaves differently in the two places is worse than
726
+ * a slower one.
727
+ *
728
+ * `db` is deliberately absent, the same way `pgboss` is absent from
729
+ * `EVENT_CONTAINERS`: the cache is a table in a database the manifest already
730
+ * declares, so mapping it here would start a container for a project that needs
731
+ * none.
732
+ */
733
+ const CACHE_CONTAINERS = {
734
+ upstash: "redis-http",
735
+ elasticache: "redis"
736
+ };
737
+ /**
738
+ * Kinds that resolve a value without anything running.
739
+ *
740
+ * A secret is the case: it has no address, so there is nothing to start and
741
+ * nothing to connect to — but it still appears in the plan, because the target
742
+ * still has to resolve it.
743
+ */
744
+ const CONTAINERLESS = {
745
+ secret: true,
746
+ credential: true,
747
+ encryption: true,
748
+ "rest-api": true,
749
+ site: true,
750
+ "mobile-app": true,
751
+ "external-api": true
752
+ };
753
+ /**
754
+ * Containers that cannot run alone.
755
+ *
756
+ * The one case is the cache: `serverless-redis-http` is a proxy and needs the
757
+ * Redis it proxies. Kept here rather than in the compose definition so the plan
758
+ * -- which is what decides what must be running -- still names everything.
759
+ */
760
+ const REQUIRES = { "redis-http": ["redis"] };
761
+ /**
762
+ * The role each kind's one key plays, where it is not a URL.
763
+ *
764
+ * The twin of `ProvidesByKind` in `@geekmidas/manifest`: that is what a
765
+ * construct declares, this is what the local target resolves, and both derive
766
+ * the key from the same `provideKey` so they cannot disagree.
767
+ */
768
+ const ROLES = {
769
+ queue: "publisherConnectionString",
770
+ topic: "publisherConnectionString",
771
+ credential: "credentials",
772
+ "mobile-app": "scheme"
773
+ };
774
+ /** The kinds whose container is the events backend's rather than their own. */
775
+ const EVENT_KINDS = {
776
+ queue: true,
777
+ topic: true
778
+ };
779
+ /**
780
+ * Which kinds provision something *inside* their container.
781
+ *
782
+ * A database creates a database, a bucket creates a bucket; mail creates
783
+ * nothing — Mailpit accepts whatever is sent to it and has no per-stage object
784
+ * to name. Both still appear in the plan, because both still resolve a URL; the
785
+ * flag is the difference between "must be running" and "must be created".
786
+ */
787
+ const PROVISIONS = {
788
+ database: true,
789
+ "database-reader": true,
790
+ "database-schema": true,
791
+ objects: true,
792
+ cache: true,
793
+ "file-server": true
794
+ };
795
+ /**
796
+ * The container each events backend needs, where it needs one of its own.
797
+ *
798
+ * `pgboss` is deliberately absent rather than mapped to `postgres`: it is a
799
+ * schema tenant in a database the manifest already declares, so mapping it here
800
+ * would start a Postgres for a project that declared no database at all.
801
+ *
802
+ * This one comes from config rather than from a declaration because there are
803
+ * no `topic` or `queue` kinds yet. When they land the mapping moves to
804
+ * {@link CONTAINERS} keyed by kind, and this constant goes with them.
805
+ */
806
+ const EVENT_CONTAINERS = {
807
+ sns: "localstack",
808
+ rabbitmq: "rabbitmq"
809
+ };
810
+ /** The backend a project gets when it declares queues or topics and says nothing. */
811
+ const DEFAULT_EVENTS = "pgboss";
812
+ /**
813
+ * How a resource of each kind separates its stage suffix.
814
+ *
815
+ * Postgres identifiers are snake_case and a hyphen would need quoting
816
+ * everywhere; buckets and queues are kebab and disallow underscores in some
817
+ * providers. The suffix is the same word either way.
818
+ */
819
+ const SEPARATORS = {
820
+ database: "_",
821
+ "database-reader": "_",
822
+ "database-schema": "_",
823
+ objects: "-"
824
+ };
825
+ /**
826
+ * The stage-scoped name for a resource.
827
+ *
828
+ * The local stage carries no suffix, so `gkm dev` keeps using `orders` and a
829
+ * developer's psql history, saved connections, and muscle memory survive a
830
+ * change of stage name. Every other stage is suffixed.
831
+ */
832
+ function resourceName(id, kind, stage, localStage) {
833
+ const base = id.toLowerCase();
834
+ if (stage === localStage) return base;
835
+ return `${base}${SEPARATORS[kind] ?? "-"}${stage}`;
836
+ }
837
+ /**
838
+ * The container a kind needs, or `undefined` if it needs none.
839
+ *
840
+ * Queues and topics have no container of their own — they live in whichever
841
+ * broker the project selected, which is why the backend is an argument here
842
+ * rather than a second pass that adds containers after the fact.
843
+ */
844
+ function containerFor(kind, events = DEFAULT_EVENTS, cache = require_ready.DEFAULT_CACHE.aws, derived = false, edge = true) {
845
+ if (EVENT_KINDS[kind]) return EVENT_CONTAINERS[events] ?? CONTAINERS.database;
846
+ if (kind === "file-server") return edge ? "caddy" : CONTAINERS.objects;
847
+ if (kind === "cache") {
848
+ if (derived) return CONTAINERS.database;
849
+ return CACHE_CONTAINERS[cache] ?? CONTAINERS.database;
850
+ }
851
+ return CONTAINERS[kind];
852
+ }
853
+ /**
854
+ * Build the plan for a manifest and stage.
855
+ *
856
+ * `order` is the caller's provisioning order — parents before children — which
857
+ * `provisionOrder` produces from the manifest. Passing it in keeps this
858
+ * function free of the traversal and makes the ordering assertable on its own.
859
+ */
860
+ function planFor(manifest, stage, order, options = {}) {
861
+ const containers = /* @__PURE__ */ new Set();
862
+ const resources = [];
863
+ const fakes = {};
864
+ const events = options.events ?? "pgboss";
865
+ const cache = options.cache ?? require_ready.DEFAULT_CACHE.aws;
866
+ for (const id of order) {
867
+ const declaration = manifest[id];
868
+ if (!declaration) continue;
869
+ const local = declaration.kind === "external-api" ? options.fakes?.[id] : void 0;
870
+ const fake = local && {
871
+ key: fakeKey(id),
872
+ ...local
660
873
  };
661
- case "localstack": return {
662
- image,
663
- restart: "unless-stopped",
664
- ports: published,
665
- environment: {
666
- AWS_DEFAULT_REGION: "us-east-1",
667
- AWS_ACCESS_KEY_ID: "LSIAQAAAAAAVNCBMPNSG",
668
- AWS_SECRET_ACCESS_KEY: LOCAL_USER$1
669
- },
670
- volumes: ["localstack-data:/var/lib/localstack"],
671
- healthcheck: {
672
- test: [
673
- "CMD",
674
- "curl",
675
- "-f",
676
- "http://localhost:4566/_localstack/health"
677
- ],
678
- interval: "10s",
679
- timeout: "5s",
680
- retries: 5,
681
- start_period: "10s"
682
- }
874
+ if (fake) fakes[fake.key] = {
875
+ id,
876
+ ...fake.image ? {
877
+ image: fake.image,
878
+ port: fake.port
879
+ } : {}
683
880
  };
684
- default: throw new UnknownContainer(container);
881
+ const container = fake?.image ? fake.key : containerFor(declaration.kind, events, cache, "of" in declaration && typeof declaration.of === "string", options.edge !== false);
882
+ if (!container && !CONTAINERLESS[declaration.kind]) continue;
883
+ if (container) {
884
+ containers.add(container);
885
+ for (const required of REQUIRES[container] ?? []) containers.add(required);
886
+ }
887
+ resources.push({
888
+ id,
889
+ kind: declaration.kind,
890
+ ...container ? { container } : {},
891
+ name: resourceName(id, declaration.kind, stage, options.localStage),
892
+ envKey: (0, _geekmidas_manifest.providedKeyFor)(id, declaration.kind, ROLES[declaration.kind] ?? "url"),
893
+ provisions: PROVISIONS[declaration.kind] === true,
894
+ ...declaration.kind === "rest-api" ? { callers: (0, _geekmidas_manifest.dependentsOf)(manifest, id) } : {},
895
+ ...declaration.kind === "site" ? { publicEnv: (0, _geekmidas_manifest.publicEnvFor)(declaration, manifest) } : {},
896
+ ...declaration.kind === "mobile-app" ? {
897
+ publicEnv: (0, _geekmidas_manifest.publicEnvFor)(declaration, manifest),
898
+ ...declaration.scheme ? { scheme: declaration.scheme } : {}
899
+ } : {},
900
+ ...declaration.kind === "file-server" && declaration.open?.length ? { open: declaration.open } : {},
901
+ ...(declaration.kind === "rest-api" || declaration.kind === "site") && declaration.subdomain ? { subdomain: declaration.subdomain } : {},
902
+ ...fake ? { fake: {
903
+ key: fake.key,
904
+ credentials: fake.credentials
905
+ } } : {},
906
+ ...declaration.kind === "external-api" && !fake ? { url: declaration.url } : {},
907
+ ..."of" in declaration ? { of: declaration.of } : {},
908
+ ..."schema" in declaration && declaration.schema ? { schema: declaration.schema } : {},
909
+ ..."version" in declaration && declaration.version ? { version: declaration.version } : {},
910
+ ..."roles" in declaration && declaration.roles === false ? { roles: false } : {},
911
+ ..."table" in declaration && declaration.table ? { table: declaration.table } : {}
912
+ });
913
+ }
914
+ if (options.edge !== false && resources.some((r) => EDGE_KINDS[r.kind] === true)) containers.add("caddy");
915
+ for (const extra of options.extraContainers ?? []) containers.add(extra);
916
+ 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));
917
+ if (cache === "db") {
918
+ const placeless = resources.filter((r) => r.kind === "cache" && !r.of);
919
+ if (placeless.length > 0) {
920
+ const databases = resources.filter((r) => r.kind === "database");
921
+ const [only] = databases;
922
+ if (!only) throw new CacheNeedsDatabase(resources.filter((r) => r.kind === "cache").map((r) => r.id));
923
+ if (databases.length > 1) throw new CacheIsAmbiguous(placeless.map((r) => r.id), databases.map((r) => r.id));
924
+ for (const resource of placeless) resource.of = only.id;
925
+ }
685
926
  }
927
+ const sites = resources.filter((r) => r.kind === "site");
928
+ const root = rootSite(sites.map((r) => {
929
+ const declared = manifest[r.id];
930
+ return {
931
+ name: require_config.appKey(r.id),
932
+ ...declared?.kind === "site" && declared.root ? { root: true } : {}
933
+ };
934
+ }));
935
+ for (const site of sites) if (require_config.appKey(site.id) === root) site.root = true;
936
+ const workerBroker = events === "pgboss" && Object.values(manifest).some((d) => d?.kind === "worker") && resources.some((r) => r.kind === "database");
937
+ return {
938
+ stage,
939
+ events,
940
+ cache,
941
+ containers: [...containers],
942
+ resources,
943
+ ...Object.keys(fakes).length ? { fakes } : {},
944
+ ...workerBroker ? { workerBroker: true } : {}
945
+ };
686
946
  }
687
947
  /**
688
- * The published port mappings for a container.
948
+ * Queues or topics were declared with pg-boss and no database to hold them.
689
949
  *
690
- * Every port is looked up by its own key rather than being derived as an offset
691
- * from the container's first, so MinIO's console cannot land on whatever was
692
- * allocated to the next container.
950
+ * Not a reconcile failure but a manifest one: the fix is a line of application
951
+ * code either way — declare a database, or select a backend that brings its own
952
+ * broker.
693
953
  */
694
- function publish(container, ports) {
695
- return portsOf(container).map((port) => {
696
- const assigned = ports[port.key];
697
- if (assigned === void 0) throw new UnassignedPort(port.key);
698
- return `${assigned}:${port.inside}`;
699
- });
700
- }
701
- /** A planned port that allocation never assigned. */
702
- var UnassignedPort = class extends Error {
703
- /** The port key that went unassigned, e.g. `minio-console`. */
704
- key;
705
- constructor(key) {
706
- super("No port was assigned for this container port");
707
- this.name = "UnassignedPort";
708
- this.key = key;
954
+ var CacheNeedsDatabase = class extends Error {
955
+ ids;
956
+ constructor(ids) {
957
+ 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(", ")}.`);
958
+ this.ids = ids;
959
+ this.name = "CacheNeedsDatabase";
709
960
  }
710
961
  };
711
-
712
- //#endregion
713
- //#region src/reconcile/docker.ts
714
- const run = (0, node_util.promisify)(node_child_process.execFile);
715
- /** How long to wait for containers to pass their health checks. */
716
- const HEALTH_TIMEOUT_MS = 12e4;
717
- const dockerCli = {
718
- async publishedPort(composePath, service, inside) {
719
- try {
720
- const { stdout } = await run("docker", [
721
- "compose",
722
- "-f",
723
- composePath,
724
- "port",
725
- service,
726
- String(inside)
727
- ]);
728
- const port = Number(stdout.trim().split(":").pop());
729
- return Number.isFinite(port) && port > 0 ? port : void 0;
730
- } catch {
731
- return void 0;
732
- }
733
- },
734
- async up(composePath, services) {
735
- await run("docker", [
736
- "compose",
737
- "-f",
738
- composePath,
739
- "up",
740
- "-d",
741
- "--remove-orphans",
742
- "--wait",
743
- `--wait-timeout=${Math.floor(HEALTH_TIMEOUT_MS / 1e3)}`,
744
- ...services
745
- ]);
746
- },
747
- async copyOut(composePath, service, from, to) {
748
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(to), { recursive: true });
749
- await run("docker", [
750
- "compose",
751
- "-f",
752
- composePath,
753
- "cp",
754
- `${service}:${from}`,
755
- to
756
- ]);
757
- },
758
- async reload(composePath, service) {
759
- await run("docker", [
760
- "compose",
761
- "-f",
762
- composePath,
763
- "exec",
764
- "-T",
765
- service,
766
- "caddy",
767
- "reload",
768
- "--config",
769
- "/etc/caddy/Caddyfile"
770
- ]);
771
- },
772
- async healthy(composePath, services) {
773
- if (services.length === 0) return true;
774
- try {
775
- const { stdout } = await run("docker", [
776
- "compose",
777
- "-f",
778
- composePath,
779
- "ps",
780
- "--format",
781
- "json",
782
- ...services
783
- ]);
784
- const running = /* @__PURE__ */ new Set();
785
- for (const line of stdout.trim().split("\n").filter(Boolean)) {
786
- const entry = JSON.parse(line);
787
- const ok = entry.State === "running" && (entry.Health === void 0 || entry.Health === "" || entry.Health === "healthy");
788
- if (ok && entry.Service) running.add(entry.Service);
789
- }
790
- return services.every((service) => running.has(service));
791
- } catch {
792
- return false;
793
- }
962
+ /**
963
+ * A `'db'` cache — a server target's default — in an app that declares more
964
+ * than one database.
965
+ *
966
+ * The target says *a* database and the graph offers several, so there is no
967
+ * answer to give — and the wrong kind of failure would be to pick one, since a
968
+ * cache silently landing in the wrong database is a bug that surfaces as
969
+ * missing rows much later. The fix is a stronger statement in application code:
970
+ * `orders.cache('Sessions')` names the database, which is a fact about the
971
+ * application rather than a deployment choice.
972
+ */
973
+ var CacheIsAmbiguous = class extends Error {
974
+ ids;
975
+ databases;
976
+ constructor(ids, databases) {
977
+ 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(", ")}.`);
978
+ this.ids = ids;
979
+ this.databases = databases;
980
+ this.name = "CacheIsAmbiguous";
981
+ }
982
+ };
983
+ var PgBossNeedsDatabase = class extends Error {
984
+ ids;
985
+ constructor(ids) {
986
+ 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(", ")}.`);
987
+ this.ids = ids;
988
+ this.name = "PgBossNeedsDatabase";
794
989
  }
795
990
  };
796
-
797
991
  //#endregion
798
- //#region src/reconcile/plan.ts
799
- /** The stage whose resources carry no suffix. */
800
- const DEFAULT_STAGE = "development";
992
+ //#region src/reconcile/env.ts
801
993
  /**
802
- * Which container serves a kind.
994
+ * The URLs a reconciled stage injects.
803
995
  *
804
- * Derived kinds map to the same container as their parent — a schema tenant
805
- * lives in its parent's Postgres — so the set is deduplicated rather than
806
- * counted.
996
+ * One `<NAME>_URL` per construct, and the protocol picks the driver. This is the
997
+ * seam between the target that writes a URL and the client that parses it, so
998
+ * every component of it is read off the resource — never inherited from ambient
999
+ * environment. A bucket can live in a different region than the function reading
1000
+ * it, and `AWS_REGION` in a Lambda is the *function's* region, so a URL that
1001
+ * omits `?region=` breaks cross-region silently at runtime.
1002
+ *
1003
+ * Locally that self-containment is what lets the port be whatever was free: the
1004
+ * app reads `ORDERS_URL` and never sees a host or a port.
807
1005
  */
808
- const CONTAINERS = {
809
- database: "postgres",
810
- "database-reader": "postgres",
811
- "database-schema": "postgres",
812
- objects: "minio",
813
- "file-server": "caddy",
814
- email: "mailpit"
1006
+ /**
1007
+ * The credential local containers are brought up with.
1008
+ *
1009
+ * The design's `roles: false` case — both URLs fall back to the cluster's master
1010
+ * credential. A deliberate downgrade, not a default: it holds until the role DDL
1011
+ * lands in `@geekmidas/db`, at which point the runtime role's URL replaces this
1012
+ * and the owner URL stops being reachable from any manifest edge.
1013
+ */
1014
+ const LOCAL_USER$2 = "geekmidas";
1015
+ /** The host containers are published on. */
1016
+ const LOCAL_HOST = "localhost";
1017
+ /** The region local buckets claim, so the client has one to sign with. */
1018
+ const LOCAL_REGION = "us-east-1";
1019
+ /**
1020
+ * The credentials the S3 client resolves for MinIO.
1021
+ *
1022
+ * An `s3://` URL deliberately carries none: deployed, the SDK reads them from
1023
+ * the execution role, so a URL that embedded a key would be one more thing to
1024
+ * rotate and one more thing to leak into a log. Locally there is no role, and
1025
+ * the same chain reads these — which is why they are injected beside the URL
1026
+ * rather than written into it.
1027
+ */
1028
+ const STORAGE_CREDENTIALS = {
1029
+ AWS_ACCESS_KEY_ID: LOCAL_USER$2,
1030
+ AWS_SECRET_ACCESS_KEY: LOCAL_USER$2,
1031
+ AWS_REGION: LOCAL_REGION
815
1032
  };
1033
+ /** The token the local cache proxy accepts. Matches the compose definition. */
1034
+ const LOCAL_TOKEN$1 = "geekmidas";
1035
+ /** The port Mailpit's inbox — its web UI and HTTP API — is published under. */
1036
+ const MAILPIT_INBOX_PORT = "mailpit-web";
1037
+ /** The schema pg-boss keeps its tables in, inside the declared database. */
1038
+ const PGBOSS_SCHEMA = "pgboss";
1039
+ /** The exchange every local topic and queue shares on RabbitMQ. */
1040
+ const RABBITMQ_EXCHANGE = "geekmidas.events";
1041
+ /**
1042
+ * Every env key a reconciled plan resolves, and its value.
1043
+ *
1044
+ * Keys come from the declaration rather than being re-derived, so what the build
1045
+ * publishes and what the app reads cannot drift.
1046
+ */
1047
+ function envFor(plan, options) {
1048
+ const env = {};
1049
+ const resolved = {};
1050
+ for (const resource of plan.resources) {
1051
+ const url = urlFor(resource, plan, options.ports, options.project ?? "", options.addresses);
1052
+ if (url) resolved[resource.id] = url;
1053
+ }
1054
+ for (const resource of plan.resources) {
1055
+ const url = resolved[resource.id];
1056
+ if (resource.kind === "rest-api") Object.assign(env, surfaceEnv(resource, url, resolved, {
1057
+ plan,
1058
+ ...options.addresses ? { addresses: options.addresses } : {},
1059
+ ...options.lanAddress ? { lanAddress: options.lanAddress } : {},
1060
+ ...options.metroPorts ? { metroPorts: options.metroPorts } : {}
1061
+ }));
1062
+ if (url) env[resource.envKey] = url;
1063
+ if (isDatabase(resource.kind) && resource.roles !== false) {
1064
+ const owner = ownerUrl(resource, plan, options.ports, options.project ?? "");
1065
+ if (owner) env[(0, _geekmidas_manifest.provideKey)(resource.id, "ownerUrl")] = owner;
1066
+ }
1067
+ if (resource.kind === "external-api" && url && resource.fake) env[(0, _geekmidas_manifest.provideKey)(resource.id, "credentials")] = resource.fake.credentials;
1068
+ if (resource.kind === "email" && url) {
1069
+ env[(0, _geekmidas_manifest.provideKey)(resource.id, "from")] = options.mailFrom ?? `noreply@${LOCAL_HOST}`;
1070
+ const inbox = options.ports[MAILPIT_INBOX_PORT];
1071
+ if (inbox !== void 0) env[(0, _geekmidas_manifest.provideKey)(resource.id, "inboxUrl")] = `http://${LOCAL_HOST}:${inbox}`;
1072
+ }
1073
+ }
1074
+ Object.assign(env, publicEnv(plan, env, options.addresses));
1075
+ Object.assign(env, brokerEnv(plan, options.ports));
1076
+ if (plan.resources.some((r) => r.kind === "objects" && env[r.envKey])) Object.assign(env, STORAGE_CREDENTIALS);
1077
+ return env;
1078
+ }
1079
+ /**
1080
+ * The values a site's bundler inlines, under the names it inlines them by.
1081
+ *
1082
+ * A rename and nothing more. `API_URL` was resolved once, by the same code that
1083
+ * resolved it for the server; a site reads the same value under `VITE_API_URL`
1084
+ * because that prefix is how its bundler is told to ship it. Nothing is derived
1085
+ * twice, so a site and its API cannot come to disagree about where the API is.
1086
+ *
1087
+ * A source that resolved to nothing is skipped rather than written empty: an
1088
+ * inlined empty string is a frontend that builds and then fails at runtime
1089
+ * against `http:///`, where a missing variable fails at build with the name of
1090
+ * the thing that is missing.
1091
+ */
1092
+ function publicEnv(plan, resolved, addresses = {}) {
1093
+ const env = {};
1094
+ const owners = new Map(plan.resources.map((r) => [r.envKey, r.id]));
1095
+ for (const resource of plan.resources) for (const [key, source] of Object.entries(resource.publicEnv ?? {})) {
1096
+ const value = (resource.kind === "mobile-app" ? addresses[owners.get(source) ?? ""] : void 0) ?? resolved[source];
1097
+ if (value) env[key] = value;
1098
+ }
1099
+ return env;
1100
+ }
816
1101
  /**
817
- * The container a cache backend needs locally.
1102
+ * What a surface publishes beyond its own address: who may call it, and where
1103
+ * a cookie set by it is readable.
818
1104
  *
819
- * Each one matches the protocol its deployed form speaks, which is the property
820
- * worth having: a cache that behaves differently in the two places is worse than
821
- * a slower one.
1105
+ * Both are read off the same list — the constructs that declared an edge to
1106
+ * this surface — which is why neither appears in application code. A surface
1107
+ * that listed its own callers would be edited every time something new called
1108
+ * it, and the thing being edited is already recorded in the graph.
822
1109
  *
823
- * `db` is deliberately absent, the same way `pgboss` is absent from
824
- * `EVENT_CONTAINERS`: the cache is a table in a database the manifest already
825
- * declares, so mapping it here would start a container for a project that needs
826
- * none.
1110
+ * An empty origin list is written, and a surface with no address writes nothing
1111
+ * at all. The two cases look alike and are not: "nothing depends on this yet" is
1112
+ * a real state a target should publish, while "this surface has no address here"
1113
+ * means it is not running in this stage, and keys belong with the address they
1114
+ * describe.
827
1115
  */
828
- const CACHE_CONTAINERS = {
829
- upstash: "redis-http",
830
- elasticache: "redis"
831
- };
1116
+ function surfaceEnv(resource, url, resolved = {}, local = {}) {
1117
+ if (!url) return {};
1118
+ const origins = [...new Set((resource.callers ?? []).map((caller) => resolved[caller]).filter((address) => Boolean(address)).map(originOf).filter((origin) => Boolean(origin)))].sort();
1119
+ const domain = (0, _geekmidas_manifest.cookieDomain)([url, ...origins]);
1120
+ const mobile = (resource.callers ?? []).map((caller) => local.plan?.resources.find((r) => r.id === caller && r.kind === "mobile-app")).filter((caller) => Boolean(caller));
1121
+ const hosts = [...local.lanAddress ? [local.lanAddress] : [], LOCAL_HOST];
1122
+ const schemes = mobile.flatMap((caller) => {
1123
+ const scheme = resolved[caller.id];
1124
+ const port = local.metroPorts?.[caller.id];
1125
+ return scheme ? (0, _geekmidas_manifest.mobileOrigins)(scheme, {
1126
+ hosts,
1127
+ ...port ? { port } : {}
1128
+ }) : [];
1129
+ });
1130
+ const own = local.addresses?.[resource.id];
1131
+ const device = mobile.length > 0 && local.lanAddress && own ? own.replace(/\/\/(localhost|127\.0\.0\.1)(?=[:/]|$)/, `//${local.lanAddress}`) : void 0;
1132
+ return {
1133
+ [(0, _geekmidas_manifest.provideKey)(resource.id, "trustedOrigins")]: [...origins, ...new Set(schemes)].join(","),
1134
+ ...domain ? { [(0, _geekmidas_manifest.provideKey)(resource.id, "cookieDomain")]: domain } : {},
1135
+ ...device ? { [(0, _geekmidas_manifest.provideKey)(resource.id, "deviceUrl")]: device } : {}
1136
+ };
1137
+ }
1138
+ /** An address reduced to the origin a browser compares against. */
1139
+ function originOf(address) {
1140
+ try {
1141
+ return new URL(address).origin;
1142
+ } catch {
1143
+ return;
1144
+ }
1145
+ }
832
1146
  /**
833
- * Kinds that resolve a value without anything running.
1147
+ * The runtime role of whatever a derived node hangs off.
834
1148
  *
835
- * A secret is the case: it has no address, so there is nothing to start and
836
- * nothing to connect to — but it still appears in the plan, because the target
837
- * still has to resolve it.
1149
+ * A reader's parent may itself be a schema tenant, so this follows `of` by one
1150
+ * hop rather than assuming the cluster — the reader of a tenant reads that
1151
+ * tenant's schema, not the database's.
838
1152
  */
839
- const CONTAINERLESS = {
840
- secret: true,
841
- credential: true,
842
- "rest-api": true,
843
- site: true
844
- };
1153
+ function parentRole(resource, plan) {
1154
+ const parent = plan.resources.find((r) => r.id === resource.of);
1155
+ return parent ? localRole(parent) : resource.name;
1156
+ }
1157
+ /** Whether a kind connects to Postgres and therefore has an owner role. */
1158
+ function isDatabase(kind) {
1159
+ return kind === "database" || kind === "database-schema";
1160
+ }
845
1161
  /**
846
- * Containers that cannot run alone.
1162
+ * The URL a migrator connects with — the owner role, which can create, alter
1163
+ * and drop.
847
1164
  *
848
- * The one case is the cache: `serverless-redis-http` is a proxy and needs the
849
- * Redis it proxies. Kept here rather than in the compose definition so the plan
850
- * -- which is what decides what must be running -- still names everything.
1165
+ * Never in `provides`, which is the whole point. A handler that could reach this
1166
+ * could `DROP TABLE`, and the security property the role split exists for is
1167
+ * that it cannot: the value is injected by `gkm exec` for the migrate step and
1168
+ * by nothing else.
851
1169
  */
852
- const REQUIRES = { "redis-http": ["redis"] };
1170
+ function ownerUrl(resource, plan, ports, project) {
1171
+ if (!resource.container) return void 0;
1172
+ const port = ports[primaryPortKey(resource.container)];
1173
+ if (port === void 0) return void 0;
1174
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(localRole(resource));
1175
+ return postgres(port, rootDatabase(resource, plan), {
1176
+ user: owner,
1177
+ password: localRolePassword(project, plan, owner)
1178
+ });
1179
+ }
853
1180
  /**
854
- * The role each kind's one key plays, where it is not a URL.
1181
+ * The shared broker keys, when anything is published or consumed.
855
1182
  *
856
- * The twin of `ProvidesByKind` in `@geekmidas/manifest`: that is what a
857
- * construct declares, this is what the local target resolves, and both derive
858
- * the key from the same `provideKey` so they cannot disagree.
1183
+ * A queue's own key is the producer's. These two are the *connection* itself,
1184
+ * which locally is one broker for every queue and topic in the project: the
1185
+ * generated pollers open a single connection and subscribe each worker by name
1186
+ * on it. Deployed there is no such thing — a Lambda is handed its own event
1187
+ * source — so this pair exists for the local target and says so.
859
1188
  */
860
- const ROLES = {
861
- queue: "publisherConnectionString",
862
- topic: "publisherConnectionString",
863
- credential: "credential"
864
- };
865
- /** The kinds whose container is the events backend's rather than their own. */
866
- const EVENT_KINDS = {
867
- queue: true,
868
- topic: true
869
- };
1189
+ function brokerEnv(plan, ports) {
1190
+ const carrier = plan.resources.find((r) => r.kind === "queue" || r.kind === "topic");
1191
+ const publisher = carrier ? urlFor(carrier, plan, ports, "") : plan.workerBroker ? workerBroker(plan, ports) : void 0;
1192
+ if (!publisher) return {};
1193
+ if (plan.events === "sns") return {};
1194
+ return { EVENT_PUBLISHER_CONNECTION_STRING: publisher };
1195
+ }
870
1196
  /**
871
- * Which kinds provision something *inside* their container.
872
- *
873
- * A database creates a database, a bucket creates a bucket; mail creates
874
- * nothing — Mailpit accepts whatever is sent to it and has no per-stage object
875
- * to name. Both still appear in the plan, because both still resolve a URL; the
876
- * flag is the difference between "must be running" and "must be created".
1197
+ * The broker a worker schedules its crons through, when nothing else declared
1198
+ * one — pg-boss in the declared database, on that database's port.
877
1199
  */
878
- const PROVISIONS = {
879
- database: true,
880
- "database-reader": true,
881
- "database-schema": true,
882
- objects: true,
883
- cache: true,
884
- "file-server": true
885
- };
1200
+ function workerBroker(plan, ports) {
1201
+ const database = plan.resources.find((r) => r.kind === "database");
1202
+ if (!database?.container) return void 0;
1203
+ const port = ports[primaryPortKey(database.container)];
1204
+ return port === void 0 ? void 0 : broker(plan, port);
1205
+ }
886
1206
  /**
887
- * The container each events backend needs, where it needs one of its own.
1207
+ * The URL for one planned resource.
888
1208
  *
889
- * `pgboss` is deliberately absent rather than mapped to `postgres`: it is a
890
- * schema tenant in a database the manifest already declares, so mapping it here
891
- * would start a Postgres for a project that declared no database at all.
1209
+ * Every part of it comes from the resource and the port it was published on.
1210
+ */
1211
+ function urlFor(resource, plan, ports, project, addresses = {}) {
1212
+ if (resource.kind === "secret") return localSecret(project, plan, resource);
1213
+ if (resource.kind === "encryption") return localKeyring(project, plan, resource);
1214
+ if (resource.kind === "mobile-app") return (0, _geekmidas_manifest.schemeBase)(project, resource.scheme);
1215
+ if (resource.kind === "credential") return void 0;
1216
+ if (resource.kind === "external-api") {
1217
+ if (!resource.fake) return resource.url === void 0 ? void 0 : (0, _geekmidas_manifest.externalApiUrl)({
1218
+ id: resource.id,
1219
+ url: resource.url
1220
+ }, plan.stage);
1221
+ const port = ports[resource.fake.key];
1222
+ return port === void 0 ? void 0 : `http://${LOCAL_HOST}:${port}`;
1223
+ }
1224
+ if (resource.kind === "rest-api" || resource.kind === "site") {
1225
+ const address = addresses[resource.id];
1226
+ const edge = plan.containers.includes("caddy") ? ports[primaryPortKey("caddy")] : void 0;
1227
+ return address && edge !== void 0 ? `https://${hostFor(resource, project)}:${edge}` : address;
1228
+ }
1229
+ if (!resource.container) return void 0;
1230
+ const port = ports[primaryPortKey(resource.container)];
1231
+ if (port === void 0) return void 0;
1232
+ switch (resource.kind) {
1233
+ case "database":
1234
+ case "database-schema":
1235
+ case "database-reader": {
1236
+ const database = rootDatabase(resource, plan);
1237
+ if (resource.roles === false) {
1238
+ const schema = schemaOf(resource, plan);
1239
+ return schema ? `${postgres(port, database)}?search_path=${schema}` : postgres(port, database);
1240
+ }
1241
+ const role = resource.kind === "database-reader" ? (0, _geekmidas_db_pg_roles.readerRole)(parentRole(resource, plan)) : localRole(resource);
1242
+ return postgres(port, database, {
1243
+ user: role,
1244
+ password: localRolePassword(project, plan, role)
1245
+ });
1246
+ }
1247
+ case "email": return `smtp://${LOCAL_HOST}:${port}`;
1248
+ case "objects": return `s3://${resource.name}?region=${LOCAL_REGION}&endpoint=http://${LOCAL_HOST}:${port}&forcePathStyle=true`;
1249
+ case "file-server": {
1250
+ const origin = plan.resources.find((r) => r.id === resource.of);
1251
+ if (!origin) return void 0;
1252
+ return plan.containers.includes("caddy") ? `https://${hostFor(resource, project)}:${port}` : `http://${LOCAL_HOST}:${port}/${origin.name}`;
1253
+ }
1254
+ case "cache":
1255
+ if (resource.of) {
1256
+ const parent = plan.resources.find((r) => r.id === resource.of);
1257
+ const url = parent ? urlFor(parent, plan, ports, project, addresses) : void 0;
1258
+ return url ? withTable(url, resource.table ?? (0, _geekmidas_manifest.cacheTable)(resource.id)) : void 0;
1259
+ }
1260
+ switch (plan.cache) {
1261
+ case "elasticache": return `redis://${LOCAL_HOST}:${port}`;
1262
+ default: return `http://:${LOCAL_TOKEN$1}@${LOCAL_HOST}:${port}`;
1263
+ }
1264
+ case "queue":
1265
+ case "topic": return broker(plan, port, resource);
1266
+ default: return;
1267
+ }
1268
+ }
1269
+ /**
1270
+ * The producer's connection string, composed from the backend the plan chose.
892
1271
  *
893
- * This one comes from config rather than from a declaration because there are
894
- * no `topic` or `queue` kinds yet. When they land the mapping moves to
895
- * {@link CONTAINERS} keyed by kind, and this constant goes with them.
1272
+ * The protocol is what picks the transport, so a producer never branches: the
1273
+ * same `.publish()` reaches pg-boss here and SQS deployed because the string it
1274
+ * was handed said so.
896
1275
  */
897
- const EVENT_CONTAINERS = {
898
- sns: "localstack",
899
- rabbitmq: "rabbitmq"
900
- };
901
- /** The backend a project gets when it declares queues or topics and says nothing. */
902
- const DEFAULT_EVENTS = "pgboss";
1276
+ function broker(plan, port, resource) {
1277
+ switch (plan.events) {
1278
+ case "pgboss": {
1279
+ const database = plan.resources.find((r) => r.kind === "database");
1280
+ if (!database) throw new PgBossNeedsDatabase([]);
1281
+ return `pgboss://${LOCAL_USER$2}:${LOCAL_USER$2}@${LOCAL_HOST}:${port}/${database.name}?schema=${PGBOSS_SCHEMA}`;
1282
+ }
1283
+ case "rabbitmq": return `rabbitmq://${LOCAL_USER$2}:${LOCAL_USER$2}@${LOCAL_HOST}:${port}?exchange=${RABBITMQ_EXCHANGE}`;
1284
+ case "sns": {
1285
+ if (!resource) throw new UnprovisionedEventsBackend("sns");
1286
+ const endpoint = emulatorEndpoint(port);
1287
+ const address = resource.kind === "topic" ? _geekmidas_events_sns_url.build({
1288
+ topicArn: emulatorTopicArn(resource.name),
1289
+ region: EMULATOR_REGION,
1290
+ endpoint
1291
+ }) : _geekmidas_events_sqs_url.build({
1292
+ queueUrl: emulatorQueueUrl(resource.name, port),
1293
+ region: EMULATOR_REGION,
1294
+ endpoint
1295
+ });
1296
+ const url = new URL(address);
1297
+ url.searchParams.set("accessKeyId", EMULATOR_CREDENTIALS.accessKeyId);
1298
+ url.searchParams.set("secretAccessKey", EMULATOR_CREDENTIALS.secretAccessKey);
1299
+ return url.toString();
1300
+ }
1301
+ }
1302
+ }
1303
+ /** A local Postgres URL, master credential and all. */
1304
+ function postgres(port, database, credential = {
1305
+ user: LOCAL_USER$2,
1306
+ password: LOCAL_USER$2
1307
+ }) {
1308
+ return `postgres://${credential.user}:${credential.password}@${LOCAL_HOST}:${port}/${database}`;
1309
+ }
903
1310
  /**
904
- * How a resource of each kind separates its stage suffix.
1311
+ * The role a handler connects as, for one database or tenant.
905
1312
  *
906
- * Postgres identifiers are snake_case and a hyphen would need quoting
907
- * everywhere; buckets and queues are kebab and disallow underscores in some
908
- * providers. The suffix is the same word either way.
1313
+ * The construct's id, lowercased and stage-scoped exactly as its database or
1314
+ * schema is — so `Orders` in the `test` stage connects as `orders_test`, and two
1315
+ * stages sharing one cluster cannot share a credential. Roles are cluster-scoped
1316
+ * in Postgres, which is why the suffix is not optional here the way it is for a
1317
+ * schema.
909
1318
  */
910
- const SEPARATORS = {
911
- database: "_",
912
- "database-reader": "_",
913
- "database-schema": "_",
914
- objects: "-"
915
- };
1319
+ function localRole(resource) {
1320
+ return resource.name;
1321
+ }
916
1322
  /**
917
- * The stage-scoped name for a resource.
1323
+ * The password for a derived local role.
1324
+ *
1325
+ * Derived rather than random, for the same reason the local secret is: a
1326
+ * password that changed on every `gkm dev` would lock a developer out of the
1327
+ * data they had a moment ago. Seeded by the project so two checkouts do not
1328
+ * share one, and by the stage so `test` and `development` do not.
918
1329
  *
919
- * The default stage carries no suffix, so `gkm dev` keeps using `orders` and a
920
- * developer's psql history, saved connections, and muscle memory survive this
921
- * change. Every other stage is suffixed.
1330
+ * It is a *local* credential by construction — the cluster is on loopback and
1331
+ * the seed is a checkout path — and no deployed target uses this function.
922
1332
  */
923
- function resourceName(id, kind, stage) {
924
- const base = id.toLowerCase();
925
- if (stage === DEFAULT_STAGE) return base;
926
- return `${base}${SEPARATORS[kind] ?? "-"}${stage}`;
1333
+ function localRolePassword(project, plan, role) {
1334
+ return (0, node_crypto.createHash)("sha256").update(`${project}:${plan.stage}:role:${role}`).digest("base64url").slice(0, 32);
927
1335
  }
928
1336
  /**
929
- * The container a kind needs, or `undefined` if it needs none.
1337
+ * A cache's address: its database's URL, carrying the table it reads.
930
1338
  *
931
- * Queues and topics have no container of their own — they live in whichever
932
- * broker the project selected, which is why the backend is an argument here
933
- * rather than a second pass that adds containers after the fact.
1339
+ * Appended rather than kept beside the URL as a second key, for the reason the
1340
+ * design gives everywhere else — an address and what it opens are one fact, and
1341
+ * two keys are one more thing to keep in step.
934
1342
  */
935
- function containerFor(kind, events = DEFAULT_EVENTS, cache = require_discover.DEFAULT_CACHE.aws, derived = false, edge = true) {
936
- if (EVENT_KINDS[kind]) return EVENT_CONTAINERS[events] ?? CONTAINERS.database;
937
- if (kind === "file-server") return edge ? "caddy" : CONTAINERS.objects;
938
- if (kind === "cache") {
939
- if (derived) return CONTAINERS.database;
940
- return CACHE_CONTAINERS[cache] ?? CONTAINERS.database;
941
- }
942
- return CONTAINERS[kind];
1343
+ function withTable(url, table) {
1344
+ const parsed = new URL(url);
1345
+ parsed.searchParams.set("table", table);
1346
+ return parsed.toString();
943
1347
  }
944
1348
  /**
945
- * Build the plan for a manifest and stage.
1349
+ * The physical database a derived resource lives in.
946
1350
  *
947
- * `order` is the caller's provisioning order — parents before children — which
948
- * `provisionOrder` produces from the manifest. Passing it in keeps this
949
- * function free of the traversal and makes the ordering assertable on its own.
1351
+ * Walks `of` to the top rather than reading the immediate parent, because a
1352
+ * reader's parent may itself be a schema tenant — two hops from the database
1353
+ * that actually exists.
950
1354
  */
951
- function planFor(manifest, stage, order, options = {}) {
952
- const containers = /* @__PURE__ */ new Set();
953
- const resources = [];
954
- const events = options.events ?? DEFAULT_EVENTS;
955
- const cache = options.cache ?? require_discover.DEFAULT_CACHE.aws;
956
- for (const id of order) {
957
- const declaration = manifest[id];
958
- if (!declaration) continue;
959
- const container = containerFor(declaration.kind, events, cache, "of" in declaration && typeof declaration.of === "string", options.edge !== false);
960
- if (!container && !CONTAINERLESS[declaration.kind]) continue;
961
- if (container) {
962
- containers.add(container);
963
- for (const required of REQUIRES[container] ?? []) containers.add(required);
964
- }
965
- resources.push({
966
- id,
967
- kind: declaration.kind,
968
- ...container ? { container } : {},
969
- name: resourceName(id, declaration.kind, stage),
970
- envKey: (0, __geekmidas_manifest.providedKeyFor)(id, declaration.kind, ROLES[declaration.kind] ?? "url"),
971
- provisions: PROVISIONS[declaration.kind] === true,
972
- ...declaration.kind === "rest-api" ? { callers: (0, __geekmidas_manifest.dependentsOf)(manifest, id) } : {},
973
- ...declaration.kind === "site" ? { publicEnv: (0, __geekmidas_manifest.publicEnvFor)(declaration, manifest) } : {},
974
- ...declaration.kind === "file-server" && declaration.open?.length ? { open: declaration.open } : {},
975
- ..."of" in declaration ? { of: declaration.of } : {},
976
- ..."schema" in declaration && declaration.schema ? { schema: declaration.schema } : {},
977
- ..."version" in declaration && declaration.version ? { version: declaration.version } : {},
978
- ..."roles" in declaration && declaration.roles === false ? { roles: false } : {},
979
- ..."table" in declaration && declaration.table ? { table: declaration.table } : {}
980
- });
1355
+ function rootDatabase(resource, plan) {
1356
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
1357
+ let current = resource;
1358
+ while (current.of) {
1359
+ const parent = byId.get(current.of);
1360
+ if (!parent) break;
1361
+ current = parent;
981
1362
  }
982
- if (options.edge !== false && resources.some((r) => EDGE_KINDS[r.kind] === true)) containers.add("caddy");
983
- for (const extra of options.extraContainers ?? []) containers.add(extra);
984
- 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));
985
- if (cache === "db") {
986
- const placeless = resources.filter((r) => r.kind === "cache" && !r.of);
987
- if (placeless.length > 0) {
988
- const databases = resources.filter((r) => r.kind === "database");
989
- const [only] = databases;
990
- if (!only) throw new CacheNeedsDatabase(resources.filter((r) => r.kind === "cache").map((r) => r.id));
991
- if (databases.length > 1) throw new CacheIsAmbiguous(placeless.map((r) => r.id), databases.map((r) => r.id));
992
- for (const resource of placeless) resource.of = only.id;
993
- }
1363
+ return current.name;
1364
+ }
1365
+ /** The schema a derived resource puts on its search path, if it has one. */
1366
+ function schemaOf(resource, plan) {
1367
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
1368
+ let current = resource;
1369
+ while (current) {
1370
+ if (current.kind === "database-schema") return current.schema;
1371
+ current = current.of ? byId.get(current.of) : void 0;
994
1372
  }
995
- return {
996
- stage,
997
- events,
998
- cache,
999
- containers: [...containers],
1000
- resources
1001
- };
1002
1373
  }
1003
1374
  /**
1004
- * Queues or topics were declared with pg-boss and no database to hold them.
1375
+ * A broker address asked for without the topic or queue it would name.
1005
1376
  *
1006
- * Not a reconcile failure but a manifest one: the fix is a line of application
1007
- * code either way — declare a database, or select a backend that brings its own
1008
- * broker.
1377
+ * On SNS each topic and queue is its own address, so there is no project-wide
1378
+ * one to hand out — a cron's schedule store, say, cannot live there.
1009
1379
  */
1010
- var CacheNeedsDatabase = class extends Error {
1011
- constructor(ids) {
1012
- super(`A cache backed by the database needs a declared database, and none was declared. Declare one, or set services.cache to 'upstash' or 'elasticache'. Caches affected: ${ids.join(", ")}.`);
1013
- this.ids = ids;
1014
- this.name = "CacheNeedsDatabase";
1380
+ var UnprovisionedEventsBackend = class extends Error {
1381
+ backend;
1382
+ constructor(backend) {
1383
+ super(`'${backend}' has no single broker address: each topic and queue is addressed by its own ARN. Something asked for one without naming the topic or queue.`);
1384
+ this.backend = backend;
1385
+ this.name = "UnprovisionedEventsBackend";
1015
1386
  }
1016
1387
  };
1017
1388
  /**
1018
- * `services.cache: 'db'` in an app that declares more than one database.
1389
+ * The keyring an `Encryption` construct resolves to locally.
1390
+ *
1391
+ * Derived like a secret — stable across restarts, distinct per project, stage
1392
+ * and construct, never written to disk — so what `gkm dev` encrypted yesterday
1393
+ * still opens today. One key, because nothing local is worth rotating: a
1394
+ * server stage's keyring is generated and rotated in its secrets instead.
1395
+ */
1396
+ function localKeyring(project, plan, resource) {
1397
+ const derive = (purpose) => (0, node_crypto.createHash)("sha256").update(`${project}:${plan.stage}:${resource.id}:${purpose}`).digest();
1398
+ return (0, _geekmidas_constructs_encryption.formatKeyring)({
1399
+ keys: [{
1400
+ id: "k1",
1401
+ key: derive("k1")
1402
+ }],
1403
+ index: derive("index")
1404
+ });
1405
+ }
1406
+ /**
1407
+ * The value a secret resolves to locally.
1019
1408
  *
1020
- * The config says *a* database and the graph offers several, so there is no
1021
- * answer to give — and the wrong kind of failure would be to pick one, since a
1022
- * cache silently landing in the wrong database is a bug that surfaces as
1023
- * missing rows much later. The fix is a stronger statement in application code:
1024
- * `orders.cache('Sessions')` names the database, which is a fact about the
1025
- * application rather than a deployment choice.
1409
+ * A hash of what identifies it, so it is stable, distinct per project, stage
1410
+ * and construct, and never written to disk as a literal. Deployed this is the
1411
+ * one kind whose value does *not* come from here — a secret manager generates
1412
+ * it once and the target reads it back.
1026
1413
  */
1027
- var CacheIsAmbiguous = class extends Error {
1028
- constructor(ids, databases) {
1029
- 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 with services.cache. Caches affected: ${ids.join(", ")}.`);
1030
- this.ids = ids;
1031
- this.databases = databases;
1032
- this.name = "CacheIsAmbiguous";
1033
- }
1034
- };
1035
- var PgBossNeedsDatabase = class extends Error {
1036
- constructor(ids) {
1037
- super(`pg-boss keeps its queues in a declared database, and none was declared. Declare one, or set services.events to 'rabbitmq' or 'sns'. Queues and topics affected: ${ids.join(", ")}.`);
1038
- this.ids = ids;
1039
- this.name = "PgBossNeedsDatabase";
1040
- }
1041
- };
1042
-
1414
+ function localSecret(project, plan, resource) {
1415
+ return (0, node_crypto.createHash)("sha256").update(`${project}:${plan.stage}:${resource.id}`).digest("base64url").slice(0, 43);
1416
+ }
1043
1417
  //#endregion
1044
- //#region src/reconcile/env.ts
1418
+ //#region src/reconcile/apps.ts
1045
1419
  /**
1046
- * The credential local containers are brought up with.
1420
+ * The apps, as services beside the containers their constructs derive.
1047
1421
  *
1048
- * The design's `roles: false` case — both URLs fall back to the cluster's master
1049
- * credential. A deliberate downgrade, not a default: it holds until the role DDL
1050
- * lands in `@geekmidas/db`, at which point the runtime role's URL replaces this
1051
- * and the owner URL stops being reachable from any manifest edge.
1422
+ * `gkm docker` used to write these by hand: every backend got
1423
+ * `DATABASE_URL=postgresql://…@postgres:5432/app` and `REDIS_URL=redis://redis`,
1424
+ * which was right only for a project whose single database happened to be
1425
+ * called `Database` — an `Orders` database publishes `ORDERS_URL`, a schema
1426
+ * tenant has a URL of its own, and buckets and mail were not wired at all.
1427
+ *
1428
+ * Now an app's environment is exactly what reconcile hands `gkm dev`: every key
1429
+ * the declared constructs provide, from the same derivation. The only
1430
+ * difference is where the addresses point — at the containers by service name
1431
+ * on the compose network, rather than at `localhost` on the ports published for
1432
+ * the host.
1433
+ *
1434
+ * Always from the *local* stage's plan, whichever stage is being reconciled:
1435
+ * `gkm test` rewrites the same file, and running the tests must not quietly
1436
+ * point these apps at the test databases.
1052
1437
  */
1053
- const LOCAL_USER = "geekmidas";
1054
- /** The host containers are published on. */
1055
- const LOCAL_HOST = "localhost";
1056
- /** The region local buckets claim, so the client has one to sign with. */
1057
- const LOCAL_REGION = "us-east-1";
1438
+ /** The profile app services carry, so `gkm dev` starts only the containers. */
1439
+ const APPS_PROFILE = "apps";
1058
1440
  /**
1059
- * The credentials the S3 client resolves for MinIO.
1441
+ * Where an app's image is built from.
1060
1442
  *
1061
- * An `s3://` URL deliberately carries none: deployed, the SDK reads them from
1062
- * the execution role, so a URL that embedded a key would be one more thing to
1063
- * rotate and one more thing to leak into a log. Locally there is no role, and
1064
- * the same chain reads these — which is why they are injected beside the URL
1065
- * rather than written into it.
1443
+ * An app at the project root is a single-app project, whose `gkm docker`
1444
+ * writes `.gkm/docker/Dockerfile`; a workspace writes one per app.
1066
1445
  */
1067
- const STORAGE_CREDENTIALS = {
1068
- AWS_ACCESS_KEY_ID: LOCAL_USER,
1069
- AWS_SECRET_ACCESS_KEY: LOCAL_USER,
1070
- AWS_REGION: LOCAL_REGION
1071
- };
1072
- /** The token the local cache proxy accepts. Matches the compose definition. */
1073
- const LOCAL_TOKEN = "geekmidas";
1074
- /** The schema pg-boss keeps its tables in, inside the declared database. */
1075
- const PGBOSS_SCHEMA = "pgboss";
1076
- /** The exchange every local topic and queue shares on RabbitMQ. */
1077
- const RABBITMQ_EXCHANGE = "geekmidas.events";
1446
+ function dockerfileOf(appName, path) {
1447
+ return path === "." ? ".gkm/docker/Dockerfile" : `.gkm/docker/Dockerfile.${appName}`;
1448
+ }
1078
1449
  /**
1079
- * Every env key a reconciled plan resolves, and its value.
1450
+ * Every construct key, addressed across the compose network.
1080
1451
  *
1081
- * Keys come from the declaration rather than being re-derived, so what the build
1082
- * publishes and what the app reads cannot drift.
1452
+ * `envFor` is asked with a placeholder port for every port key, so each
1453
+ * `localhost:<placeholder>` in its answer names exactly one container port —
1454
+ * two containers listening on the same port inside cannot be confused — and is
1455
+ * rewritten to `<container>:<inside>`.
1083
1456
  */
1084
- function envFor(plan, options) {
1085
- const env = {};
1086
- const resolved = {};
1087
- for (const resource of plan.resources) {
1088
- const url = urlFor(resource, plan, options.ports, options.project ?? "", options.addresses);
1089
- if (url) resolved[resource.id] = url;
1457
+ function inNetworkEnv(workspace, manifest, fakes = {}) {
1458
+ const plan = planFor(manifest, workspace.stages.local, (0, _geekmidas_manifest.provisionOrder)(manifest), {
1459
+ localStage: workspace.stages.local,
1460
+ ...backendsOf(workspace),
1461
+ fakes
1462
+ });
1463
+ const placeholders = {};
1464
+ const targets = /* @__PURE__ */ new Map();
1465
+ let next = 49152;
1466
+ for (const container of [...plan.containers].sort()) for (const port of portsOf(container, plan.fakes)) {
1467
+ placeholders[port.key] = next;
1468
+ targets.set(next, `${container}:${port.inside}`);
1469
+ next += 1;
1090
1470
  }
1091
- for (const resource of plan.resources) {
1092
- const url = resolved[resource.id];
1093
- if (resource.kind === "rest-api") Object.assign(env, surfaceEnv(resource, url, resolved));
1094
- if (url) env[resource.envKey] = url;
1095
- if (isDatabase(resource.kind) && resource.roles !== false) {
1096
- const owner = ownerUrl(resource, plan, options.ports, options.project ?? "");
1097
- if (owner) env[(0, __geekmidas_manifest.provideKey)(resource.id, "ownerUrl")] = owner;
1471
+ for (const key of portKeys(plan.containers, plan.fakes)) placeholders[key] ??= next++;
1472
+ const env = envFor(plan, {
1473
+ ports: placeholders,
1474
+ project: workspace.name,
1475
+ addresses: surfaceAddresses(workspace, manifest, (app, port) => `http://${app}:${port}`)
1476
+ });
1477
+ const rewrite = (value) => value.replace(/(?:localhost|127\.0\.0\.1):(\d+)/g, (match, port) => {
1478
+ return targets.get(Number(port)) ?? match;
1479
+ });
1480
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, rewrite(value)]));
1481
+ }
1482
+ /**
1483
+ * The keys one app's environment may hold: what its own declaration provides
1484
+ * and requires, and what each construct it has an edge to provides.
1485
+ *
1486
+ * The edges, not the manifest. Every app used to be handed every key the
1487
+ * workspace resolved — a web app got the database's owner URL and the auth
1488
+ * server's signing secret, and the API got the auth server's database — which
1489
+ * is exactly what a declared edge exists to rule out. A deploy composes an
1490
+ * app's environment from its edges; so does this.
1491
+ *
1492
+ * One hop: a surface an app calls is reached over HTTP, so its URL is the
1493
+ * app's business and its database is not. A site also gets the public
1494
+ * variant of each key its bundle inlines (`NEXT_PUBLIC_API_URL`), and a surface
1495
+ * the edges of the workers whose crons and subscribers its server runs.
1496
+ *
1497
+ * `undefined` for an app no declaration describes, which gets nothing but its
1498
+ * port.
1499
+ */
1500
+ function appEnvKeys(manifest, appName, runnables = {}) {
1501
+ const entry = Object.entries(manifest).find(([id, d]) => (d.kind === "rest-api" || d.kind === "site" || d.kind === "mobile-app") && require_config.appKey(id) === appName);
1502
+ if (!entry) return void 0;
1503
+ const [id, declaration] = entry;
1504
+ const keys = /* @__PURE__ */ new Set([
1505
+ ...declaration.provides ?? [],
1506
+ ...declaration.requires ?? [],
1507
+ ...declaration.kind === "rest-api" ? declaration.endpoints.flatMap((endpoint) => endpoint.requires ?? []) : []
1508
+ ]);
1509
+ const edges = [...(0, _geekmidas_manifest.dependenciesOf)(declaration).map((edge) => edge.target), ...runnables[id] ?? []];
1510
+ if (declaration.kind === "rest-api" && declaration.endpoints.length === 0) {
1511
+ const runsWorkers = Object.values(manifest).some((other) => other.kind === "worker");
1512
+ for (const [otherId, other] of Object.entries(manifest)) {
1513
+ if (other.kind !== "worker") continue;
1514
+ edges.push(...(0, _geekmidas_manifest.dependenciesOf)(other).map((edge) => edge.target), ...runnables[otherId] ?? []);
1515
+ keys.add("EVENT_PUBLISHER_CONNECTION_STRING");
1516
+ }
1517
+ if (runsWorkers) for (const other of Object.values(manifest)) {
1518
+ if (other.kind !== "queue" && other.kind !== "topic") continue;
1519
+ for (const key of other.provides ?? []) keys.add(key);
1098
1520
  }
1099
- if (resource.kind === "email" && url) env[(0, __geekmidas_manifest.provideKey)(resource.id, "from")] = options.mailFrom ?? `noreply@${LOCAL_HOST}`;
1100
1521
  }
1101
- Object.assign(env, publicEnv(plan, env));
1102
- Object.assign(env, brokerEnv(plan, options.ports));
1103
- if (plan.resources.some((r) => r.kind === "objects" && env[r.envKey])) Object.assign(env, STORAGE_CREDENTIALS);
1104
- return env;
1522
+ for (const id of edges) {
1523
+ const target = manifest[id];
1524
+ if (!target) continue;
1525
+ for (const key of target.provides ?? []) keys.add(key);
1526
+ if (target.kind === "queue" || target.kind === "topic") keys.add("EVENT_PUBLISHER_CONNECTION_STRING");
1527
+ if (target.kind === "objects") {
1528
+ keys.add("AWS_ACCESS_KEY_ID");
1529
+ keys.add("AWS_SECRET_ACCESS_KEY");
1530
+ keys.add("AWS_REGION");
1531
+ }
1532
+ }
1533
+ if (declaration.kind === "site" || declaration.kind === "mobile-app") for (const key of Object.keys((0, _geekmidas_manifest.publicEnvFor)(declaration, manifest))) keys.add(key);
1534
+ return keys;
1535
+ }
1536
+ /** One compose service per app the workspace runs, behind the apps profile. */
1537
+ function appServices(workspace, manifest, containers, runnables = {}, fakes = {}) {
1538
+ const env = inNetworkEnv(workspace, manifest, fakes);
1539
+ const services = {};
1540
+ for (const [name, app] of Object.entries(workspace.apps)) {
1541
+ if (app.type === "mobile" || !app.port) continue;
1542
+ const key = require_config.appKey(name);
1543
+ const health = app.type === "web" ? "/" : "/health";
1544
+ const allowed = appEnvKeys(manifest, name, runnables);
1545
+ const own = Object.fromEntries(Object.entries(env).filter(([envKey]) => allowed?.has(envKey)));
1546
+ services[key] = {
1547
+ image: `${key}:\${TAG:-latest}`,
1548
+ build: {
1549
+ context: ".",
1550
+ dockerfile: dockerfileOf(name, app.path)
1551
+ },
1552
+ profiles: [APPS_PROFILE],
1553
+ ports: [`${app.port}:${app.port}`],
1554
+ environment: {
1555
+ NODE_ENV: "production",
1556
+ PORT: String(app.port),
1557
+ ...own
1558
+ },
1559
+ ...containers.some((c) => c !== "caddy") ? { depends_on: containers.filter((c) => c !== "caddy") } : {},
1560
+ healthcheck: {
1561
+ test: [
1562
+ "CMD",
1563
+ "wget",
1564
+ "-q",
1565
+ "--spider",
1566
+ `http://localhost:${app.port}${health}`
1567
+ ],
1568
+ interval: "10s",
1569
+ timeout: "5s",
1570
+ retries: 5
1571
+ }
1572
+ };
1573
+ }
1574
+ return services;
1105
1575
  }
1576
+ //#endregion
1577
+ //#region src/reconcile/clients.ts
1106
1578
  /**
1107
- * The values a site's bundler inlines, under the names it inlines them by.
1579
+ * The real Postgres and MinIO clients the applier runs against.
1108
1580
  *
1109
- * A rename and nothing more. `API_URL` was resolved once, by the same code that
1110
- * resolved it for the server; a site reads the same value under `VITE_API_URL`
1111
- * because that prefix is how its bundler is told to ship it. Nothing is derived
1112
- * twice, so a site and its API cannot come to disagree about where the API is.
1581
+ * Kept apart from `provision.ts` so the rules there — what gets created, in what
1582
+ * order, and never dropping anything — are asserted against fakes, while the
1583
+ * drivers live here where there is nothing to assert but wiring.
1113
1584
  *
1114
- * A source that resolved to nothing is skipped rather than written empty: an
1115
- * inlined empty string is a frontend that builds and then fails at runtime
1116
- * against `http:///`, where a missing variable fails at build with the name of
1117
- * the thing that is missing.
1585
+ * Both are constructed from the same local addresses the env writer composes,
1586
+ * so the applier cannot end up talking to a different container than the app.
1118
1587
  */
1119
- function publicEnv(plan, resolved) {
1120
- const env = {};
1121
- for (const resource of plan.resources) for (const [key, source] of Object.entries(resource.publicEnv ?? {})) {
1122
- const value = resolved[source];
1123
- if (value) env[key] = value;
1124
- }
1125
- return env;
1126
- }
1588
+ /** The credential local containers are brought up with. */
1589
+ const LOCAL_USER$1 = "geekmidas";
1127
1590
  /**
1128
- * What a surface publishes beyond its own address: who may call it, and where
1129
- * a cookie set by it is readable.
1130
- *
1131
- * Both are read off the same list — the constructs that declared an edge to
1132
- * this surface — which is why neither appears in application code. A surface
1133
- * that listed its own callers would be edited every time something new called
1134
- * it, and the thing being edited is already recorded in the graph.
1591
+ * A Postgres client that opens one connection per database it is asked about.
1135
1592
  *
1136
- * An empty origin list is written, and a surface with no address writes nothing
1137
- * at all. The two cases look alike and are not: "nothing depends on this yet" is
1138
- * a real state a target should publish, while "this surface has no address here"
1139
- * means it is not running in this stage, and keys belong with the address they
1140
- * describe.
1593
+ * `CREATE DATABASE` cannot run from a connection to the database being created,
1594
+ * and a schema must be created from inside its own database — so the database is
1595
+ * part of each query rather than fixed when the client is built.
1141
1596
  */
1142
- function surfaceEnv(resource, url, resolved = {}) {
1143
- if (!url) return {};
1144
- const origins = [...new Set((resource.callers ?? []).map((caller) => resolved[caller]).filter((address) => Boolean(address)).map(originOf).filter((origin) => Boolean(origin)))].sort();
1145
- const domain = (0, __geekmidas_manifest.cookieDomain)([url, ...origins]);
1597
+ function pgClient(port) {
1598
+ return { async query(database, sql, values) {
1599
+ const client = new pg.Client({
1600
+ host: "localhost",
1601
+ port,
1602
+ user: LOCAL_USER$1,
1603
+ password: LOCAL_USER$1,
1604
+ database: database ?? LOCAL_USER$1
1605
+ });
1606
+ await client.connect();
1607
+ try {
1608
+ return (await client.query(sql, values)).rows;
1609
+ } finally {
1610
+ await client.end();
1611
+ }
1612
+ } };
1613
+ }
1614
+ /** A bucket client pointed at the local MinIO. */
1615
+ function bucketClient(port) {
1616
+ const s3 = new _aws_sdk_client_s3.S3Client({
1617
+ region: "us-east-1",
1618
+ endpoint: `http://localhost:${port}`,
1619
+ forcePathStyle: true,
1620
+ credentials: {
1621
+ accessKeyId: LOCAL_USER$1,
1622
+ secretAccessKey: LOCAL_USER$1
1623
+ }
1624
+ });
1625
+ return {
1626
+ async exists(bucket) {
1627
+ try {
1628
+ await s3.send(new _aws_sdk_client_s3.HeadBucketCommand({ Bucket: bucket }));
1629
+ return true;
1630
+ } catch {
1631
+ return false;
1632
+ }
1633
+ },
1634
+ async create(bucket) {
1635
+ await s3.send(new _aws_sdk_client_s3.CreateBucketCommand({ Bucket: bucket }));
1636
+ },
1637
+ async policy(bucket) {
1638
+ try {
1639
+ return (await s3.send(new _aws_sdk_client_s3.GetBucketPolicyCommand({ Bucket: bucket }))).Policy;
1640
+ } catch {
1641
+ return;
1642
+ }
1643
+ },
1644
+ async setPolicy(bucket, policy) {
1645
+ await s3.send(new _aws_sdk_client_s3.PutBucketPolicyCommand({
1646
+ Bucket: bucket,
1647
+ Policy: policy
1648
+ }));
1649
+ }
1650
+ };
1651
+ }
1652
+ /** A topic and queue client pointed at the local AWS emulator. */
1653
+ function carrierClient(port) {
1654
+ const config = {
1655
+ region: EMULATOR_REGION,
1656
+ endpoint: emulatorEndpoint(port),
1657
+ credentials: EMULATOR_CREDENTIALS
1658
+ };
1659
+ const sns = new _aws_sdk_client_sns.SNSClient(config);
1660
+ const sqs = new _aws_sdk_client_sqs.SQSClient(config);
1146
1661
  return {
1147
- [(0, __geekmidas_manifest.provideKey)(resource.id, "trustedOrigins")]: origins.join(","),
1148
- ...domain ? { [(0, __geekmidas_manifest.provideKey)(resource.id, "cookieDomain")]: domain } : {}
1662
+ async topicExists(name) {
1663
+ try {
1664
+ await sns.send(new _aws_sdk_client_sns.GetTopicAttributesCommand({ TopicArn: emulatorTopicArn(name) }));
1665
+ return true;
1666
+ } catch {
1667
+ return false;
1668
+ }
1669
+ },
1670
+ async createTopic(name) {
1671
+ await sns.send(new _aws_sdk_client_sns.CreateTopicCommand({ Name: name }));
1672
+ },
1673
+ async queueExists(name) {
1674
+ try {
1675
+ await sqs.send(new _aws_sdk_client_sqs.GetQueueUrlCommand({ QueueName: name }));
1676
+ return true;
1677
+ } catch {
1678
+ return false;
1679
+ }
1680
+ },
1681
+ async createQueue(name) {
1682
+ await sqs.send(new _aws_sdk_client_sqs.CreateQueueCommand({ QueueName: name }));
1683
+ }
1149
1684
  };
1150
1685
  }
1151
- /** An address reduced to the origin a browser compares against. */
1152
- function originOf(address) {
1153
- try {
1154
- return new URL(address).origin;
1155
- } catch {
1156
- return void 0;
1157
- }
1158
- }
1686
+ //#endregion
1687
+ //#region src/reconcile/compose.ts
1159
1688
  /**
1160
- * The runtime role of whatever a derived node hangs off.
1689
+ * The compose document a plan implies.
1161
1690
  *
1162
- * A reader's parent may itself be a schema tenant, so this follows `of` by one
1163
- * hop rather than assuming the cluster — the reader of a tenant reads that
1164
- * tenant's schema, not the database's.
1691
+ * The third declaration of the same containers disappears here: today a
1692
+ * `services: ['postgres','minio']` block is kept in step with the code by hand,
1693
+ * which is the triplication this design exists to remove, in the one place you
1694
+ * touch every day. A `database` implies Postgres; the list is derived.
1695
+ *
1696
+ * Returns an object rather than a string for the same reason `plan` is pure —
1697
+ * what should exist is asserted as data, and turning it into YAML is one line at
1698
+ * the edge.
1699
+ *
1700
+ * What stays config is unchanged: images and versions are pinned explicitly, and
1701
+ * a container no construct implies is still declared by hand. Neutral facts come
1702
+ * from the declaration, provider detail from config.
1165
1703
  */
1166
- function parentRole(resource, plan) {
1167
- const parent = plan.resources.find((r) => r.id === resource.of);
1168
- return parent ? localRole(parent) : resource.name;
1169
- }
1170
- /** Whether a kind connects to Postgres and therefore has an owner role. */
1171
- function isDatabase(kind) {
1172
- return kind === "database" || kind === "database-schema";
1173
- }
1704
+ /** The credential every derived container is brought up with locally. */
1705
+ const LOCAL_USER = "geekmidas";
1174
1706
  /**
1175
- * The URL a migrator connects with — the owner role, which can create, alter
1176
- * and drop.
1707
+ * The token the local cache accepts.
1177
1708
  *
1178
- * Never in `provides`, which is the whole point. A handler that could reach this
1179
- * could `DROP TABLE`, and the security property the role split exists for is
1180
- * that it cannot: the value is injected by `gkm exec` for the migrate step and
1181
- * by nothing else.
1709
+ * Fixed rather than generated: it is only ever reachable on a port this project
1710
+ * published, and the URL that carries it is derived, so nothing is made safer
1711
+ * by making it unguessable and a stable one keeps `redis-cli` sessions working.
1182
1712
  */
1183
- function ownerUrl(resource, plan, ports, project) {
1184
- if (!resource.container) return void 0;
1185
- const port = ports[primaryPortKey(resource.container)];
1186
- if (port === void 0) return void 0;
1187
- const owner = (0, __geekmidas_db_pg_roles.ownerRole)(localRole(resource));
1188
- return postgres(port, rootDatabase(resource, plan), {
1189
- user: owner,
1190
- password: localRolePassword(project, plan, owner)
1191
- });
1192
- }
1713
+ const LOCAL_TOKEN = "geekmidas";
1193
1714
  /**
1194
- * The shared broker keys, when anything is published or consumed.
1715
+ * Build the compose document for a plan.
1195
1716
  *
1196
- * A queue's own key is the producer's. These two are the *connection* itself,
1197
- * which locally is one broker for every queue and topic in the project: the
1198
- * generated pollers open a single connection and subscribe each worker by name
1199
- * on it. Deployed there is no such thing — a Lambda is handed its own event
1200
- * source — so this pair exists for the local target and says so.
1717
+ * Every container is published on its assigned port, never on the image's
1718
+ * default: the point of allocation is that two projects can run at once, and
1719
+ * one container publishing 5432 puts that back.
1201
1720
  */
1202
- function brokerEnv(plan, ports) {
1203
- const carrier = plan.resources.find((r) => r.kind === "queue" || r.kind === "topic");
1204
- if (!carrier) return {};
1205
- const publisher = urlFor(carrier, plan, ports, "");
1206
- if (!publisher) return {};
1721
+ function composeFor(plan, options) {
1722
+ const services = {};
1723
+ const volumes = {};
1724
+ for (const container of [...plan.containers].sort()) {
1725
+ const declared = container === "postgres" ? plan.resources.find((r) => r.version)?.version : void 0;
1726
+ const fake = plan.fakes?.[container];
1727
+ const image = declared ? postgresImage(declared) : fake?.image ?? DEFAULT_IMAGES[container];
1728
+ if (!image) throw new UnknownContainer(container);
1729
+ const published = publish(container, options.ports, plan.fakes);
1730
+ services[container] = fake ? {
1731
+ image,
1732
+ restart: "unless-stopped",
1733
+ ports: published
1734
+ } : define(container, image, published);
1735
+ const volume = volumeOf(container);
1736
+ if (volume) volumes[volume] = {};
1737
+ }
1207
1738
  return {
1208
- EVENT_PUBLISHER_CONNECTION_STRING: publisher,
1209
- EVENT_SUBSCRIBER_CONNECTION_STRING: plan.events === "sns" ? publisher.replace(/^sns:/, "sqs:") : publisher
1739
+ name: options.project,
1740
+ services: {
1741
+ ...services,
1742
+ ...options.apps
1743
+ },
1744
+ ...Object.keys(volumes).length ? { volumes } : {}
1210
1745
  };
1211
1746
  }
1212
- /**
1213
- * The URL for one planned resource.
1214
- *
1215
- * Every part of it comes from the resource and the port it was published on.
1216
- */
1217
- function urlFor(resource, plan, ports, project, addresses = {}) {
1218
- if (resource.kind === "secret") return localSecret(project, plan, resource);
1219
- if (resource.kind === "credential") return void 0;
1220
- if (resource.kind === "rest-api" || resource.kind === "site") {
1221
- const address = addresses[resource.id];
1222
- const edge = plan.containers.includes("caddy") ? ports[primaryPortKey("caddy")] : void 0;
1223
- return address && edge !== void 0 ? `https://${hostFor(resource, project)}:${edge}` : address;
1747
+ /** Render a compose document as the file it becomes. */
1748
+ function toYaml(file) {
1749
+ return `# Generated by gkm from the construct manifest — do not edit.
1750
+ # Containers are derived from what the app declares. Image pins and anything
1751
+ # no construct implies go in your own docker-compose.yml, which is merged over
1752
+ # this file and wins:
1753
+ #
1754
+ # docker compose -f docker-compose.constructs.yml -f docker-compose.yml …
1755
+ #
1756
+ # "gkm dev" and "gkm test" start the containers. The apps sit behind the
1757
+ # "apps" profile: run "gkm setup", then
1758
+ # docker compose -f docker-compose.constructs.yml --profile apps up --build
1759
+ ${(0, yaml.stringify)(file, { lineWidth: 0 })}`;
1760
+ }
1761
+ /** A container with no image, from config or from the defaults. */
1762
+ var UnknownContainer = class extends Error {
1763
+ /** The container that could not be resolved. */
1764
+ container;
1765
+ /** The containers that have a default, so the caller can see the set. */
1766
+ known = Object.keys(DEFAULT_IMAGES).sort();
1767
+ constructor(container) {
1768
+ super("No image is known for this container; pin one in config");
1769
+ this.name = "UnknownContainer";
1770
+ this.container = container;
1224
1771
  }
1225
- if (!resource.container) return void 0;
1226
- const port = ports[primaryPortKey(resource.container)];
1227
- if (port === void 0) return void 0;
1228
- switch (resource.kind) {
1229
- case "database":
1230
- case "database-schema":
1231
- case "database-reader": {
1232
- const database = rootDatabase(resource, plan);
1233
- if (resource.roles === false) {
1234
- const schema = schemaOf(resource, plan);
1235
- return schema ? `${postgres(port, database)}?search_path=${schema}` : postgres(port, database);
1772
+ };
1773
+ /** One container's definition, published on the port it was assigned. */
1774
+ function define(container, image, published) {
1775
+ switch (container) {
1776
+ case "postgres": return {
1777
+ image,
1778
+ restart: "unless-stopped",
1779
+ ports: published,
1780
+ environment: {
1781
+ POSTGRES_USER: LOCAL_USER,
1782
+ POSTGRES_PASSWORD: LOCAL_USER,
1783
+ POSTGRES_DB: LOCAL_USER
1784
+ },
1785
+ volumes: ["postgres-data:/var/lib/postgresql"],
1786
+ healthcheck: {
1787
+ test: ["CMD-SHELL", `pg_isready -U ${LOCAL_USER}`],
1788
+ interval: "5s",
1789
+ timeout: "3s",
1790
+ retries: 10,
1791
+ start_period: "10s"
1236
1792
  }
1237
- const role = resource.kind === "database-reader" ? (0, __geekmidas_db_pg_roles.readerRole)(parentRole(resource, plan)) : localRole(resource);
1238
- return postgres(port, database, {
1239
- user: role,
1240
- password: localRolePassword(project, plan, role)
1241
- });
1242
- }
1243
- case "email": return `smtp://${LOCAL_HOST}:${port}`;
1244
- case "objects": return `s3://${resource.name}?region=${LOCAL_REGION}&endpoint=http://${LOCAL_HOST}:${port}&forcePathStyle=true`;
1245
- case "file-server": {
1246
- const origin = plan.resources.find((r) => r.id === resource.of);
1247
- if (!origin) return void 0;
1248
- return plan.containers.includes("caddy") ? `https://${hostFor(resource, project)}:${port}` : `http://${LOCAL_HOST}:${port}/${origin.name}`;
1249
- }
1250
- case "cache":
1251
- if (resource.of) {
1252
- const parent = plan.resources.find((r) => r.id === resource.of);
1253
- const url = parent ? urlFor(parent, plan, ports, project, addresses) : void 0;
1254
- return url ? withTable(url, resource.table ?? (0, __geekmidas_manifest.cacheTable)(resource.id)) : void 0;
1793
+ };
1794
+ case "minio": return {
1795
+ image,
1796
+ restart: "unless-stopped",
1797
+ ports: published,
1798
+ environment: {
1799
+ MINIO_ROOT_USER: LOCAL_USER,
1800
+ MINIO_ROOT_PASSWORD: LOCAL_USER
1801
+ },
1802
+ command: "server --console-address \":9001\" /data",
1803
+ volumes: ["minio-data:/data"],
1804
+ healthcheck: {
1805
+ test: [
1806
+ "CMD",
1807
+ "mc",
1808
+ "ready",
1809
+ "local"
1810
+ ],
1811
+ interval: "10s",
1812
+ timeout: "5s",
1813
+ retries: 5,
1814
+ start_period: "10s"
1815
+ }
1816
+ };
1817
+ case "caddy": return {
1818
+ image,
1819
+ restart: "unless-stopped",
1820
+ ports: published,
1821
+ volumes: [
1822
+ "./.gkm/Caddyfile:/etc/caddy/Caddyfile:ro",
1823
+ "./.gkm/caddy-sites:/etc/caddy/sites:ro",
1824
+ "caddy-data:/data"
1825
+ ],
1826
+ extra_hosts: ["host.docker.internal:host-gateway"],
1827
+ healthcheck: {
1828
+ test: [
1829
+ "CMD",
1830
+ "caddy",
1831
+ "version"
1832
+ ],
1833
+ interval: "10s",
1834
+ timeout: "5s",
1835
+ retries: 5
1836
+ }
1837
+ };
1838
+ case "mailpit": return {
1839
+ image,
1840
+ restart: "unless-stopped",
1841
+ ports: published,
1842
+ environment: {
1843
+ MP_SMTP_AUTH_ACCEPT_ANY: "1",
1844
+ MP_SMTP_AUTH_ALLOW_INSECURE: "1"
1845
+ },
1846
+ healthcheck: {
1847
+ test: [
1848
+ "CMD",
1849
+ "wget",
1850
+ "-q",
1851
+ "--spider",
1852
+ "http://localhost:8025"
1853
+ ],
1854
+ interval: "10s",
1855
+ timeout: "5s",
1856
+ retries: 5
1857
+ }
1858
+ };
1859
+ case "redis": return {
1860
+ image,
1861
+ restart: "unless-stopped",
1862
+ ports: published,
1863
+ volumes: ["redis-data:/data"],
1864
+ healthcheck: {
1865
+ test: [
1866
+ "CMD",
1867
+ "redis-cli",
1868
+ "ping"
1869
+ ],
1870
+ interval: "5s",
1871
+ timeout: "3s",
1872
+ retries: 5
1873
+ }
1874
+ };
1875
+ case "redis-http": return {
1876
+ image,
1877
+ restart: "unless-stopped",
1878
+ ports: published,
1879
+ environment: {
1880
+ SRH_MODE: "env",
1881
+ SRH_TOKEN: LOCAL_TOKEN,
1882
+ SRH_CONNECTION_STRING: "redis://redis:6379"
1883
+ },
1884
+ depends_on: ["redis"],
1885
+ healthcheck: {
1886
+ test: [
1887
+ "CMD",
1888
+ "wget",
1889
+ "-q",
1890
+ "-O",
1891
+ "/dev/null",
1892
+ "http://127.0.0.1:80/"
1893
+ ],
1894
+ interval: "5s",
1895
+ timeout: "3s",
1896
+ retries: 10
1897
+ }
1898
+ };
1899
+ case "rabbitmq": return {
1900
+ image,
1901
+ restart: "unless-stopped",
1902
+ ports: published,
1903
+ environment: {
1904
+ RABBITMQ_DEFAULT_USER: LOCAL_USER,
1905
+ RABBITMQ_DEFAULT_PASS: LOCAL_USER
1906
+ },
1907
+ volumes: ["rabbitmq-data:/var/lib/rabbitmq"],
1908
+ healthcheck: {
1909
+ test: [
1910
+ "CMD",
1911
+ "rabbitmq-diagnostics",
1912
+ "-q",
1913
+ "ping"
1914
+ ],
1915
+ interval: "10s",
1916
+ timeout: "5s",
1917
+ retries: 5
1255
1918
  }
1256
- switch (plan.cache) {
1257
- case "elasticache": return `redis://${LOCAL_HOST}:${port}`;
1258
- default: return `http://:${LOCAL_TOKEN}@${LOCAL_HOST}:${port}`;
1919
+ };
1920
+ case "localstack": return {
1921
+ image,
1922
+ restart: "unless-stopped",
1923
+ ports: published,
1924
+ extra_hosts: ["host.docker.internal:host-gateway"],
1925
+ environment: {
1926
+ AWS_DEFAULT_REGION: EMULATOR_REGION,
1927
+ AWS_ACCESS_KEY_ID: EMULATOR_CREDENTIALS.accessKeyId,
1928
+ AWS_SECRET_ACCESS_KEY: EMULATOR_CREDENTIALS.secretAccessKey
1929
+ },
1930
+ volumes: ["localstack-data:/var/lib/localstack"],
1931
+ healthcheck: {
1932
+ test: [
1933
+ "CMD",
1934
+ "bash",
1935
+ "-c",
1936
+ "exec 3<>/dev/tcp/localhost/4566"
1937
+ ],
1938
+ interval: "10s",
1939
+ timeout: "5s",
1940
+ retries: 5,
1941
+ start_period: "10s"
1259
1942
  }
1260
- case "queue":
1261
- case "topic": return broker(plan, port);
1262
- default: return void 0;
1263
- }
1264
- }
1265
- /**
1266
- * The producer's connection string, composed from the backend the plan chose.
1267
- *
1268
- * The protocol is what picks the transport, so a producer never branches: the
1269
- * same `.publish()` reaches pg-boss here and SQS deployed because the string it
1270
- * was handed said so.
1271
- */
1272
- function broker(plan, port) {
1273
- switch (plan.events) {
1274
- case "pgboss": {
1275
- const database = plan.resources.find((r) => r.kind === "database");
1276
- if (!database) throw new PgBossNeedsDatabase([]);
1277
- return `pgboss://${LOCAL_USER}:${LOCAL_USER}@${LOCAL_HOST}:${port}/${database.name}?schema=${PGBOSS_SCHEMA}`;
1278
- }
1279
- case "rabbitmq": return `rabbitmq://${LOCAL_USER}:${LOCAL_USER}@${LOCAL_HOST}:${port}?exchange=${RABBITMQ_EXCHANGE}`;
1280
- case "sns": throw new UnprovisionedEventsBackend("sns");
1943
+ };
1944
+ default: throw new UnknownContainer(container);
1281
1945
  }
1282
1946
  }
1283
- /** A local Postgres URL, master credential and all. */
1284
- function postgres(port, database, credential = {
1285
- user: LOCAL_USER,
1286
- password: LOCAL_USER
1287
- }) {
1288
- return `postgres://${credential.user}:${credential.password}@${LOCAL_HOST}:${port}/${database}`;
1289
- }
1290
1947
  /**
1291
- * The role a handler connects as, for one database or tenant.
1948
+ * The published port mappings for a container.
1292
1949
  *
1293
- * The construct's id, lowercased and stage-scoped exactly as its database or
1294
- * schema is — so `Orders` in the `test` stage connects as `orders_test`, and two
1295
- * stages sharing one cluster cannot share a credential. Roles are cluster-scoped
1296
- * in Postgres, which is why the suffix is not optional here the way it is for a
1297
- * schema.
1950
+ * Every port is looked up by its own key rather than being derived as an offset
1951
+ * from the container's first, so MinIO's console cannot land on whatever was
1952
+ * allocated to the next container.
1298
1953
  */
1299
- function localRole(resource) {
1300
- return resource.name;
1954
+ function publish(container, ports, fakes) {
1955
+ return portsOf(container, fakes).map((port) => {
1956
+ const assigned = ports[port.key];
1957
+ if (assigned === void 0) throw new UnassignedPort(port.key);
1958
+ return `${assigned}:${port.inside}`;
1959
+ });
1301
1960
  }
1961
+ /** A planned port that allocation never assigned. */
1962
+ var UnassignedPort = class extends Error {
1963
+ /** The port key that went unassigned, e.g. `minio-console`. */
1964
+ key;
1965
+ constructor(key) {
1966
+ super("No port was assigned for this container port");
1967
+ this.name = "UnassignedPort";
1968
+ this.key = key;
1969
+ }
1970
+ };
1971
+ //#endregion
1972
+ //#region src/reconcile/docker.ts
1302
1973
  /**
1303
- * The password for a derived local role.
1974
+ * The real Docker, behind the small interface reconcile needs.
1304
1975
  *
1305
- * Derived rather than random, for the same reason the local secret is: a
1306
- * password that changed on every `gkm dev` would lock a developer out of the
1307
- * data they had a moment ago. Seeded by the project so two checkouts do not
1308
- * share one, and by the stage so `test` and `development` do not.
1976
+ * Shells out to `docker compose` rather than talking to the daemon socket: it is
1977
+ * what a developer runs by hand when something is wrong, so the two cannot
1978
+ * disagree, and it keeps Docker out of this package's dependencies.
1309
1979
  *
1310
- * It is a *local* credential by construction — the cluster is on loopback and
1311
- * the seed is a checkout path — and no deployed target uses this function.
1980
+ * Every call is scoped to the generated compose file. Nothing here can touch a
1981
+ * container this project did not generate.
1312
1982
  */
1313
- function localRolePassword(project, plan, role) {
1314
- return (0, node_crypto.createHash)("sha256").update(`${project}:${plan.stage}:role:${role}`).digest("base64url").slice(0, 32);
1315
- }
1983
+ const run = (0, node_util.promisify)(node_child_process.execFile);
1316
1984
  /**
1317
- * A cache's address: its database's URL, carrying the table it reads.
1985
+ * The generated file, then the project's own if it has one.
1318
1986
  *
1319
- * Appended rather than kept beside the URL as a second key, for the reason the
1320
- * design gives everywhere else — an address and what it opens are one fact, and
1321
- * two keys are one more thing to keep in step.
1987
+ * Merged in that order so the project's wins — an `image:` there pins a
1988
+ * container this file derived, and a service there is added beside them.
1322
1989
  */
1323
- function withTable(url, table) {
1324
- const parsed = new URL(url);
1325
- parsed.searchParams.set("table", table);
1326
- return parsed.toString();
1990
+ function composeFiles(composePath) {
1991
+ const project = (0, node_path.join)((0, node_path.dirname)(composePath), "docker-compose.yml");
1992
+ return [
1993
+ "-f",
1994
+ composePath,
1995
+ ...(0, node_fs.existsSync)(project) ? ["-f", project] : []
1996
+ ];
1327
1997
  }
1328
- /**
1329
- * The physical database a derived resource lives in.
1330
- *
1331
- * Walks `of` to the top rather than reading the immediate parent, because a
1332
- * reader's parent may itself be a schema tenant — two hops from the database
1333
- * that actually exists.
1334
- */
1335
- function rootDatabase(resource, plan) {
1336
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
1337
- let current = resource;
1338
- while (current.of) {
1339
- const parent = byId.get(current.of);
1340
- if (!parent) break;
1341
- current = parent;
1998
+ /** How long to wait for containers to pass their health checks. */
1999
+ const HEALTH_TIMEOUT_MS = 12e4;
2000
+ /** `docker compose up` exited unsuccessfully; its own output said why. */
2001
+ var ComposeUpFailed = class extends Error {
2002
+ services;
2003
+ code;
2004
+ constructor(services, code) {
2005
+ super(`docker compose could not start ${services.join(", ")} (exit ${code ?? "signal"}). Its output above names the container; \`docker compose logs <service>\` shows why it stopped.`);
2006
+ this.services = services;
2007
+ this.code = code;
2008
+ this.name = "ComposeUpFailed";
1342
2009
  }
1343
- return current.name;
2010
+ };
2011
+ /** Run compose with its output on this terminal rather than captured. */
2012
+ function shown(args, services) {
2013
+ return new Promise((resolve, reject) => {
2014
+ const child = (0, node_child_process.spawn)("docker", args, { stdio: [
2015
+ "ignore",
2016
+ "inherit",
2017
+ "inherit"
2018
+ ] });
2019
+ child.on("error", reject);
2020
+ child.on("close", (code) => code === 0 ? resolve() : reject(new ComposeUpFailed(services, code)));
2021
+ });
1344
2022
  }
1345
- /** The schema a derived resource puts on its search path, if it has one. */
1346
- function schemaOf(resource, plan) {
1347
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
1348
- let current = resource;
1349
- while (current) {
1350
- if (current.kind === "database-schema") return current.schema;
1351
- current = current.of ? byId.get(current.of) : void 0;
2023
+ const dockerCli = {
2024
+ async publishedPort(composePath, service, inside) {
2025
+ try {
2026
+ const { stdout } = await run("docker", [
2027
+ "compose",
2028
+ ...composeFiles(composePath),
2029
+ "port",
2030
+ service,
2031
+ String(inside)
2032
+ ]);
2033
+ const port = Number(stdout.trim().split(":").pop());
2034
+ return Number.isFinite(port) && port > 0 ? port : void 0;
2035
+ } catch {
2036
+ return;
2037
+ }
2038
+ },
2039
+ async up(composePath, services, options = {}) {
2040
+ const args = [
2041
+ "compose",
2042
+ ...composeFiles(composePath),
2043
+ "up",
2044
+ "-d",
2045
+ "--remove-orphans",
2046
+ "--wait",
2047
+ `--wait-timeout=${Math.floor(HEALTH_TIMEOUT_MS / 1e3)}`,
2048
+ ...services
2049
+ ];
2050
+ if (options.show) return shown(args, services);
2051
+ await run("docker", args);
2052
+ },
2053
+ async copyOut(composePath, service, from, to) {
2054
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(to), { recursive: true });
2055
+ await run("docker", [
2056
+ "compose",
2057
+ ...composeFiles(composePath),
2058
+ "cp",
2059
+ `${service}:${from}`,
2060
+ to
2061
+ ]);
2062
+ },
2063
+ async reload(composePath, service) {
2064
+ await run("docker", [
2065
+ "compose",
2066
+ ...composeFiles(composePath),
2067
+ "exec",
2068
+ "-T",
2069
+ service,
2070
+ "caddy",
2071
+ "reload",
2072
+ "--config",
2073
+ "/etc/caddy/Caddyfile"
2074
+ ]);
2075
+ },
2076
+ async healthy(composePath, services) {
2077
+ if (services.length === 0) return true;
2078
+ try {
2079
+ const { stdout } = await run("docker", [
2080
+ "compose",
2081
+ ...composeFiles(composePath),
2082
+ "ps",
2083
+ "--format",
2084
+ "json",
2085
+ ...services
2086
+ ]);
2087
+ const running = /* @__PURE__ */ new Set();
2088
+ for (const line of stdout.trim().split("\n").filter(Boolean)) {
2089
+ const entry = JSON.parse(line);
2090
+ if (entry.State === "running" && (entry.Health === void 0 || entry.Health === "" || entry.Health === "healthy") && entry.Service) running.add(entry.Service);
2091
+ }
2092
+ return services.every((service) => running.has(service));
2093
+ } catch {
2094
+ return false;
2095
+ }
1352
2096
  }
1353
- return void 0;
1354
- }
2097
+ };
2098
+ //#endregion
2099
+ //#region src/reconcile/lan.ts
1355
2100
  /**
1356
- * A backend whose local addresses cannot be derived yet.
1357
- *
1358
- * SNS and SQS are addressed by ARN, which means the topic and queue have to be
1359
- * created in LocalStack before a URL can name them. Until that provisioning
1360
- * lands, saying so is better than handing out a string that fails on first use.
2101
+ * This machine's address on the local network — what a phone running the app
2102
+ * reaches it on.
1361
2103
  */
1362
- var UnprovisionedEventsBackend = class extends Error {
1363
- constructor(backend) {
1364
- 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.`);
1365
- this.backend = backend;
1366
- this.name = "UnprovisionedEventsBackend";
1367
- }
1368
- };
1369
2104
  /**
1370
- * The value a secret resolves to locally.
2105
+ * The first private IPv4 address of an interface that is up and not loopback.
1371
2106
  *
1372
- * A hash of what identifies it, so it is stable, distinct per project, stage
1373
- * and construct, and never written to disk as a literal. Deployed this is the
1374
- * one kind whose value does *not* come from here — a secret manager generates
1375
- * it once and the target reads it back.
2107
+ * Private ranges only (`10/8`, `172.16/12`, `192.168/16`): a public address
2108
+ * would mean listening for a phone on the open internet, and a link-local one
2109
+ * (`169.254/16`) is what an interface has when it found no network at all.
2110
+ * Undefined when there is none — a laptop on no network still runs, its mobile
2111
+ * app reaching only a simulator.
1376
2112
  */
1377
- function localSecret(project, plan, resource) {
1378
- return (0, node_crypto.createHash)("sha256").update(`${project}:${plan.stage}:${resource.id}`).digest("base64url").slice(0, 43);
2113
+ function lanAddress(interfaces = (0, node_os.networkInterfaces)()) {
2114
+ for (const entries of Object.values(interfaces)) for (const entry of entries ?? []) {
2115
+ if (entry.family !== "IPv4" || entry.internal) continue;
2116
+ if (isPrivate(entry.address)) return entry.address;
2117
+ }
2118
+ }
2119
+ function isPrivate(address) {
2120
+ return /^10\./.test(address) || /^192\.168\./.test(address) || /^172\.(1[6-9]|2\d|3[01])\./.test(address);
1379
2121
  }
1380
-
1381
2122
  //#endregion
1382
2123
  //#region src/reconcile/ports.ts
1383
2124
  /**
2125
+ * Port allocation — why two projects can run at once.
2126
+ *
2127
+ * Publishing `5432:5432` means the second project on your machine cannot start.
2128
+ * Nothing solves that except giving each project its own ports, and what makes
2129
+ * it *possible* is the single-`<NAME>_URL` rule: an app reads `ORDERS_URL` and
2130
+ * never sees a host or a port, so reconcile is free to bind whatever is
2131
+ * available and compose the URL from what it bound. An app reading `DB_HOST` and
2132
+ * `DB_PORT` separately could not be moved this way.
2133
+ *
2134
+ * Assignments are **persisted, not recomputed**. Recomputing means adding a
2135
+ * construct renumbers its neighbours, and every running container, saved
2136
+ * connection string, and `psql` history goes stale at once.
2137
+ *
2138
+ * Pure, with the liveness probe injected — a collision with another project's
2139
+ * stack is a fact about the machine, and keeping it a parameter is what lets the
2140
+ * rules be asserted without binding a socket.
2141
+ */
2142
+ /**
1384
2143
  * The window ports are drawn from.
1385
2144
  *
1386
2145
  * Above the registered range so nothing here needs privileges, and below the
@@ -1438,6 +2197,27 @@ async function allocate(project, containers, existing = {}, probe = isPortFree)
1438
2197
  }
1439
2198
  return assignments;
1440
2199
  }
2200
+ /**
2201
+ * The ports to keep: what running containers are observed on, then what was
2202
+ * saved — minus any saved entry whose port something else already holds.
2203
+ *
2204
+ * Spreading one over the other let an observed port override its own key and
2205
+ * leave a *different* key still saved on the same number: two services on one
2206
+ * port, and whichever answered first won. Saved keys for containers the plan no
2207
+ * longer has — a backend switched and back — were the usual source. Observed
2208
+ * wins because it is what is actually bound; a dropped entry is simply
2209
+ * allocated again.
2210
+ */
2211
+ function keptPorts(saved = {}, observed = {}) {
2212
+ const kept = { ...observed };
2213
+ const taken = new Set(Object.values(observed));
2214
+ for (const [key, port] of Object.entries(saved).sort(([a], [b]) => a < b ? -1 : 1)) {
2215
+ if (key in kept || taken.has(port)) continue;
2216
+ kept[key] = port;
2217
+ taken.add(port);
2218
+ }
2219
+ return kept;
2220
+ }
1441
2221
  /** The window was exhausted. */
1442
2222
  var NoPortAvailable = class extends Error {
1443
2223
  /** Where the search started. */
@@ -1478,17 +2258,33 @@ async function nextFree(from, taken, probe) {
1478
2258
  * rather than as a connection failure ten minutes later.
1479
2259
  */
1480
2260
  function isPortFree(port) {
1481
- return new Promise((resolve$1) => {
2261
+ return new Promise((resolve) => {
1482
2262
  const server = (0, node_net.createServer)();
1483
- server.once("error", () => resolve$1(false));
1484
- server.once("listening", () => server.close(() => resolve$1(true)));
2263
+ server.once("error", () => resolve(false));
2264
+ server.once("listening", () => server.close(() => resolve(true)));
1485
2265
  server.listen(port, "0.0.0.0");
1486
2266
  });
1487
2267
  }
1488
-
1489
2268
  //#endregion
1490
2269
  //#region src/reconcile/provision.ts
1491
2270
  /**
2271
+ * Creating what the URLs name.
2272
+ *
2273
+ * Convergent and idempotent: every statement asks whether the thing exists
2274
+ * first, so reconciling repeatedly is free and a half-applied run recovers by
2275
+ * being run again. That property is what lets `gkm dev` do this on every start.
2276
+ *
2277
+ * The line the design draws is at data, not at side effects — this creates
2278
+ * databases, schemas, and buckets, and it never seeds, resets, or drops. A
2279
+ * developer who wants their data gone asks for it explicitly.
2280
+ *
2281
+ * Statement generation is separated from application for the reason the design
2282
+ * gives: the same DDL has to run in-process locally and from a provisioner in a
2283
+ * VPC, and one implementation is what stops "works locally, fails deployed".
2284
+ * When the role DDL lands in `@geekmidas/db` this delegates to it rather than
2285
+ * growing its own.
2286
+ */
2287
+ /**
1492
2288
  * The Postgres work a plan implies.
1493
2289
  *
1494
2290
  * Databases before the schemas inside them, which `provisionOrder` already
@@ -1539,9 +2335,9 @@ function postgresStatements(plan, project = "") {
1539
2335
  function cacheTableDdl(cache, home, plan) {
1540
2336
  const database = rootDatabase(home, plan);
1541
2337
  const schema = home.roles === false ? void 0 : home.schema;
1542
- const name = cache.table ?? (0, __geekmidas_manifest.cacheTable)(cache.id);
2338
+ const name = cache.table ?? (0, _geekmidas_manifest.cacheTable)(cache.id);
1543
2339
  const table = schema ? `${schema}.${name}` : name;
1544
- const created = (0, __geekmidas_cache_postgres.cacheTableStatements)({ table }).map((statement) => ({
2340
+ const created = (0, _geekmidas_cache_postgres.cacheTableStatements)({ table }).map((statement) => ({
1545
2341
  id: cache.id,
1546
2342
  describe: statement.describe,
1547
2343
  database,
@@ -1550,7 +2346,7 @@ function cacheTableDdl(cache, home, plan) {
1550
2346
  }));
1551
2347
  if (!schema) return created;
1552
2348
  const runtime = localRole(home);
1553
- const owner = (0, __geekmidas_db_pg_roles.ownerRole)(runtime);
2349
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
1554
2350
  const qualified = table.split(".").map((part) => quoteIdentifier(part)).join(".");
1555
2351
  return [
1556
2352
  ...created,
@@ -1578,13 +2374,14 @@ function cacheTableDdl(cache, home, plan) {
1578
2374
  function rolesFor(resource, schema, plan, project) {
1579
2375
  if (resource.roles === false) return [];
1580
2376
  const runtime = localRole(resource);
1581
- const owner = (0, __geekmidas_db_pg_roles.ownerRole)(runtime);
1582
- const reader = plan.resources.some((r) => r.kind === "database-reader" && r.of === resource.id) ? (0, __geekmidas_db_pg_roles.readerRole)(runtime) : void 0;
1583
- return (0, __geekmidas_db_pg_roles.roleStatements)({
2377
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
2378
+ const reader = plan.resources.some((r) => r.kind === "database-reader" && r.of === resource.id) ? (0, _geekmidas_db_pg_roles.readerRole)(runtime) : void 0;
2379
+ return (0, _geekmidas_db_pg_roles.roleStatements)({
1584
2380
  runtime,
1585
2381
  owner,
1586
2382
  ...reader ? { reader } : {},
1587
2383
  schema,
2384
+ ...resource.kind === "database" ? { database: rootDatabase(resource, plan) } : {},
1588
2385
  passwords: {
1589
2386
  runtime: localRolePassword(project, plan, runtime),
1590
2387
  owner: localRolePassword(project, plan, owner),
@@ -1630,8 +2427,7 @@ async function applyPostgres(client, statements) {
1630
2427
  });
1631
2428
  continue;
1632
2429
  }
1633
- const rows = await client.query(statement.database, statement.exists.sql, statement.exists.values);
1634
- if (rows.length > 0) {
2430
+ if ((await client.query(statement.database, statement.exists.sql, statement.exists.values)).length > 0) {
1635
2431
  applied.push({
1636
2432
  id: statement.id,
1637
2433
  describe: statement.describe,
@@ -1698,6 +2494,66 @@ function bucketPolicy(bucket, open) {
1698
2494
  });
1699
2495
  }
1700
2496
  /**
2497
+ * The topics and queues to create on the AWS emulator.
2498
+ *
2499
+ * Only on the `sns` backend: pg-boss makes its own tables on first connect and
2500
+ * a RabbitMQ exchange is declared by the client, but an SNS topic and an SQS
2501
+ * queue must exist before anything can publish to them.
2502
+ */
2503
+ function carrierNames(plan) {
2504
+ if (plan.events !== "sns") return {
2505
+ topics: [],
2506
+ queues: []
2507
+ };
2508
+ const named = (kind) => plan.resources.filter((r) => r.kind === kind).map((r) => r.name);
2509
+ return {
2510
+ topics: named("topic"),
2511
+ queues: named("queue")
2512
+ };
2513
+ }
2514
+ /** Create each topic and queue the plan names, skipping those that exist. */
2515
+ async function applyCarriers(client, carriers) {
2516
+ const applied = [];
2517
+ for (const name of carriers.topics) {
2518
+ const created = !await client.topicExists(name);
2519
+ if (created) await client.createTopic(name);
2520
+ applied.push({
2521
+ id: name,
2522
+ describe: `topic ${name}`,
2523
+ created
2524
+ });
2525
+ }
2526
+ for (const name of carriers.queues) {
2527
+ const created = !await client.queueExists(name);
2528
+ if (created) await client.createQueue(name);
2529
+ applied.push({
2530
+ id: name,
2531
+ describe: `queue ${name}`,
2532
+ created
2533
+ });
2534
+ }
2535
+ return applied;
2536
+ }
2537
+ /** The Postgres databases the plan creates — each is a `CREATE DATABASE`. */
2538
+ function postgresDatabaseNames(plan) {
2539
+ return plan.resources.filter((resource) => resource.kind === "database" && resource.provisions && resource.container === "postgres").map((resource) => resource.name);
2540
+ }
2541
+ /**
2542
+ * Whether every one of these databases exists. A database dropped behind the
2543
+ * recorded state's back — by another checkout's test teardown, against the
2544
+ * same container — makes the state a lie, and only asking Postgres finds out.
2545
+ * Unreachable counts as missing: applying again is what finds out why.
2546
+ */
2547
+ async function databasesExist(client, names) {
2548
+ if (names.length === 0) return true;
2549
+ try {
2550
+ const rows = await client.query(void 0, "SELECT datname FROM pg_catalog.pg_database WHERE datname = ANY($1)", [names]);
2551
+ return new Set(rows.map((row) => row.datname)).size === names.length;
2552
+ } catch {
2553
+ return false;
2554
+ }
2555
+ }
2556
+ /**
1701
2557
  * Apply each served bucket's open-path policy, skipping those already correct.
1702
2558
  *
1703
2559
  * Compared as parsed JSON rather than as text: the same policy re-serialised
@@ -1756,9 +2612,20 @@ async function applyBuckets(client, buckets) {
1756
2612
  }
1757
2613
  return applied;
1758
2614
  }
1759
-
1760
2615
  //#endregion
1761
2616
  //#region src/reconcile/state.ts
2617
+ /**
2618
+ * What reconcile records, and the hash that lets it do nothing.
2619
+ *
2620
+ * Reconciling on every `gkm dev` is only acceptable if the converged case is
2621
+ * free, so the desired plan is hashed: matching hash plus healthy containers
2622
+ * means there is nothing to do. Without that, the automatic reconcile the design
2623
+ * asks for would tax every start.
2624
+ *
2625
+ * Almost nothing needs recording — roles are queried, migrations have their own
2626
+ * table, containers are remembered by Docker. Only ports and this hash have no
2627
+ * other owner.
2628
+ */
1762
2629
  const STATE_DIR = ".gkm/reconcile";
1763
2630
  /**
1764
2631
  * The hash of everything a reconcile would act on.
@@ -1787,7 +2654,7 @@ async function loadState(root, stage) {
1787
2654
  const state = JSON.parse(raw);
1788
2655
  return state.stage === stage ? state : void 0;
1789
2656
  } catch {
1790
- return void 0;
2657
+ return;
1791
2658
  }
1792
2659
  }
1793
2660
  /** Record what was applied, so the next run can skip it. */
@@ -1796,14 +2663,46 @@ async function saveState(root, state) {
1796
2663
  await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
1797
2664
  await (0, node_fs_promises.writeFile)(path, `${JSON.stringify(state, null, 2)}\n`);
1798
2665
  }
2666
+ /**
2667
+ * Forget what was applied, so the next reconcile of this stage converges from
2668
+ * nothing — creating again whatever was dropped underneath the record.
2669
+ */
2670
+ async function forgetState(root, stage) {
2671
+ await (0, node_fs_promises.rm)(statePath(root, stage), { force: true });
2672
+ }
1799
2673
  function statePath(root, stage) {
1800
2674
  return (0, node_path.join)(root, STATE_DIR, `${stage}.json`);
1801
2675
  }
1802
-
1803
2676
  //#endregion
1804
2677
  //#region src/reconcile/index.ts
1805
- /** Where the generated compose file is written, relative to the project root. */
1806
- const COMPOSE_PATH = ".gkm/docker-compose.yml";
2678
+ /**
2679
+ * Reconcile — the one convergent function `gkm dev`, `gkm test`, and `gkm setup`
2680
+ * all call.
2681
+ *
2682
+ * Three phases, and only this one has side effects: declaring is pure (`gkm
2683
+ * build` and the dev watcher), running reads `<NAME>_URL` and provisions
2684
+ * nothing. Reconcile computes the desired state, compares, and applies the
2685
+ * difference — which is what makes "when does it run" answerable with
2686
+ * *whenever, repeatedly*.
2687
+ *
2688
+ * It is safe to run automatically because its blast radius is entirely local:
2689
+ * this project's containers, this project's `.gkm/`. Nothing it does can reach a
2690
+ * cloud. The line is drawn at data, not at side effects — it allocates ports,
2691
+ * writes compose, starts containers, and creates roles; it never seeds, resets,
2692
+ * or drops.
2693
+ *
2694
+ * Docker is injected rather than imported so the rules above can be asserted
2695
+ * without a daemon. The default implementation is the real one.
2696
+ */
2697
+ /**
2698
+ * Where the generated compose file is written, relative to the project root.
2699
+ *
2700
+ * At the root, beside the project's own `docker-compose.yml`, because the two
2701
+ * are one stack: this file is everything the constructs imply and is never
2702
+ * edited, that one is anything they cannot express — an image pin, an extra
2703
+ * service — and is merged over it, so it wins.
2704
+ */
2705
+ const COMPOSE_PATH = "docker-compose.constructs.yml";
1807
2706
  /**
1808
2707
  * The local edge's config, beside the compose file that mounts it.
1809
2708
  *
@@ -1839,32 +2738,37 @@ const CADDY_ROOT_IN_CONTAINER = "/data/caddy/pki/authorities/local/root.crt";
1839
2738
  * hash and one health check.
1840
2739
  */
1841
2740
  async function reconcile(options) {
1842
- const { root, project, manifest, stage, start = true, provision = true, docker = dockerCli, probe = isPortFree, sql = pgClient, buckets = bucketClient } = options;
1843
- const plan = planFor(manifest, stage, (0, __geekmidas_manifest.provisionOrder)(manifest), {
2741
+ const { root, project, manifest, stage, start = true, provision = true, docker = dockerCli, probe = isPortFree, sql = pgClient, buckets = bucketClient, carriers = carrierClient } = options;
2742
+ const plan = planFor(manifest, stage, (0, _geekmidas_manifest.provisionOrder)(manifest), {
2743
+ localStage: options.localStage,
1844
2744
  events: options.events,
1845
2745
  cache: options.cache,
1846
2746
  extraContainers: options.extraContainers,
2747
+ ...options.fakes ? { fakes: options.fakes } : {},
1847
2748
  ...options.edge === void 0 ? {} : { edge: options.edge }
1848
2749
  });
1849
2750
  const composePath = (0, node_path.join)(root, COMPOSE_PATH);
1850
- const observed = await observedPorts(docker, composePath, plan.containers);
1851
- const ports = await allocate(project, portKeys(plan.containers), {
1852
- ...options.saved,
1853
- ...observed
1854
- }, probe);
2751
+ const observed = await observedPorts(docker, composePath, plan.containers, plan.fakes);
2752
+ const ports = await allocate(project, portKeys(plan.containers, plan.fakes), keptPorts(options.saved, observed), probe);
1855
2753
  const compose = composeFor(plan, {
1856
2754
  project,
1857
2755
  ports,
1858
- ...options.images ? { images: options.images } : {}
2756
+ ...options.apps ? { apps: options.apps(plan.containers) } : {}
1859
2757
  });
1860
2758
  const caddyfile = toCaddyfile(sitesFor(plan, project, options.addresses));
1861
- const hash = planHash(plan, compose, { caddyfile });
1862
- const addresses = addressesFor(plan.containers, ports);
2759
+ const hash = planHash(plan, compose, {
2760
+ caddyfile,
2761
+ postgres: postgresStatements(plan, project).map((statement) => statement.create).join(";\n")
2762
+ });
2763
+ const services = serviceAddresses(plan.containers, ports, plan.fakes);
2764
+ const lan = plan.resources.some((r) => r.kind === "mobile-app") ? options.lanAddress === void 0 ? lanAddress() : options.lanAddress ?? void 0 : void 0;
1863
2765
  const env = envFor(plan, {
1864
2766
  ports,
1865
2767
  project,
1866
2768
  ...options.mailFrom ? { mailFrom: options.mailFrom } : {},
1867
- ...options.addresses ? { addresses: options.addresses } : {}
2769
+ ...options.addresses ? { addresses: options.addresses } : {},
2770
+ ...lan ? { lanAddress: lan } : {},
2771
+ ...options.metroPorts ? { metroPorts: options.metroPorts } : {}
1868
2772
  });
1869
2773
  if (plan.containers.includes("caddy")) env.NODE_EXTRA_CA_CERTS = (0, node_path.join)(root, LOCAL_CA_PATH);
1870
2774
  const result = {
@@ -1872,24 +2776,34 @@ async function reconcile(options) {
1872
2776
  plan,
1873
2777
  compose,
1874
2778
  ports,
1875
- addresses,
2779
+ services,
1876
2780
  env,
1877
2781
  provisioned: [],
2782
+ fakes: options.fakes ?? {},
1878
2783
  hash,
1879
2784
  changed: false
1880
2785
  };
1881
2786
  const recorded = await loadState(root, stage);
1882
- const converged = recorded?.hash === hash && (!start || await docker.healthy(composePath, plan.containers));
1883
- if (converged) return result;
2787
+ const postgresPort = ports[primaryPortKey("postgres")];
2788
+ if (recorded?.hash === hash && (0, node_fs.existsSync)(composePath) && (!start || await docker.healthy(composePath, plan.containers)) && (!start || !provision || postgresPort === void 0 || await databasesExist(sql(postgresPort), postgresDatabaseNames(plan)))) return result;
1884
2789
  await write(composePath, toYaml(compose));
1885
2790
  if (plan.containers.includes("caddy")) {
1886
2791
  await write((0, node_path.join)(root, CADDYFILE_PATH), caddyfileRoot());
1887
2792
  await write((0, node_path.join)(root, caddySitesPath(stage)), caddyfile);
2793
+ await pruneCaddySites(root, [
2794
+ stage,
2795
+ options.localStage,
2796
+ require_workspace.TEST_STAGE
2797
+ ]);
2798
+ }
2799
+ if (start && plan.containers.length > 0) {
2800
+ options.progress?.(`🐳 Starting ${plan.containers.join(", ")} — the first start pulls each image, which can take a few minutes`);
2801
+ await docker.up(composePath, plan.containers, options.progress ? { show: true } : {});
1888
2802
  }
1889
- if (start && plan.containers.length > 0) await docker.up(composePath, plan.containers);
1890
2803
  if (start && plan.containers.includes("caddy")) await docker.reload(composePath, "caddy").catch(() => {});
1891
2804
  if (start && plan.containers.includes("caddy")) await docker.copyOut(composePath, "caddy", CADDY_ROOT_IN_CONTAINER, (0, node_path.join)(root, LOCAL_CA_PATH)).catch(() => {});
1892
- const provisioned = start && provision ? await create(plan, ports, sql, buckets, project) : [];
2805
+ if (start && provision) options.progress?.("🗄️ Creating what the constructs declare — databases, roles, buckets, topics");
2806
+ const provisioned = start && provision ? await create(plan, ports, sql, buckets, carriers, project) : [];
1893
2807
  await saveState(root, {
1894
2808
  hash,
1895
2809
  stage
@@ -1898,783 +2812,368 @@ async function reconcile(options) {
1898
2812
  ...result,
1899
2813
  provisioned,
1900
2814
  changed: true
1901
- };
1902
- }
1903
- /**
1904
- * Create the databases, schemas, and buckets the plan names.
1905
- *
1906
- * Idempotent throughout, so this runs on every non-converged reconcile rather
1907
- * than being something to remember.
1908
- */
1909
- async function create(plan, ports, sql, buckets, project) {
1910
- const applied = [];
1911
- const postgresPort = ports[primaryPortKey("postgres")];
1912
- const statements = postgresStatements(plan, project);
1913
- if (postgresPort !== void 0 && statements.length > 0) applied.push(...await applyPostgres(sql(postgresPort), statements));
1914
- const minioPort = ports[primaryPortKey("minio")];
1915
- const names = bucketNames(plan);
1916
- const policies = bucketPolicies(plan);
1917
- if (minioPort !== void 0 && (names.length > 0 || policies.length > 0)) {
1918
- const client = buckets(minioPort);
1919
- if (names.length > 0) applied.push(...await applyBuckets(client, names));
1920
- if (policies.length > 0) applied.push(...await applyPolicies(client, policies));
1921
- }
1922
- return applied;
1923
- }
1924
- /**
1925
- * The host ports of containers already running.
1926
- *
1927
- * Keyed the same way allocation keys them, so the two merge without either
1928
- * knowing about the other.
1929
- */
1930
- async function observedPorts(docker, composePath, containers) {
1931
- const observed = {};
1932
- for (const container of containers) for (const port of portsOf(container)) {
1933
- const running = await docker.publishedPort(composePath, container, port.inside);
1934
- if (running !== void 0) observed[port.key] = running;
1935
- }
1936
- return observed;
1937
- }
1938
- /**
1939
- * Where each container can be reached on this machine.
1940
- *
1941
- * The primary port only — a container's console is for a human to open, not
1942
- * something an app connects to.
1943
- */
1944
- function addressesFor(containers, ports) {
1945
- const addresses = {};
1946
- for (const container of containers) {
1947
- const port = ports[primaryPortKey(container)];
1948
- if (port !== void 0) addresses[container] = `localhost:${port}`;
1949
- }
1950
- return addresses;
1951
- }
1952
- /** Write a file only when its content would change, so mtimes stay meaningful. */
1953
- async function write(path, content) {
1954
- try {
1955
- if (await (0, node_fs_promises.readFile)(path, "utf-8") === content) return;
1956
- } catch {}
1957
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
1958
- await (0, node_fs_promises.writeFile)(path, content);
1959
- }
1960
-
1961
- //#endregion
1962
- //#region src/reconcile/workspace.ts
1963
- /**
1964
- * Every constructs glob in the workspace, resolved against its app.
1965
- *
1966
- * Absolute because discovery globs from a single cwd while apps live in
1967
- * different directories.
1968
- */
1969
- function constructGlobs(workspace) {
1970
- return require_workspace.allConstructGlobs(workspace);
1971
- }
1972
- /** Whether any app has adopted the constructs glob. */
1973
- function usesConstructs(workspace) {
1974
- return constructGlobs(workspace).length > 0;
1975
- }
1976
- /**
1977
- * Image pins, by container. The config half of the derived/config split.
1978
- *
1979
- * Read from `services.images` rather than from the backend keys beside it.
1980
- * They used to share one key, which is how `cache: true` came to mean "start a
1981
- * Redis" — the last way a container could exist because config asked for one
1982
- * instead of because something declared it.
1983
- */
1984
- function imagePins(workspace) {
1985
- return { ...workspace.services.images };
1986
- }
1987
- /**
1988
- * The containers a workspace's declarations imply, without reconciling.
1989
- *
1990
- * The same derivation `reconcileWorkspace` makes, available to callers that
1991
- * need to know *what would run* without starting anything or writing ports —
1992
- * `gkm setup` deciding which credentials to generate, `gkm docker` writing a
1993
- * compose file. Those used to each read a boolean per service out of config,
1994
- * which is how a container could exist because config asked for one rather than
1995
- * because something declared it.
1996
- */
1997
- async function derivedContainers(workspace, stage, manifest) {
1998
- const found = manifest ?? await require_discover.discover({
1999
- patterns: constructGlobs(workspace),
2000
- cwd: workspace.root
2001
- });
2002
- return planFor(found, stage, (0, __geekmidas_manifest.provisionOrder)(found), {
2003
- events: workspace.services.events,
2004
- cache: cacheBackendOf(workspace.services.cache, providerOf(workspace))
2005
- }).containers;
2006
- }
2007
- /**
2008
- * Reconcile a workspace for one stage.
2009
- *
2010
- * Ports are loaded and saved around the call rather than inside it, so the loop
2011
- * stays a pure-ish function of its inputs and the store keeps its single owner.
2012
- */
2013
- async function reconcileWorkspace(workspace, options) {
2014
- const manifest = options.manifest ?? await require_discover.discover({
2015
- patterns: constructGlobs(workspace),
2016
- cwd: workspace.root
2017
- });
2018
- const result = await reconcile({
2019
- root: workspace.root,
2020
- project: workspace.name,
2021
- manifest,
2022
- stage: options.stage,
2023
- events: workspace.services.events,
2024
- cache: cacheBackendOf(workspace.services.cache, providerOf(workspace)),
2025
- images: imagePins(workspace),
2026
- saved: await loadPortState(workspace.root),
2027
- addresses: surfaceAddresses(workspace, manifest),
2028
- ...options.start === void 0 ? {} : { start: options.start }
2029
- });
2030
- await savePortState(workspace.root, { ...result.ports });
2031
- return result;
2032
- }
2033
- /**
2034
- * Where each declared surface and site answers locally.
2035
- *
2036
- * The addresses come from the ports the workspace already assigns; which
2037
- * construct sits at which one comes from the manifest. That split is the point:
2038
- * this used to answer "who may call whom" by listing every app the workspace
2039
- * runs, which is a different question that happened to give the same answer in
2040
- * a single-repo workspace and no answer at all deployed. Now it answers only
2041
- * "where does this construct answer", and the graph answers the rest.
2042
- *
2043
- * A site is matched to its app by `path`, because that is the one thing a site
2044
- * declaration and a workspace app both name. Surfaces are matched to the
2045
- * backend app: every `rest-api` in a process answers on that process's port, so
2046
- * an app serving both its own API and an auth server publishes one address
2047
- * twice — which is exactly what it does at runtime.
2048
- */
2049
- function surfaceAddresses(workspace, manifest) {
2050
- const addresses = {};
2051
- for (const [id, declaration] of Object.entries(manifest)) {
2052
- if (declaration.kind !== "rest-api" && declaration.kind !== "site") continue;
2053
- const host = declaration.kind === "site" ? require_config.appKey(id) : appKeyOfHost(manifest, id);
2054
- const app = host ? workspace.apps[host] : void 0;
2055
- if (app?.port) addresses[id] = localAddress(app.port);
2056
- }
2057
- return addresses;
2058
- }
2059
- /** The app key serving a surface, following a mount to its host. */
2060
- function appKeyOfHost(manifest, id) {
2061
- const host = require_config.hostOf(manifest, id);
2062
- return host ? require_config.appKey(host) : void 0;
2063
- }
2064
- /** Where a local process answers, given the port the workspace gave it. */
2065
- function localAddress(port) {
2066
- return `http://localhost:${port}`;
2067
- }
2068
-
2069
- //#endregion
2070
- //#region src/credentials/index.ts
2071
- const logger = console;
2072
- /**
2073
- * Load environment files
2074
- * @internal Exported for testing
2075
- */
2076
- function loadEnvFiles(envConfig, cwd = process.cwd()) {
2077
- const loaded = [];
2078
- const missing = [];
2079
- const envFiles = envConfig ? Array.isArray(envConfig) ? envConfig : [envConfig] : [".env"];
2080
- for (const envFile of envFiles) {
2081
- const envPath = (0, node_path.resolve)(cwd, envFile);
2082
- if ((0, node_fs.existsSync)(envPath)) {
2083
- (0, dotenv.config)({
2084
- path: envPath,
2085
- override: true,
2086
- quiet: true
2087
- });
2088
- loaded.push(envFile);
2089
- } else if (envConfig) missing.push(envFile);
2090
- }
2091
- return {
2092
- loaded,
2093
- missing
2094
- };
2095
- }
2096
- /**
2097
- * Check if a port is available
2098
- * @internal Exported for testing
2099
- */
2100
- async function isPortAvailable(port) {
2101
- return new Promise((resolve$1) => {
2102
- const server = (0, node_net.createServer)();
2103
- server.once("error", (err) => {
2104
- if (err.code === "EADDRINUSE") resolve$1(false);
2105
- else resolve$1(false);
2106
- });
2107
- server.once("listening", () => {
2108
- server.close();
2109
- resolve$1(true);
2110
- });
2111
- server.listen(port);
2112
- });
2113
- }
2114
- /**
2115
- * Find an available port starting from the preferred port
2116
- * @internal Exported for testing
2117
- */
2118
- async function findAvailablePort(preferredPort, maxAttempts = 10) {
2119
- for (let i = 0; i < maxAttempts; i++) {
2120
- const port = preferredPort + i;
2121
- if (await isPortAvailable(port)) return port;
2122
- logger.log(`⚠️ Port ${port} is in use, trying ${port + 1}...`);
2123
- }
2124
- throw new Error(`Could not find an available port after trying ${maxAttempts} ports starting from ${preferredPort}`);
2125
- }
2126
- const PORT_STATE_PATH = ".gkm/ports.json";
2127
- /**
2128
- * Parse docker-compose.yml and extract all port mappings that use env var interpolation.
2129
- * Entries like `'${POSTGRES_HOST_PORT:-5432}:5432'` are captured.
2130
- * Fixed port mappings like `'5050:80'` are skipped.
2131
- * @internal Exported for testing
2132
- */
2133
- function parseComposePortMappings(composePath) {
2134
- if (!(0, node_fs.existsSync)(composePath)) return [];
2135
- const content = (0, node_fs.readFileSync)(composePath, "utf-8");
2136
- const compose = (0, yaml.parse)(content);
2137
- if (!compose?.services) return [];
2138
- const results = [];
2139
- for (const [serviceName, serviceConfig] of Object.entries(compose.services)) for (const portMapping of serviceConfig?.ports ?? []) {
2140
- const match = String(portMapping).match(/\$\{(\w+):-(\d+)\}:(\d+)/);
2141
- if (match?.[1] && match[2] && match[3]) results.push({
2142
- service: serviceName,
2143
- envVar: match[1],
2144
- defaultPort: Number(match[2]),
2145
- containerPort: Number(match[3])
2146
- });
2147
- }
2148
- return results;
2149
- }
2150
- /**
2151
- * Load saved port state from .gkm/ports.json.
2152
- * @internal Exported for testing
2153
- */
2154
- async function loadPortState(workspaceRoot) {
2155
- try {
2156
- const raw = await (0, node_fs_promises.readFile)((0, node_path.join)(workspaceRoot, PORT_STATE_PATH), "utf-8");
2157
- return JSON.parse(raw);
2158
- } catch {
2159
- return {};
2160
- }
2161
- }
2162
- /**
2163
- * Save port state to .gkm/ports.json.
2164
- * @internal Exported for testing
2165
- */
2166
- async function savePortState(workspaceRoot, ports) {
2167
- const dir = (0, node_path.join)(workspaceRoot, ".gkm");
2168
- await (0, node_fs_promises.mkdir)(dir, { recursive: true });
2169
- await (0, node_fs_promises.writeFile)((0, node_path.join)(workspaceRoot, PORT_STATE_PATH), `${JSON.stringify(ports, null, 2)}\n`);
2170
- }
2171
- /**
2172
- * Check if a project's own Docker container is running and return its host port.
2173
- * Uses `docker compose port` scoped to the project's compose file.
2174
- * @internal Exported for testing
2175
- */
2176
- function getContainerHostPort(workspaceRoot, service, containerPort) {
2177
- try {
2178
- const result = (0, node_child_process.execSync)(`docker compose port ${service} ${containerPort}`, {
2179
- cwd: workspaceRoot,
2180
- stdio: "pipe"
2181
- }).toString().trim();
2182
- const match = result.match(/:(\d+)$/);
2183
- return match ? Number(match[1]) : null;
2184
- } catch {
2185
- return null;
2186
- }
2187
- }
2188
- /**
2189
- * Resolve host ports for Docker services by parsing docker-compose.yml.
2190
- * Priority: running container → saved state → find available port.
2191
- * Persists resolved ports to .gkm/ports.json.
2192
- * @internal Exported for testing
2193
- */
2194
- async function resolveServicePorts(workspaceRoot) {
2195
- const composePath = (0, node_path.join)(workspaceRoot, "docker-compose.yml");
2196
- const mappings = parseComposePortMappings(composePath);
2197
- if (mappings.length === 0) return {
2198
- dockerEnv: {},
2199
- ports: {},
2200
- mappings: []
2201
- };
2202
- const savedState = await loadPortState(workspaceRoot);
2203
- const dockerEnv = {};
2204
- const ports = {};
2205
- const assignedPorts = /* @__PURE__ */ new Set();
2206
- logger.log("\n🔌 Resolving service ports...");
2207
- for (const mapping of mappings) {
2208
- const containerPort = getContainerHostPort(workspaceRoot, mapping.service, mapping.containerPort);
2209
- if (containerPort !== null) {
2210
- ports[mapping.envVar] = containerPort;
2211
- dockerEnv[mapping.envVar] = String(containerPort);
2212
- assignedPorts.add(containerPort);
2213
- logger.log(` 🔄 ${mapping.service}:${mapping.containerPort}: reusing existing container on port ${containerPort}`);
2214
- continue;
2215
- }
2216
- const savedPort = savedState[mapping.envVar];
2217
- if (savedPort && !assignedPorts.has(savedPort) && await isPortAvailable(savedPort)) {
2218
- ports[mapping.envVar] = savedPort;
2219
- dockerEnv[mapping.envVar] = String(savedPort);
2220
- assignedPorts.add(savedPort);
2221
- logger.log(` 💾 ${mapping.service}:${mapping.containerPort}: using saved port ${savedPort}`);
2222
- continue;
2223
- }
2224
- let resolvedPort = await findAvailablePort(mapping.defaultPort);
2225
- while (assignedPorts.has(resolvedPort)) resolvedPort = await findAvailablePort(resolvedPort + 1);
2226
- ports[mapping.envVar] = resolvedPort;
2227
- dockerEnv[mapping.envVar] = String(resolvedPort);
2228
- assignedPorts.add(resolvedPort);
2229
- if (resolvedPort !== mapping.defaultPort) logger.log(` ⚡ ${mapping.service}:${mapping.containerPort}: port ${mapping.defaultPort} occupied, using port ${resolvedPort}`);
2230
- else logger.log(` ✅ ${mapping.service}:${mapping.containerPort}: using default port ${resolvedPort}`);
2231
- }
2232
- await savePortState(workspaceRoot, ports);
2233
- return {
2234
- dockerEnv,
2235
- ports,
2236
- mappings
2237
- };
2238
- }
2239
- /**
2240
- * Replace a port in a URL string.
2241
- * Handles both `hostname:port` and `localhost:port` patterns.
2242
- * @internal Exported for testing
2243
- */
2244
- function replacePortInUrl(url, oldPort, newPort) {
2245
- if (oldPort === newPort) return url;
2246
- let result = url.replace(new RegExp(`:${oldPort}(?=[/?#]|$)`, "g"), `:${newPort}`);
2247
- result = result.replace(new RegExp(`%3A${oldPort}(?=[%/?#&]|$)`, "gi"), `%3A${newPort}`);
2248
- return result;
2815
+ };
2249
2816
  }
2250
2817
  /**
2251
- * Rewrite connection URLs and port vars in secrets with resolved ports.
2252
- * Uses the parsed compose mappings to determine which default ports to replace.
2253
- * Pure transform — does not modify secrets on disk.
2254
- * @internal Exported for testing
2818
+ * Create the databases, schemas, buckets, topics and queues the plan names.
2819
+ *
2820
+ * Idempotent throughout, so this runs on every non-converged reconcile rather
2821
+ * than being something to remember.
2255
2822
  */
2256
- function rewriteUrlsWithPorts(secrets, resolvedPorts) {
2257
- const { ports, mappings } = resolvedPorts;
2258
- const result = { ...secrets };
2259
- const portReplacements = [];
2260
- const serviceNames = /* @__PURE__ */ new Set();
2261
- for (const mapping of mappings) {
2262
- serviceNames.add(mapping.service);
2263
- const resolved = ports[mapping.envVar];
2264
- if (resolved !== void 0) portReplacements.push({
2265
- defaultPort: mapping.defaultPort,
2266
- resolvedPort: resolved
2267
- });
2268
- }
2269
- for (const [key, value] of Object.entries(result)) {
2270
- if (!key.endsWith("_HOST")) continue;
2271
- if (serviceNames.has(value)) result[key] = "localhost";
2272
- }
2273
- for (const [key, value] of Object.entries(result)) {
2274
- if (!key.endsWith("_PORT")) continue;
2275
- for (const { defaultPort, resolvedPort } of portReplacements) if (value === String(defaultPort)) result[key] = String(resolvedPort);
2276
- }
2277
- for (const [key, value] of Object.entries(result)) {
2278
- if (!key.endsWith("_URL") && !key.endsWith("_ENDPOINT") && !key.endsWith("_CONNECTION_STRING") && key !== "DATABASE_URL") continue;
2279
- let rewritten = value;
2280
- for (const name of serviceNames) rewritten = rewritten.replace(new RegExp(`@${name}:`, "g"), "@localhost:");
2281
- for (const { defaultPort, resolvedPort } of portReplacements) rewritten = replacePortInUrl(rewritten, defaultPort, resolvedPort);
2282
- result[key] = rewritten;
2823
+ async function create(plan, ports, sql, buckets, emulatorCarriers, project) {
2824
+ const applied = [];
2825
+ const postgresPort = ports[primaryPortKey("postgres")];
2826
+ const statements = postgresStatements(plan, project);
2827
+ if (postgresPort !== void 0 && statements.length > 0) applied.push(...await applyPostgres(sql(postgresPort), statements));
2828
+ const minioPort = ports[primaryPortKey("minio")];
2829
+ const names = bucketNames(plan);
2830
+ const policies = bucketPolicies(plan);
2831
+ if (minioPort !== void 0 && (names.length > 0 || policies.length > 0)) {
2832
+ const client = buckets(minioPort);
2833
+ if (names.length > 0) applied.push(...await applyBuckets(client, names));
2834
+ if (policies.length > 0) applied.push(...await applyPolicies(client, policies));
2283
2835
  }
2284
- return result;
2836
+ const emulatorPort = ports[primaryPortKey("localstack")];
2837
+ const carriers = carrierNames(plan);
2838
+ if (emulatorPort !== void 0 && carriers.topics.length + carriers.queues.length > 0) applied.push(...await applyCarriers(emulatorCarriers(emulatorPort), carriers));
2839
+ return applied;
2285
2840
  }
2286
2841
  /**
2287
- * Build the environment variables to pass to `docker compose up`.
2288
- * Merges process.env, secrets, and port mappings so that Docker Compose
2289
- * can interpolate variables like ${POSTGRES_USER} correctly.
2290
- * @internal Exported for testing
2842
+ * The host ports of containers already running.
2843
+ *
2844
+ * Keyed the same way allocation keys them, so the two merge without either
2845
+ * knowing about the other.
2291
2846
  */
2292
- function buildDockerComposeEnv(secretsEnv, portEnv) {
2293
- return {
2294
- ...process.env,
2295
- ...secretsEnv,
2296
- ...portEnv
2297
- };
2847
+ async function observedPorts(docker, composePath, containers, fakes) {
2848
+ const observed = {};
2849
+ for (const container of containers) for (const port of portsOf(container, fakes)) {
2850
+ const running = await docker.publishedPort(composePath, container, port.inside);
2851
+ if (running !== void 0) observed[port.key] = running;
2852
+ }
2853
+ return observed;
2298
2854
  }
2855
+ /** Write a file only when its content would change, so mtimes stay meaningful. */
2299
2856
  /**
2300
- * Parse all service names from a docker-compose.yml file.
2301
- * @internal Exported for testing
2857
+ * Remove the routes of stages this project no longer reconciles.
2858
+ *
2859
+ * Only the local stage and `test` are ever written, so any other file is left
2860
+ * over from a stage that was renamed — `development` becoming `dev`. Caddy
2861
+ * imports every file, and the leftover declares the same hosts as its
2862
+ * replacement: it refuses the whole config as ambiguous, and every URL behind
2863
+ * the edge goes with it.
2302
2864
  */
2303
- function parseComposeServiceNames(composePath) {
2304
- if (!(0, node_fs.existsSync)(composePath)) return [];
2305
- const content = (0, node_fs.readFileSync)(composePath, "utf-8");
2306
- const compose = (0, yaml.parse)(content);
2307
- return Object.keys(compose?.services ?? {});
2865
+ async function pruneCaddySites(root, stages) {
2866
+ const dir = (0, node_path.dirname)((0, node_path.join)(root, caddySitesPath(require_workspace.TEST_STAGE)));
2867
+ const keep = new Set(stages.map((stage) => stage && `${stage}.caddy`));
2868
+ for (const file of await (0, node_fs_promises.readdir)(dir)) if (file.endsWith(".caddy") && !keep.has(file)) await (0, node_fs_promises.rm)((0, node_path.join)(dir, file));
2308
2869
  }
2309
- /**
2310
- * Start docker-compose services for a single-app project (no workspace config).
2311
- * Starts all services defined in docker-compose.yml.
2312
- */
2313
- async function startComposeServices(cwd, portEnv, secretsEnv) {
2314
- const composeFile = (0, node_path.join)(cwd, "docker-compose.yml");
2315
- if (!(0, node_fs.existsSync)(composeFile)) return;
2316
- const servicesToStart = parseComposeServiceNames(composeFile);
2317
- if (servicesToStart.length === 0) return;
2318
- logger.log(`🐳 Starting services: ${servicesToStart.join(", ")}`);
2870
+ async function write(path, content) {
2319
2871
  try {
2320
- (0, node_child_process.execSync)(`docker compose up -d ${servicesToStart.join(" ")}`, {
2321
- cwd,
2322
- stdio: "inherit",
2323
- env: buildDockerComposeEnv(secretsEnv, portEnv)
2324
- });
2325
- logger.log("✅ Services started");
2326
- } catch (error) {
2327
- logger.error("❌ Failed to start services:", error.message);
2328
- throw error;
2329
- }
2872
+ if (await (0, node_fs_promises.readFile)(path, "utf-8") === content) return;
2873
+ } catch {}
2874
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
2875
+ await (0, node_fs_promises.writeFile)(path, content);
2330
2876
  }
2877
+ //#endregion
2878
+ //#region src/reconcile/workspace.ts
2331
2879
  /**
2332
- * Start docker-compose services for a workspace.
2333
- * Discovers all services from docker-compose.yml and starts everything
2334
- * except app services (which are managed by turbo).
2335
- * @internal Exported for testing
2880
+ * Workspace config → reconcile.
2881
+ *
2882
+ * Nothing here is read from a `services:` block — there is none. Which
2883
+ * containers exist comes from the manifest; which backend a cache or a broker
2884
+ * resolves to comes from the deploy target; and an image pin is the project's
2885
+ * own `docker-compose.yml`, merged over the generated file.
2886
+ *
2887
+ * Shared by `gkm setup`, `gkm dev`, and `gkm test` so all three converge on the
2888
+ * same state, differing only in the stage they pass.
2889
+ */
2890
+ var workspace_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
2891
+ FAKE_ENV: () => FAKE_ENV,
2892
+ backendsOf: () => backendsOf,
2893
+ constructGlobs: () => constructGlobs,
2894
+ derivedContainers: () => derivedContainers,
2895
+ fakesApply: () => fakesApply,
2896
+ metroPorts: () => metroPorts,
2897
+ reconcileWorkspace: () => reconcileWorkspace,
2898
+ surfaceAddresses: () => surfaceAddresses
2899
+ });
2900
+ /**
2901
+ * Every constructs glob in the workspace, resolved against its app.
2902
+ *
2903
+ * Absolute because discovery globs from a single cwd while apps live in
2904
+ * different directories.
2336
2905
  */
2337
- async function startWorkspaceServices(workspace, portEnv, secretsEnv) {
2338
- const composeFile = (0, node_path.join)(workspace.root, "docker-compose.yml");
2339
- if (!(0, node_fs.existsSync)(composeFile)) return;
2340
- const allServices = parseComposeServiceNames(composeFile);
2341
- const appNames = new Set(Object.keys(workspace.apps));
2342
- const servicesToStart = allServices.filter((name) => !appNames.has(name));
2343
- if (servicesToStart.length === 0) return;
2344
- logger.log(`🐳 Starting services: ${servicesToStart.join(", ")}`);
2345
- try {
2346
- (0, node_child_process.execSync)(`docker compose up -d ${servicesToStart.join(" ")}`, {
2347
- cwd: workspace.root,
2348
- stdio: "inherit",
2349
- env: buildDockerComposeEnv(secretsEnv, portEnv)
2350
- });
2351
- logger.log("✅ Services started");
2352
- } catch (error) {
2353
- logger.error("❌ Failed to start services:", error.message);
2354
- throw error;
2355
- }
2906
+ function constructGlobs(workspace) {
2907
+ return require_workspace.allConstructGlobs(workspace);
2908
+ }
2909
+ /** The backends a workspace's target implies, as the plan takes them. */
2910
+ function backendsOf(workspace) {
2911
+ const on = require_backends.providerOf(workspace);
2912
+ return {
2913
+ events: require_backends.eventsBackendFor(on),
2914
+ cache: require_backends.cacheBackendFor(on)
2915
+ };
2356
2916
  }
2357
2917
  /**
2358
- * Load and flatten secrets for an app from encrypted storage.
2359
- * For workspace app: maps {APP}_DATABASE_URL → DATABASE_URL.
2360
- * @internal Exported for testing
2918
+ * The containers a workspace's declarations imply, without reconciling.
2919
+ *
2920
+ * The same derivation `reconcileWorkspace` makes, available to callers that
2921
+ * need to know *what would run* without starting anything or writing ports —
2922
+ * `gkm setup` deciding which credentials to generate, `gkm docker` writing a
2923
+ * compose file. Those used to each read a boolean per service out of config,
2924
+ * which is how a container could exist because config asked for one rather than
2925
+ * because something declared it.
2361
2926
  */
2362
- async function loadSecretsForApp(secretsRoot, appName, stages = ["dev", "development"]) {
2363
- let secrets = {};
2364
- for (const stage of stages) if (require_storage.secretsExist(stage, secretsRoot)) {
2365
- const stageSecrets = await require_storage.readStageSecrets(stage, secretsRoot);
2366
- if (stageSecrets) {
2367
- logger.log(`🔐 Loading secrets from stage: ${stage}`);
2368
- secrets = require_storage.toEmbeddableSecrets(stageSecrets);
2369
- break;
2370
- }
2371
- }
2372
- if (Object.keys(secrets).length === 0) return {};
2373
- if (!appName) return secrets;
2374
- const prefix = appName.toUpperCase();
2375
- const mapped = { ...secrets };
2376
- const appDbUrl = secrets[`${prefix}_DATABASE_URL`];
2377
- if (appDbUrl) mapped.DATABASE_URL = appDbUrl;
2378
- return mapped;
2927
+ async function derivedContainers(workspace, stage, manifest) {
2928
+ const found = manifest ?? await require_discover.discover({
2929
+ patterns: constructGlobs(workspace),
2930
+ cwd: workspace.root
2931
+ });
2932
+ return planFor(found, stage, (0, _geekmidas_manifest.provisionOrder)(found), {
2933
+ localStage: workspace.stages.local,
2934
+ ...backendsOf(workspace)
2935
+ }).containers;
2379
2936
  }
2380
2937
  /**
2381
- * Walk up the directory tree to find the root containing .gkm/secrets/.
2382
- * @internal Exported for testing
2938
+ * Set by `gkm dev --fake` for the apps it starts. Each app's own `gkm dev`
2939
+ * reconciles too, and must answer the way the workspace did.
2383
2940
  */
2384
- function findSecretsRoot(startDir) {
2385
- let dir = startDir;
2386
- while (dir !== "/") {
2387
- if ((0, node_fs.existsSync)((0, node_path.join)(dir, ".gkm", "secrets"))) return dir;
2388
- const parent = (0, node_path.dirname)(dir);
2389
- if (parent === dir) break;
2390
- dir = parent;
2391
- }
2392
- return startDir;
2393
- }
2941
+ const FAKE_ENV = "GKM_FAKE";
2394
2942
  /**
2395
- * Generate the credentials injection code snippet.
2396
- * This is the common logic used by both entry wrapper and exec preload.
2397
- * @internal
2943
+ * Whether external APIs are faked: always for `gkm test`, and for `gkm dev`
2944
+ * only when asked — by `--fake`, or by the workspace that started this app
2945
+ * with it. Never for anything acting on a deployed stage.
2398
2946
  */
2399
- function generateCredentialsInjection(secretsJsonPath) {
2400
- return `import { existsSync, readFileSync } from 'node:fs';
2401
-
2402
- // Inject dev secrets via globalThis and process.env
2403
- // Using globalThis.__gkm_credentials__ avoids CJS/ESM interop issues where
2404
- // Object.assign on the Credentials export only mutates one module copy.
2405
- const secretsPath = '${secretsJsonPath}';
2406
- if (existsSync(secretsPath)) {
2407
- const secrets = JSON.parse(readFileSync(secretsPath, 'utf-8'));
2408
- globalThis.__gkm_credentials__ = secrets;
2409
- Object.assign(process.env, secrets);
2410
- }
2411
- `;
2947
+ function fakesApply(stage, fake, env = process.env) {
2948
+ return fake === true || stage === "test" || env["GKM_FAKE"] === "1";
2412
2949
  }
2413
2950
  /**
2414
- * Create a preload script that injects secrets into Credentials.
2415
- * Used by `gkm exec` to inject secrets before running any command.
2416
- * @internal Exported for testing
2951
+ * Reconcile a workspace for one stage.
2952
+ *
2953
+ * Ports are loaded and saved around the call rather than inside it, so the loop
2954
+ * stays a pure-ish function of its inputs and the store keeps its single owner.
2417
2955
  */
2418
- async function createCredentialsPreload(preloadPath, secretsJsonPath) {
2419
- const content = `/**
2420
- * Credentials preload generated by 'gkm exec'
2421
- * This file is loaded via NODE_OPTIONS="--import <path>"
2422
- */
2423
- ${generateCredentialsInjection(secretsJsonPath)}`;
2424
- await (0, node_fs_promises.writeFile)(preloadPath, content);
2956
+ async function reconcileWorkspace(workspace, options) {
2957
+ const runnables = {};
2958
+ const discovered = await require_discover.discover({
2959
+ patterns: constructGlobs(workspace),
2960
+ cwd: workspace.root,
2961
+ runnables
2962
+ });
2963
+ const manifest = options.manifest ?? discovered;
2964
+ const fakes = fakesApply(options.stage, options.fake) ? await require_ready.readFakes(workspace.root, manifest) : {};
2965
+ const result = await reconcile({
2966
+ root: workspace.root,
2967
+ project: workspace.name,
2968
+ manifest,
2969
+ stage: options.stage,
2970
+ localStage: workspace.stages.local,
2971
+ ...backendsOf(workspace),
2972
+ saved: await loadPortState(workspace.root),
2973
+ addresses: surfaceAddresses(workspace, manifest),
2974
+ metroPorts: metroPorts(workspace, manifest),
2975
+ fakes,
2976
+ apps: (containers) => appServices(workspace, manifest, containers, runnables, fakes),
2977
+ ...options.start === void 0 ? {} : { start: options.start },
2978
+ ...options.progress ? { progress: options.progress } : {}
2979
+ });
2980
+ await savePortState(workspace.root, { ...result.ports });
2981
+ return result;
2425
2982
  }
2426
2983
  /**
2427
- * Create a wrapper script that injects secrets before importing the entry file.
2428
- * @internal Exported for testing
2984
+ * Where each mobile app's Metro runs: its app's port, which `gkm exec` hands
2985
+ * Expo as `RCT_METRO_PORT`. Kept apart from the surfaces' addresses — a phone
2986
+ * reaches Metro by `exp://`, not through the edge.
2429
2987
  */
2430
- async function createEntryWrapper(wrapperPath, entryPath, secretsJsonPath) {
2431
- const credentialsInjection = secretsJsonPath ? `${generateCredentialsInjection(secretsJsonPath)}
2432
- ` : "";
2433
- const content = `#!/usr/bin/env node
2434
- /**
2435
- * Entry wrapper generated by 'gkm dev --entry'
2436
- */
2437
- ${credentialsInjection}// Import and run the user's entry file (dynamic import ensures secrets load first)
2438
- await import('${entryPath}');
2439
- `;
2440
- await (0, node_fs_promises.writeFile)(wrapperPath, content);
2988
+ function metroPorts(workspace, manifest) {
2989
+ const ports = {};
2990
+ for (const [id, declaration] of Object.entries(manifest)) {
2991
+ if (declaration.kind !== "mobile-app") continue;
2992
+ const port = workspace.apps[require_config.appKey(id)]?.port;
2993
+ if (port) ports[id] = port;
2994
+ }
2995
+ return ports;
2441
2996
  }
2442
2997
  /**
2443
- * Prepare credentials for dev/exec/test modes.
2444
- * Loads workspace config, secrets, resolves Docker ports, rewrites URLs,
2445
- * injects PORT, dependency URLs, and writes credentials JSON.
2998
+ * Where each declared surface and site answers locally.
2446
2999
  *
2447
- * @param options.resolveDockerPorts - How to resolve Docker ports:
2448
- * - `'full'` (default): probe running containers, saved state, then find available ports. Used by dev/test.
2449
- * - `'readonly'`: check running containers and saved state only, never probe for new ports. Used by exec.
2450
- * @param options.stages - Secret stages to try, in order. Default: ['dev', 'development'].
2451
- * @param options.startDocker - Start Docker Compose services after port resolution. Default: false.
2452
- * @param options.secretsFileName - Custom secrets JSON filename. Default: 'dev-secrets-{appName}.json' or 'dev-secrets.json'.
2453
- * @internal Exported for testing
3000
+ * The addresses come from the ports the workspace already assigns; which
3001
+ * construct sits at which one comes from the manifest. That split is the point:
3002
+ * this used to answer "who may call whom" by listing every app the workspace
3003
+ * runs, which is a different question that happened to give the same answer in
3004
+ * a single-repo workspace and no answer at all deployed. Now it answers only
3005
+ * "where does this construct answer", and the graph answers the rest.
3006
+ *
3007
+ * A site is matched to its app by `path`, because that is the one thing a site
3008
+ * declaration and a workspace app both name. Surfaces are matched to the
3009
+ * backend app: every `rest-api` in a process answers on that process's port, so
3010
+ * an app serving both its own API and an auth server publishes one address
3011
+ * twice — which is exactly what it does at runtime.
2454
3012
  */
2455
- async function prepareEntryCredentials(options) {
2456
- const cwd = options.cwd ?? process.cwd();
2457
- const portMode = options.resolveDockerPorts ?? "full";
2458
- let workspaceAppPort;
2459
- let secretsRoot = cwd;
2460
- let appName;
2461
- let appInfo;
2462
- try {
2463
- appInfo = await require_config.loadWorkspaceAppInfo(cwd);
2464
- workspaceAppPort = appInfo.app.port;
2465
- secretsRoot = appInfo.workspaceRoot;
2466
- appName = appInfo.appName;
2467
- } catch {
2468
- secretsRoot = findSecretsRoot(cwd);
2469
- appName = require_config.getAppNameFromCwd(cwd) ?? void 0;
2470
- }
2471
- const resolvedPort = options.explicitPort ?? workspaceAppPort ?? 3e3;
2472
- const credentials = await loadSecretsForApp(secretsRoot, appName, options.stages);
2473
- credentials.PORT = String(resolvedPort);
2474
- const declaredKeys = [];
2475
- if (appInfo && usesConstructs(appInfo.workspace)) {
2476
- const { reconcileWorkspace: reconcileWorkspace$1 } = await Promise.resolve().then(() => require("./workspace-DdJss8I6.cjs"));
2477
- const reconciled = await reconcileWorkspace$1(appInfo.workspace, {
2478
- stage: options.reconcileStage ?? "development",
2479
- start: options.startDocker ?? false
2480
- });
2481
- Object.assign(credentials, reconciled.env);
2482
- declaredKeys.push(...Object.keys(reconciled.env));
2483
- if (Object.keys(reconciled.env).length > 0) logger.log(`🔌 Resolved ${Object.keys(reconciled.env).length} declared URL(s)`);
2484
- } else {
2485
- const composePath = (0, node_path.join)(secretsRoot, "docker-compose.yml");
2486
- const mappings = parseComposePortMappings(composePath);
2487
- if (mappings.length > 0) {
2488
- let resolvedPorts;
2489
- if (portMode === "full") resolvedPorts = await resolveServicePorts(secretsRoot);
2490
- else {
2491
- const savedPorts = await loadPortState(secretsRoot);
2492
- const ports = {};
2493
- for (const mapping of mappings) {
2494
- const containerPort = getContainerHostPort(secretsRoot, mapping.service, mapping.containerPort);
2495
- if (containerPort !== null) ports[mapping.envVar] = containerPort;
2496
- else {
2497
- const saved = savedPorts[mapping.envVar];
2498
- if (saved !== void 0) ports[mapping.envVar] = saved;
2499
- }
2500
- }
2501
- resolvedPorts = {
2502
- dockerEnv: {},
2503
- ports,
2504
- mappings
2505
- };
2506
- }
2507
- if (options.startDocker) if (appInfo) await startWorkspaceServices(appInfo.workspace, resolvedPorts.dockerEnv, credentials);
2508
- else await startComposeServices(secretsRoot, resolvedPorts.dockerEnv, credentials);
2509
- if (Object.keys(resolvedPorts.ports).length > 0) {
2510
- const rewritten = rewriteUrlsWithPorts(credentials, resolvedPorts);
2511
- Object.assign(credentials, rewritten);
2512
- logger.log(`🔌 Applied ${Object.keys(resolvedPorts.ports).length} port mapping(s)`);
2513
- }
2514
- }
2515
- }
2516
- if (appInfo?.appName) {
2517
- const depEnv = require_workspace.getDependencyEnvVars(appInfo.workspace, appInfo.appName);
2518
- Object.assign(credentials, depEnv);
2519
- }
2520
- if (!credentials.EVENT_PUBLISHER_CONNECTION_STRING && !credentials.EVENT_SUBSCRIBER_CONNECTION_STRING && credentials.PGBOSS_DB_USER) {
2521
- const pgbossUrl = require_generator.generatePgBossUrl({
2522
- username: credentials.PGBOSS_DB_USER,
2523
- password: credentials.PGBOSS_DB_PASSWORD ?? "",
2524
- host: credentials.POSTGRES_HOST ?? "localhost",
2525
- port: Number(credentials.POSTGRES_PORT ?? "5432"),
2526
- database: credentials.POSTGRES_DB ?? "app"
2527
- });
2528
- credentials.EVENT_PUBLISHER_CONNECTION_STRING = pgbossUrl;
2529
- credentials.EVENT_SUBSCRIBER_CONNECTION_STRING = pgbossUrl;
3013
+ function surfaceAddresses(workspace, manifest, at = (_app, port) => localAddress(port)) {
3014
+ const addresses = {};
3015
+ for (const [id, declaration] of Object.entries(manifest)) {
3016
+ if (declaration.kind !== "rest-api" && declaration.kind !== "site") continue;
3017
+ const host = require_config.appKey(id);
3018
+ const port = workspace.apps[host]?.port;
3019
+ if (port) addresses[id] = at(host, port);
2530
3020
  }
2531
- const secretsDir = (0, node_path.join)(secretsRoot, ".gkm");
2532
- await (0, node_fs_promises.mkdir)(secretsDir, { recursive: true });
2533
- const secretsFileName = options.secretsFileName ?? (appName ? `dev-secrets-${appName}.json` : "dev-secrets.json");
2534
- const secretsJsonPath = (0, node_path.join)(secretsDir, secretsFileName);
2535
- await (0, node_fs_promises.writeFile)(secretsJsonPath, JSON.stringify(credentials, null, 2));
2536
- return {
2537
- credentials,
2538
- resolvedPort,
2539
- secretsJsonPath,
2540
- appName,
2541
- secretsRoot,
2542
- appInfo,
2543
- declaredKeys
2544
- };
3021
+ return addresses;
3022
+ }
3023
+ /** Where a local process answers, given the port the workspace gave it. */
3024
+ function localAddress(port) {
3025
+ return `http://localhost:${port}`;
2545
3026
  }
2546
-
2547
3027
  //#endregion
2548
- Object.defineProperty(exports, 'LOCAL_CA_PATH', {
2549
- enumerable: true,
2550
- get: function () {
2551
- return LOCAL_CA_PATH;
2552
- }
3028
+ Object.defineProperty(exports, "COMPOSE_PATH", {
3029
+ enumerable: true,
3030
+ get: function() {
3031
+ return COMPOSE_PATH;
3032
+ }
3033
+ });
3034
+ Object.defineProperty(exports, "FAKE_ENV", {
3035
+ enumerable: true,
3036
+ get: function() {
3037
+ return FAKE_ENV;
3038
+ }
3039
+ });
3040
+ Object.defineProperty(exports, "LOCAL_CA_PATH", {
3041
+ enumerable: true,
3042
+ get: function() {
3043
+ return LOCAL_CA_PATH;
3044
+ }
2553
3045
  });
2554
- Object.defineProperty(exports, 'applyPostgres', {
2555
- enumerable: true,
2556
- get: function () {
2557
- return applyPostgres;
2558
- }
3046
+ Object.defineProperty(exports, "applyPostgres", {
3047
+ enumerable: true,
3048
+ get: function() {
3049
+ return applyPostgres;
3050
+ }
3051
+ });
3052
+ Object.defineProperty(exports, "backendsOf", {
3053
+ enumerable: true,
3054
+ get: function() {
3055
+ return backendsOf;
3056
+ }
2559
3057
  });
2560
- Object.defineProperty(exports, 'cacheBackendOf', {
2561
- enumerable: true,
2562
- get: function () {
2563
- return cacheBackendOf;
2564
- }
3058
+ Object.defineProperty(exports, "constructGlobs", {
3059
+ enumerable: true,
3060
+ get: function() {
3061
+ return constructGlobs;
3062
+ }
2565
3063
  });
2566
- Object.defineProperty(exports, 'constructGlobs', {
2567
- enumerable: true,
2568
- get: function () {
2569
- return constructGlobs;
2570
- }
3064
+ Object.defineProperty(exports, "createCredentialsPreload", {
3065
+ enumerable: true,
3066
+ get: function() {
3067
+ return createCredentialsPreload;
3068
+ }
2571
3069
  });
2572
- Object.defineProperty(exports, 'createCredentialsPreload', {
2573
- enumerable: true,
2574
- get: function () {
2575
- return createCredentialsPreload;
2576
- }
3070
+ Object.defineProperty(exports, "createEntryWrapper", {
3071
+ enumerable: true,
3072
+ get: function() {
3073
+ return createEntryWrapper;
3074
+ }
2577
3075
  });
2578
- Object.defineProperty(exports, 'createEntryWrapper', {
2579
- enumerable: true,
2580
- get: function () {
2581
- return createEntryWrapper;
2582
- }
3076
+ Object.defineProperty(exports, "derivedContainers", {
3077
+ enumerable: true,
3078
+ get: function() {
3079
+ return derivedContainers;
3080
+ }
2583
3081
  });
2584
- Object.defineProperty(exports, 'derivedContainers', {
2585
- enumerable: true,
2586
- get: function () {
2587
- return derivedContainers;
2588
- }
3082
+ Object.defineProperty(exports, "describeServices", {
3083
+ enumerable: true,
3084
+ get: function() {
3085
+ return describeServices;
3086
+ }
2589
3087
  });
2590
- Object.defineProperty(exports, 'emailBackendOf', {
2591
- enumerable: true,
2592
- get: function () {
2593
- return emailBackendOf;
2594
- }
3088
+ Object.defineProperty(exports, "fakeKey", {
3089
+ enumerable: true,
3090
+ get: function() {
3091
+ return fakeKey;
3092
+ }
2595
3093
  });
2596
- Object.defineProperty(exports, 'findAvailablePort', {
2597
- enumerable: true,
2598
- get: function () {
2599
- return findAvailablePort;
2600
- }
3094
+ Object.defineProperty(exports, "findAvailablePort", {
3095
+ enumerable: true,
3096
+ get: function() {
3097
+ return findAvailablePort;
3098
+ }
2601
3099
  });
2602
- Object.defineProperty(exports, 'imagePins', {
2603
- enumerable: true,
2604
- get: function () {
2605
- return imagePins;
2606
- }
3100
+ Object.defineProperty(exports, "forgetState", {
3101
+ enumerable: true,
3102
+ get: function() {
3103
+ return forgetState;
3104
+ }
2607
3105
  });
2608
- Object.defineProperty(exports, 'isPortAvailable', {
2609
- enumerable: true,
2610
- get: function () {
2611
- return isPortAvailable;
2612
- }
3106
+ Object.defineProperty(exports, "isPortAvailable", {
3107
+ enumerable: true,
3108
+ get: function() {
3109
+ return isPortAvailable;
3110
+ }
2613
3111
  });
2614
- Object.defineProperty(exports, 'loadEnvFiles', {
2615
- enumerable: true,
2616
- get: function () {
2617
- return loadEnvFiles;
2618
- }
3112
+ Object.defineProperty(exports, "loadEnvFiles", {
3113
+ enumerable: true,
3114
+ get: function() {
3115
+ return loadEnvFiles;
3116
+ }
2619
3117
  });
2620
- Object.defineProperty(exports, 'loadSecretsForApp', {
2621
- enumerable: true,
2622
- get: function () {
2623
- return loadSecretsForApp;
2624
- }
3118
+ Object.defineProperty(exports, "loadSecretsForApp", {
3119
+ enumerable: true,
3120
+ get: function() {
3121
+ return loadSecretsForApp;
3122
+ }
2625
3123
  });
2626
- Object.defineProperty(exports, 'prepareEntryCredentials', {
2627
- enumerable: true,
2628
- get: function () {
2629
- return prepareEntryCredentials;
2630
- }
3124
+ Object.defineProperty(exports, "pgClient", {
3125
+ enumerable: true,
3126
+ get: function() {
3127
+ return pgClient;
3128
+ }
2631
3129
  });
2632
- Object.defineProperty(exports, 'providerOf', {
2633
- enumerable: true,
2634
- get: function () {
2635
- return providerOf;
2636
- }
3130
+ Object.defineProperty(exports, "postgresDatabaseNames", {
3131
+ enumerable: true,
3132
+ get: function() {
3133
+ return postgresDatabaseNames;
3134
+ }
2637
3135
  });
2638
- Object.defineProperty(exports, 'reconcileWorkspace', {
2639
- enumerable: true,
2640
- get: function () {
2641
- return reconcileWorkspace;
2642
- }
3136
+ Object.defineProperty(exports, "prepareEntryCredentials", {
3137
+ enumerable: true,
3138
+ get: function() {
3139
+ return prepareEntryCredentials;
3140
+ }
2643
3141
  });
2644
- Object.defineProperty(exports, 'resolveServicePorts', {
2645
- enumerable: true,
2646
- get: function () {
2647
- return resolveServicePorts;
2648
- }
3142
+ Object.defineProperty(exports, "primaryPortKey", {
3143
+ enumerable: true,
3144
+ get: function() {
3145
+ return primaryPortKey;
3146
+ }
2649
3147
  });
2650
- Object.defineProperty(exports, 'resourceName', {
2651
- enumerable: true,
2652
- get: function () {
2653
- return resourceName;
2654
- }
3148
+ Object.defineProperty(exports, "quoteIdentifier", {
3149
+ enumerable: true,
3150
+ get: function() {
3151
+ return quoteIdentifier;
3152
+ }
2655
3153
  });
2656
- Object.defineProperty(exports, 'rewriteUrlsWithPorts', {
2657
- enumerable: true,
2658
- get: function () {
2659
- return rewriteUrlsWithPorts;
2660
- }
3154
+ Object.defineProperty(exports, "reconcileWorkspace", {
3155
+ enumerable: true,
3156
+ get: function() {
3157
+ return reconcileWorkspace;
3158
+ }
2661
3159
  });
2662
- Object.defineProperty(exports, 'startWorkspaceServices', {
2663
- enumerable: true,
2664
- get: function () {
2665
- return startWorkspaceServices;
2666
- }
3160
+ Object.defineProperty(exports, "resourceName", {
3161
+ enumerable: true,
3162
+ get: function() {
3163
+ return resourceName;
3164
+ }
2667
3165
  });
2668
- Object.defineProperty(exports, 'storageBackendOf', {
2669
- enumerable: true,
2670
- get: function () {
2671
- return storageBackendOf;
2672
- }
3166
+ Object.defineProperty(exports, "rootSite", {
3167
+ enumerable: true,
3168
+ get: function() {
3169
+ return rootSite;
3170
+ }
2673
3171
  });
2674
- Object.defineProperty(exports, 'usesConstructs', {
2675
- enumerable: true,
2676
- get: function () {
2677
- return usesConstructs;
2678
- }
3172
+ Object.defineProperty(exports, "workspace_exports", {
3173
+ enumerable: true,
3174
+ get: function() {
3175
+ return workspace_exports;
3176
+ }
2679
3177
  });
2680
- //# sourceMappingURL=credentials-G1JwBoXH.cjs.map
3178
+
3179
+ //# sourceMappingURL=workspace-GBzR_hID.cjs.map