@geekmidas/cli 10.0.0-alpha.144 → 10.0.0-alpha.146

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 (185) hide show
  1. package/dist/{GoDaddyProvider-IVuFcWyc.mjs → GoDaddyProvider-BESq24p-.mjs} +2 -2
  2. package/dist/{GoDaddyProvider-IVuFcWyc.mjs.map → GoDaddyProvider-BESq24p-.mjs.map} +1 -1
  3. package/dist/{GoDaddyProvider-DAJIa64i.cjs → GoDaddyProvider-BK5N6-fx.cjs} +2 -2
  4. package/dist/{GoDaddyProvider-DAJIa64i.cjs.map → GoDaddyProvider-BK5N6-fx.cjs.map} +1 -1
  5. package/dist/{HostingerProvider-BtLb-jkn.mjs → HostingerProvider-BV30wTNI.mjs} +2 -2
  6. package/dist/{HostingerProvider-BtLb-jkn.mjs.map → HostingerProvider-BV30wTNI.mjs.map} +1 -1
  7. package/dist/{HostingerProvider-DdikWVRy.cjs → HostingerProvider-BbQod5OB.cjs} +2 -2
  8. package/dist/{HostingerProvider-DdikWVRy.cjs.map → HostingerProvider-BbQod5OB.cjs.map} +1 -1
  9. package/dist/{LegacyStateStore-CmgUY9kR.mjs → LegacyStateStore-Ck3HI28A.mjs} +2 -2
  10. package/dist/{LegacyStateStore-CmgUY9kR.mjs.map → LegacyStateStore-Ck3HI28A.mjs.map} +1 -1
  11. package/dist/{LegacyStateStore-CWwT7Mj5.cjs → LegacyStateStore-OEno6vIb.cjs} +2 -2
  12. package/dist/{LegacyStateStore-CWwT7Mj5.cjs.map → LegacyStateStore-OEno6vIb.cjs.map} +1 -1
  13. package/dist/{LocalStateStore-NOmS4QyA.mjs → LocalStateStore-Fa54CpLw.mjs} +2 -2
  14. package/dist/{LocalStateStore-NOmS4QyA.mjs.map → LocalStateStore-Fa54CpLw.mjs.map} +1 -1
  15. package/dist/{LocalStateStore-BkeQg1ga.cjs → LocalStateStore-ukDFg6GM.cjs} +2 -2
  16. package/dist/{LocalStateStore-BkeQg1ga.cjs.map → LocalStateStore-ukDFg6GM.cjs.map} +1 -1
  17. package/dist/{S3StateStore-Cw2nwI5C.cjs → S3StateStore-Cjuft2Lk.cjs} +4 -4
  18. package/dist/{S3StateStore-Cw2nwI5C.cjs.map → S3StateStore-Cjuft2Lk.cjs.map} +1 -1
  19. package/dist/{S3StateStore-SjIxuWHM.mjs → S3StateStore-D53985SR.mjs} +4 -4
  20. package/dist/{S3StateStore-SjIxuWHM.mjs.map → S3StateStore-D53985SR.mjs.map} +1 -1
  21. package/dist/{SSMStateStore-DGqzo4Ob.mjs → SSMStateStore-CRjV2h2G.mjs} +2 -2
  22. package/dist/{SSMStateStore-DGqzo4Ob.mjs.map → SSMStateStore-CRjV2h2G.mjs.map} +1 -1
  23. package/dist/{SSMStateStore-DC1N1Baw.cjs → SSMStateStore-CnJgw3_-.cjs} +2 -2
  24. package/dist/{SSMStateStore-DC1N1Baw.cjs.map → SSMStateStore-CnJgw3_-.cjs.map} +1 -1
  25. package/dist/{add-BwC_EH0e.cjs → add-CG_4mNir.cjs} +7 -7
  26. package/dist/{add-BwC_EH0e.cjs.map → add-CG_4mNir.cjs.map} +1 -1
  27. package/dist/{add-Bnd7vuUN.mjs → add-D0-1UyFj.mjs} +7 -7
  28. package/dist/{add-Bnd7vuUN.mjs.map → add-D0-1UyFj.mjs.map} +1 -1
  29. package/dist/{apps-D1svw9OG.cjs → apps-DHi6E_yH.cjs} +416 -51
  30. package/dist/apps-DHi6E_yH.cjs.map +1 -0
  31. package/dist/{apps-Xrlvir2-.mjs → apps-DWALM-8s.mjs} +389 -49
  32. package/dist/apps-DWALM-8s.mjs.map +1 -0
  33. package/dist/{bundler-CoRIF5bx.mjs → bundler-Cb5ynXXS.mjs} +6 -6
  34. package/dist/{bundler-CoRIF5bx.mjs.map → bundler-Cb5ynXXS.mjs.map} +1 -1
  35. package/dist/{bundler-CgWYsgqb.cjs → bundler-Co_7zpYC.cjs} +6 -6
  36. package/dist/{bundler-CgWYsgqb.cjs.map → bundler-Co_7zpYC.cjs.map} +1 -1
  37. package/dist/{cli-DsPHbC7p.cjs → cli-C5M_7Kux.cjs} +4 -4
  38. package/dist/{cli-DsPHbC7p.cjs.map → cli-C5M_7Kux.cjs.map} +1 -1
  39. package/dist/{cli-CKlTRVwo.mjs → cli-D_9WqN6C.mjs} +4 -4
  40. package/dist/{cli-CKlTRVwo.mjs.map → cli-D_9WqN6C.mjs.map} +1 -1
  41. package/dist/{compose-BMTnoIek.mjs → compose-7p0-3ogo.mjs} +5 -5
  42. package/dist/compose-7p0-3ogo.mjs.map +1 -0
  43. package/dist/{compose-ChUQHKG3.cjs → compose-BeQ01iYk.cjs} +27 -25
  44. package/dist/compose-BeQ01iYk.cjs.map +1 -0
  45. package/dist/{compose-CVAoA04l.cjs → compose-C10hkeHU.cjs} +5 -5
  46. package/dist/compose-C10hkeHU.cjs.map +1 -0
  47. package/dist/{compose-CkvPmijw.mjs → compose-DxmEMeTu.mjs} +27 -25
  48. package/dist/compose-DxmEMeTu.mjs.map +1 -0
  49. package/dist/{config-BKpzKP6W.mjs → config-B-wza0Xk.mjs} +2 -2
  50. package/dist/{config-BKpzKP6W.mjs.map → config-B-wza0Xk.mjs.map} +1 -1
  51. package/dist/{config-QAqAEgb0.cjs → config-CWExbDxA.cjs} +2 -2
  52. package/dist/{config-QAqAEgb0.cjs.map → config-CWExbDxA.cjs.map} +1 -1
  53. package/dist/config.cjs +2 -2
  54. package/dist/config.mjs +2 -2
  55. package/dist/{credentials-Jx1Vdisc.mjs → credentials-B5Oe4fLE.mjs} +7 -7
  56. package/dist/{credentials-Jx1Vdisc.mjs.map → credentials-B5Oe4fLE.mjs.map} +1 -1
  57. package/dist/{credentials-CCIXh-cq.cjs → credentials-Csnd7M8M.cjs} +7 -7
  58. package/dist/{credentials-CCIXh-cq.cjs.map → credentials-Csnd7M8M.cjs.map} +1 -1
  59. package/dist/deploy/public.cjs +12 -12
  60. package/dist/deploy/public.mjs +12 -12
  61. package/dist/{deploy-8wsaNpPW.mjs → deploy-6DDEG4Ai.mjs} +13 -13
  62. package/dist/{deploy-8wsaNpPW.mjs.map → deploy-6DDEG4Ai.mjs.map} +1 -1
  63. package/dist/{deploy-CEX0YRdq.cjs → deploy-BwNxJ3ZI.cjs} +13 -13
  64. package/dist/{deploy-CEX0YRdq.cjs.map → deploy-BwNxJ3ZI.cjs.map} +1 -1
  65. package/dist/{docker-M_-xKiFU.cjs → docker-BZnNUJCy.cjs} +5 -5
  66. package/dist/{docker-M_-xKiFU.cjs.map → docker-BZnNUJCy.cjs.map} +1 -1
  67. package/dist/{docker-M4kCqczV.mjs → docker-Ch5aPQ04.mjs} +5 -5
  68. package/dist/{docker-M4kCqczV.mjs.map → docker-Ch5aPQ04.mjs.map} +1 -1
  69. package/dist/{dokploy-BsAPW8K1.mjs → dokploy-CTWw3WSo.mjs} +2 -2
  70. package/dist/{dokploy-BsAPW8K1.mjs.map → dokploy-CTWw3WSo.mjs.map} +1 -1
  71. package/dist/{dokploy-Djm8QIQZ.cjs → dokploy-Cn7dQqmE.cjs} +2 -2
  72. package/dist/{dokploy-Djm8QIQZ.cjs.map → dokploy-Cn7dQqmE.cjs.map} +1 -1
  73. package/dist/{eas-zEpuiYYj.mjs → eas-D0B8H7hT.mjs} +3 -3
  74. package/dist/{eas-zEpuiYYj.mjs.map → eas-D0B8H7hT.mjs.map} +1 -1
  75. package/dist/{eas-B-Ac5NjL.cjs → eas-IPjz0PWK.cjs} +3 -3
  76. package/dist/{eas-B-Ac5NjL.cjs.map → eas-IPjz0PWK.cjs.map} +1 -1
  77. package/dist/{encryption-EOEhb95p.mjs → encryption-C9auXcSV.mjs} +4 -4
  78. package/dist/{encryption-EOEhb95p.mjs.map → encryption-C9auXcSV.mjs.map} +1 -1
  79. package/dist/{encryption-B4LCEdXH.cjs → encryption-vK64UP4M.cjs} +4 -4
  80. package/dist/{encryption-B4LCEdXH.cjs.map → encryption-vK64UP4M.cjs.map} +1 -1
  81. package/dist/{engine-Ci-uU3kt.mjs → engine-C3N2WhbC.mjs} +10 -10
  82. package/dist/{engine-Ci-uU3kt.mjs.map → engine-C3N2WhbC.mjs.map} +1 -1
  83. package/dist/{engine-6NLOikTQ.cjs → engine-Icqv5JI6.cjs} +10 -10
  84. package/dist/{engine-6NLOikTQ.cjs.map → engine-Icqv5JI6.cjs.map} +1 -1
  85. package/dist/{github-C0oLDg5G.mjs → github-D24wTOe2.mjs} +9 -9
  86. package/dist/{github-C0oLDg5G.mjs.map → github-D24wTOe2.mjs.map} +1 -1
  87. package/dist/{github-u9sfpl0l.cjs → github-DUuNInc0.cjs} +9 -9
  88. package/dist/{github-u9sfpl0l.cjs.map → github-DUuNInc0.cjs.map} +1 -1
  89. package/dist/{googlePlay-DfLH_sPa.cjs → googlePlay-BGDKlnPx.cjs} +5 -5
  90. package/dist/{googlePlay-DfLH_sPa.cjs.map → googlePlay-BGDKlnPx.cjs.map} +1 -1
  91. package/dist/{googlePlay-3nfA-wWh.mjs → googlePlay-Cy-MaYr2.mjs} +5 -5
  92. package/dist/{googlePlay-3nfA-wWh.mjs.map → googlePlay-Cy-MaYr2.mjs.map} +1 -1
  93. package/dist/index.cjs +71 -79
  94. package/dist/index.cjs.map +1 -1
  95. package/dist/index.mjs +71 -79
  96. package/dist/index.mjs.map +1 -1
  97. package/dist/{local-CtzKG55y.cjs → local-B4xobzh-.cjs} +2 -2
  98. package/dist/{local-CtzKG55y.cjs.map → local-B4xobzh-.cjs.map} +1 -1
  99. package/dist/{local-uvqZDwZ9.mjs → local-CdpBgn3d.mjs} +2 -2
  100. package/dist/{local-uvqZDwZ9.mjs.map → local-CdpBgn3d.mjs.map} +1 -1
  101. package/dist/{migrate-C6V9bEVY.cjs → migrate--hMBtpx-.cjs} +4 -4
  102. package/dist/{migrate-C6V9bEVY.cjs.map → migrate--hMBtpx-.cjs.map} +1 -1
  103. package/dist/{migrate-CA1GWA4t.mjs → migrate-DVrXTq58.mjs} +4 -4
  104. package/dist/{migrate-CA1GWA4t.mjs.map → migrate-DVrXTq58.mjs.map} +1 -1
  105. package/dist/{migrate-s9lVmF98.mjs → migrate-DhZfvCkJ.mjs} +6 -6
  106. package/dist/{migrate-s9lVmF98.mjs.map → migrate-DhZfvCkJ.mjs.map} +1 -1
  107. package/dist/{migrate-FKPFIzwd.cjs → migrate-DwQ-zaMy.cjs} +6 -6
  108. package/dist/{migrate-FKPFIzwd.cjs.map → migrate-DwQ-zaMy.cjs.map} +1 -1
  109. package/dist/{notes-BjxySbyH.cjs → notes-C2b5RzGl.cjs} +4 -4
  110. package/dist/{notes-BjxySbyH.cjs.map → notes-C2b5RzGl.cjs.map} +1 -1
  111. package/dist/{notes-Dz1M9_q9.mjs → notes-z5OOMqm4.mjs} +4 -4
  112. package/dist/{notes-Dz1M9_q9.mjs.map → notes-z5OOMqm4.mjs.map} +1 -1
  113. package/dist/openapi.cjs +2 -2
  114. package/dist/openapi.mjs +2 -2
  115. package/dist/{projectBucket-2XgQSnLw.mjs → projectBucket-DPD0_B8N.mjs} +2 -2
  116. package/dist/{projectBucket-2XgQSnLw.mjs.map → projectBucket-DPD0_B8N.mjs.map} +1 -1
  117. package/dist/{projectBucket-DsXNW1Yc.cjs → projectBucket-Dk_aZ1cD.cjs} +2 -2
  118. package/dist/{projectBucket-DsXNW1Yc.cjs.map → projectBucket-Dk_aZ1cD.cjs.map} +1 -1
  119. package/dist/{publish-Dmy_OhvF.mjs → publish-Bmc1Wfs3.mjs} +2 -2
  120. package/dist/{publish-Dmy_OhvF.mjs.map → publish-Bmc1Wfs3.mjs.map} +1 -1
  121. package/dist/{publish-7-dwP5TL.cjs → publish-CDvh-9OG.cjs} +2 -2
  122. package/dist/{publish-7-dwP5TL.cjs.map → publish-CDvh-9OG.cjs.map} +1 -1
  123. package/dist/{resolve-DhsUJwm8.cjs → resolve-CuxPZ3ga.cjs} +4 -4
  124. package/dist/{resolve-DhsUJwm8.cjs.map → resolve-CuxPZ3ga.cjs.map} +1 -1
  125. package/dist/{resolve-BK7mzDBb.mjs → resolve-DHARlMdl.mjs} +4 -4
  126. package/dist/{resolve-BK7mzDBb.mjs.map → resolve-DHARlMdl.mjs.map} +1 -1
  127. package/dist/{rollback-8qHgyadV.mjs → rollback-DZq_dIbl.mjs} +7 -7
  128. package/dist/{rollback-8qHgyadV.mjs.map → rollback-DZq_dIbl.mjs.map} +1 -1
  129. package/dist/{rollback-DP2iDjc9.cjs → rollback-DxHut8C-.cjs} +7 -7
  130. package/dist/{rollback-DP2iDjc9.cjs.map → rollback-DxHut8C-.cjs.map} +1 -1
  131. package/dist/{s3-DxCex5Fx.mjs → s3-Cd7UK2y8.mjs} +3 -3
  132. package/dist/{s3-DxCex5Fx.mjs.map → s3-Cd7UK2y8.mjs.map} +1 -1
  133. package/dist/{s3-DSPbU5gN.cjs → s3-Dhy58V_y.cjs} +3 -3
  134. package/dist/{s3-DSPbU5gN.cjs.map → s3-Dhy58V_y.cjs.map} +1 -1
  135. package/dist/{serverSetup-BSuHk2t2.cjs → serverSetup-DYiKHMVp.cjs} +7 -7
  136. package/dist/{serverSetup-BSuHk2t2.cjs.map → serverSetup-DYiKHMVp.cjs.map} +1 -1
  137. package/dist/{serverSetup-CeFpl5VJ.mjs → serverSetup-qe5bdBhO.mjs} +7 -7
  138. package/dist/{serverSetup-CeFpl5VJ.mjs.map → serverSetup-qe5bdBhO.mjs.map} +1 -1
  139. package/dist/{sniffer-BfNl8jn-.mjs → sniffer-BNcLP8MO.mjs} +7 -7
  140. package/dist/{sniffer-BfNl8jn-.mjs.map → sniffer-BNcLP8MO.mjs.map} +1 -1
  141. package/dist/{sniffer-Cb3n63dY.cjs → sniffer-DFix2ORf.cjs} +7 -7
  142. package/dist/{sniffer-Cb3n63dY.cjs.map → sniffer-DFix2ORf.cjs.map} +1 -1
  143. package/dist/{snsSubscriptions-DoZ0Q1n6.mjs → snsSubscriptions-BwX28_Kl.mjs} +3 -3
  144. package/dist/{snsSubscriptions-DoZ0Q1n6.mjs.map → snsSubscriptions-BwX28_Kl.mjs.map} +1 -1
  145. package/dist/{snsSubscriptions-Bd40ebt6.cjs → snsSubscriptions-Dr-gJWtR.cjs} +3 -3
  146. package/dist/{snsSubscriptions-Bd40ebt6.cjs.map → snsSubscriptions-Dr-gJWtR.cjs.map} +1 -1
  147. package/dist/{sst-B6RbJp8g.mjs → sst-Bvtx6uZ9.mjs} +5 -5
  148. package/dist/{sst-B6RbJp8g.mjs.map → sst-Bvtx6uZ9.mjs.map} +1 -1
  149. package/dist/{sst-DKNyfTpw.cjs → sst-CoKFPW7f.cjs} +5 -5
  150. package/dist/{sst-DKNyfTpw.cjs.map → sst-CoKFPW7f.cjs.map} +1 -1
  151. package/dist/{stack-DwQ62dKK.mjs → stack-BeSbt_7k.mjs} +100 -45
  152. package/dist/stack-BeSbt_7k.mjs.map +1 -0
  153. package/dist/{stack-UcV-V6Qk.cjs → stack-DbaKGKnI.cjs} +100 -45
  154. package/dist/stack-DbaKGKnI.cjs.map +1 -0
  155. package/dist/{stage-52sKecmS.mjs → stage-BblkSR2C.mjs} +7 -7
  156. package/dist/{stage-52sKecmS.mjs.map → stage-BblkSR2C.mjs.map} +1 -1
  157. package/dist/{stage-C2v5890I.cjs → stage-DI5mzoAi.cjs} +7 -7
  158. package/dist/{stage-C2v5890I.cjs.map → stage-DI5mzoAi.cjs.map} +1 -1
  159. package/dist/{stages-CFI0OiLj.cjs → stages-C-bVwvJZ.cjs} +3 -3
  160. package/dist/{stages-CFI0OiLj.cjs.map → stages-C-bVwvJZ.cjs.map} +1 -1
  161. package/dist/{stages-DoYa81kN.mjs → stages-DBsDvEbo.mjs} +3 -3
  162. package/dist/{stages-DoYa81kN.mjs.map → stages-DBsDvEbo.mjs.map} +1 -1
  163. package/dist/target/public.cjs +1 -1
  164. package/dist/target/public.mjs +1 -1
  165. package/dist/{terminal-DkXWdU0E.cjs → terminal-Bxy_A8iP.cjs} +2 -2
  166. package/dist/{terminal-DkXWdU0E.cjs.map → terminal-Bxy_A8iP.cjs.map} +1 -1
  167. package/dist/{terminal-BDEqpkbO.mjs → terminal-DDqusYW0.mjs} +2 -2
  168. package/dist/{terminal-BDEqpkbO.mjs.map → terminal-DDqusYW0.mjs.map} +1 -1
  169. package/dist/workspace/index.cjs +1 -1
  170. package/dist/workspace/index.mjs +1 -1
  171. package/dist/{workspace-Dkm3HL9e.cjs → workspace-BbbkJDUU.cjs} +5 -5
  172. package/dist/workspace-BbbkJDUU.cjs.map +1 -0
  173. package/dist/{workspace-BbfBFtjn.mjs → workspace-CZGJdcTs.mjs} +5 -5
  174. package/dist/workspace-CZGJdcTs.mjs.map +1 -0
  175. package/package.json +17 -15
  176. package/dist/apps-D1svw9OG.cjs.map +0 -1
  177. package/dist/apps-Xrlvir2-.mjs.map +0 -1
  178. package/dist/compose-BMTnoIek.mjs.map +0 -1
  179. package/dist/compose-CVAoA04l.cjs.map +0 -1
  180. package/dist/compose-ChUQHKG3.cjs.map +0 -1
  181. package/dist/compose-CkvPmijw.mjs.map +0 -1
  182. package/dist/stack-DwQ62dKK.mjs.map +0 -1
  183. package/dist/stack-UcV-V6Qk.cjs.map +0 -1
  184. package/dist/workspace-BbfBFtjn.mjs.map +0 -1
  185. package/dist/workspace-Dkm3HL9e.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"apps-D1svw9OG.cjs","names":["hostFor","WILDCARD_SUBDOMAIN","CLIENT_IP_HEADER","TELEMETRY_KEYS","appKey","stageSampleRate","DEFAULT_CACHE","holdsEveryCache","fakeKey","providedKeyFor","dependentsOf","publicEnvFor","bucketExpiry","isWildcardSite","protectedSubdomains","WILDCARD_SUBDOMAIN","rootSite","appKey","GkmError","provideKey","wildcardDomainOf","telemetryEnv","otlpHeaders","primaryPortKey","objectsWebhookToken","INBOX_RELAY_TOKEN_KEY","inboxRelayToken","cookieDomain","mobileOrigins","ownerRole","schemeBase","externalApiUrl","hostFor","readerRole","LOGS_ORG","cacheTable","emulatorEndpoint","snsUrl","emulatorTopicArn","EMULATOR_REGION","sqsUrl","emulatorQueueUrl","createHash","GkmError","formatKeyring","drawSecret","createHash","cacheTable","cacheTableStatements","ownerRole","readerRole","roleStatements","NOTIFICATION_RULE_PREFIX","minioNotificationRule","GkmError","appKey","isAbsolute","join","relative","sep","provideKey","publicEnvFor","PUBLIC_PREFIX","PUBLIC_ENV_PREFIXES","dirname","join","existsSync","parse","readFileSync","telemetryArgs","externalsManifestName","GkmError","relative","join","isAbsolute","allConstructGlobs","readFileSync","sep","Client","S3Client","HeadBucketCommand","CreateBucketCommand","GetBucketPolicyCommand","PutBucketPolicyCommand","GetBucketLifecycleConfigurationCommand","DeleteBucketLifecycleCommand","PutBucketLifecycleConfigurationCommand","GetBucketNotificationConfigurationCommand","PutBucketNotificationConfigurationCommand","EMULATOR_REGION","emulatorEndpoint","SNSClient","SQSClient","GetTopicAttributesCommand","emulatorTopicArn","CreateTopicCommand","GetQueueUrlCommand","CreateQueueCommand","promisify","execFile","join","dirname","existsSync","spawn","mkdir","networkInterfaces","GkmError","Client","CLUSTER_DATABASE","S3Client","ListBucketsCommand","createHash","GkmError","createServer","createHash","readFile","mkdir","dirname","writeFile","rm","join","provisionOrder","TEST_STAGE","join","portKeys","composeFor","serviceAddresses","primaryPortKey","existsSync","toYaml","portsOf","dirname","readdir","rm","readFile","chmod","mkdir","writeFile","allConstructGlobs","providerOf","eventsBackendFor","cacheBackendFor","discover","provisionOrder","readFakes","readCredentialFakes","loadLocalCredentials","loadPortState","savePortState","saveLocalCredentials","watchedBuckets","HOST_GATEWAY","objectsRoute","objectsWebhookToken","inboxRelayWorker","inboxWebhookUrl","inboxRelayToken","appKey","provisionOrder","appKey","portsOf","portKeys","dependenciesOf","TELEMETRY_KEYS","publicEnvFor","workerEdges","eventsEdgeBucket","provideKey","INBOX_RELAY_TOKEN_KEY"],"sources":["../src/generators/processorRoute.ts","../src/reconcile/caddyfile.ts","../src/telemetry/edges.ts","../src/reconcile/plan.ts","../src/reconcile/env.ts","../src/providers/s3/lifecycle.ts","../src/reconcile/provision.ts","../src/build/workers.ts","../src/compose/siteBuild.ts","../src/exec/imageBuild.ts","../src/docker/templates.ts","../src/docker/layout.ts","../src/reconcile/clients.ts","../src/reconcile/docker.ts","../src/reconcile/lan.ts","../src/reconcile/logins.ts","../src/reconcile/ports.ts","../src/reconcile/state.ts","../src/reconcile/index.ts","../src/reconcile/workspace.ts","../src/reconcile/apps.ts"],"sourcesContent":["/**\n * Where `gkm dev` serves a file server's processors, on the dev server of the\n * app holding them: named after the file server.\n *\n * One definition for both sides — the dev server mounts it, and the local\n * edge rewrites each processor pattern on the file server's host onto it — so\n * the path the edge sends and the path the server answers cannot drift.\n */\nexport const PROCESSORS_DEV_PREFIX = '/__gkm/processors/';\n\n/** The base a file server's processors answer under, in `gkm dev`. */\nexport function processorsDevRoute(fileServerId: string): string {\n\treturn `${PROCESSORS_DEV_PREFIX}${fileServerId}`;\n}\n","/**\n * The Caddy configuration a plan implies.\n *\n * A file server is a *domain that serves a bucket*, and locally it had neither:\n * `UPLOADS_SERVER_URL` resolved to MinIO's path-style address, which works and\n * is not the deployed shape. MinIO's own virtual-host mode cannot fix that —\n * it reads the leading label *as the bucket name*, so it produces the right\n * shape only when the server's id and the bucket's happen to agree, and never\n * for a server fronting two buckets.\n *\n * So the mapping lives in front of MinIO instead: one host per file server,\n * rewriting the bucket in as a path prefix. That is the whole of it — no\n * caching, because caching is not what is missing locally, and a caching proxy\n * would add an invalidation story a local stack has no use for.\n *\n * What it buys beyond the shape is a certificate. Caddy issues one per host\n * from its own CA, so a local address is `https://` like the deployed one, and\n * everything downstream of that — `Secure` cookies, `SameSite`, a cookie domain\n * with more than one host under it — starts behaving the way it will in\n * production rather than the way `http://localhost` allows.\n *\n * Pure, like `composeFor`: what should exist is data, and rendering it is one\n * line at the edge.\n */\n\nimport { CLIENT_IP_HEADER, WILDCARD_SUBDOMAIN } from '@geekmidas/manifest';\nimport { processorsDevRoute } from '../generators/processorRoute.js';\nimport type { Plan, PlannedResource } from './plan';\n\n/** One host on the edge, and what answers behind it. */\nexport interface CaddySite {\n\t/** e.g. `api.kitchen-sink.localhost` */\n\thost: string;\n\t/** Where the request is sent, e.g. `http://minio:9000`. */\n\tupstream: string;\n\t/**\n\t * A path to rewrite to, where the upstream expects a different one.\n\t *\n\t * The bucket prefix on an object store is the case. A surface and a site\n\t * want none: they are already serving the paths the client asked for.\n\t */\n\trewrite?: string;\n\t/**\n\t * Path prefixes sent somewhere else on the same host: a file server's\n\t * processor patterns, to the dev server holding them, under the route it\n\t * mounts them on.\n\t */\n\tprocessors?: {\n\t\tprefixes: readonly string[];\n\t\tupstream: string;\n\t\t/** Prepended to the path: `/__gkm/processors/AssetsServer`. */\n\t\tunder: string;\n\t};\n\t/**\n\t * For a wildcard site: what keeps a host that is not a tenant from\n\t * reaching it — the hosts nothing but an app may answer on, refused\n\t * outright, and the route asked about every other host before it is\n\t * served.\n\t */\n\ttenants?: {\n\t\t/** Full hosts — `api.shop.localhost`, `www.shop.localhost`. */\n\t\tprotected: readonly string[];\n\t\t/** Its `hosts` route: `200` serves the host, anything else is returned. */\n\t\thosts?: { upstream: string; uri: string };\n\t};\n}\n\n/**\n * The kinds the edge serves.\n *\n * Everything that owns a *public address*. Deployed, each of these has a real\n * hostname and a certificate, so this is what makes the local shape the same\n * one rather than a near-enough one — and the application is indifferent\n * either way, because it reads whichever address was injected and never\n * composes one.\n *\n * Adding a kind here is the whole of adding it to the edge.\n */\nexport const EDGE_KINDS: Readonly<Record<string, true>> = {\n\t'file-server': true,\n\t'rest-api': true,\n\t// Caddy proxies the upgrade as it is; nothing about the route differs.\n\t'websocket-api': true,\n\tsite: true,\n};\n\n/**\n * How the edge reaches the host, from inside its container.\n *\n * A surface and a site are served by processes `gkm dev` starts on the host,\n * not by containers — so the edge has to leave Docker's network to reach them.\n * Docker Desktop resolves this name already; on Linux the compose definition\n * maps it to the host gateway.\n */\nconst HOST_GATEWAY = 'host.docker.internal';\n\n/**\n * The suffix every local host shares.\n *\n * `.localhost` rather than a made-up TLD because it resolves to loopback\n * without touching `/etc/hosts` — macOS and systemd-resolved both answer for\n * subdomains of it, and Caddy issues internal certificates for it by default.\n */\nexport const LOCAL_TLD = 'localhost';\n\n/**\n * The sites a plan implies, one per file server.\n *\n * The leading label is the *server's* stage-scoped name rather than the\n * bucket's, which is the difference that matters: two servers over one bucket\n * are a legitimate arrangement — two cache behaviours, one origin — and naming\n * the host after the bucket would make them collide.\n */\nexport function sitesFor(\n\tplan: Plan,\n\tproject: string,\n\t/**\n\t * Where surfaces and sites answer on the host, keyed by construct id.\n\t *\n\t * Assigned by whatever starts them rather than published by a container,\n\t * which is why they arrive here instead of being read off a port.\n\t */\n\taddresses: Readonly<Record<string, string>> = {},\n\t/**\n\t * Where each file server's processors answer, keyed by the file server's\n\t * id: the dev server of the app holding them.\n\t */\n\tprocessorAddresses: Readonly<Record<string, string>> = {},\n): CaddySite[] {\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\tconst sites: CaddySite[] = [];\n\n\tfor (const resource of plan.resources) {\n\t\tif (!EDGE_KINDS[resource.kind]) continue;\n\n\t\tconst host = hostFor(resource, project);\n\n\t\tif (resource.kind === 'file-server') {\n\t\t\t// The bucket is a prefix on the origin, never part of the address: the\n\t\t\t// client asks for the key it stored.\n\t\t\tconst origin = resource.of ? byId.get(resource.of) : undefined;\n\t\t\tif (!origin) continue;\n\n\t\t\t// Its processors' patterns go to the dev server holding them, once\n\t\t\t// it has an address; everything else is still the bucket.\n\t\t\tconst address = processorAddresses[resource.id];\n\t\t\tconst port = address ? portOf(address) : undefined;\n\t\t\tsites.push({\n\t\t\t\thost,\n\t\t\t\tupstream: 'http://minio:9000',\n\t\t\t\trewrite: `/${origin.name}{uri}`,\n\t\t\t\t...(resource.processors?.length && port\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tprocessors: {\n\t\t\t\t\t\t\t\tprefixes: resource.processors,\n\t\t\t\t\t\t\t\tupstream: `http://${HOST_GATEWAY}:${port}`,\n\t\t\t\t\t\t\t\tunder: processorsDevRoute(resource.id),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// A surface or a site: a process on the host, at an address something\n\t\t// else assigned. Without one there is nothing to route to — which is the\n\t\t// ordinary state before `gkm dev` has decided where things listen.\n\t\tconst address = addresses[resource.id];\n\t\tif (!address) continue;\n\n\t\tconst port = portOf(address);\n\t\tif (!port) continue;\n\n\t\tconst upstream = `http://${HOST_GATEWAY}:${port}`;\n\t\tif (resource.subdomain === WILDCARD_SUBDOMAIN) {\n\t\t\tsites.push({\n\t\t\t\thost,\n\t\t\t\tupstream,\n\t\t\t\ttenants: tenantsOf(resource, host, addresses),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tsites.push({ host, upstream });\n\t}\n\n\treturn sites;\n}\n\n/**\n * What stands between a wildcard site and a host that is not a tenant.\n *\n * Caddy already prefers a named host to the `*`, so `api.shop.localhost`\n * reaches the API whatever the wildcard says. What it cannot know is the\n * labels nothing is running on: `www`, or an app this stage has not started.\n * Those are refused here, so no slug that a deploy would protect is ever\n * served locally either.\n *\n * The `hosts` route is asked through `forward_auth`, which is a deployed\n * edge's check in miniature: a `2xx` lets the request through, and any other\n * answer — the app's own `404` — is what the browser gets, so a mistyped\n * slug fails here and not first in production. Without an address for the\n * surface serving it there is nothing to ask, and every host is served.\n */\nfunction tenantsOf(\n\tresource: PlannedResource,\n\thost: string,\n\taddresses: Readonly<Record<string, string>>,\n): CaddySite['tenants'] {\n\tconst domain = host.slice(`${WILDCARD_SUBDOMAIN}.`.length);\n\tconst surface = resource.hosts\n\t\t? addresses[resource.hosts.surface]\n\t\t: undefined;\n\tconst port = surface ? portOf(surface) : undefined;\n\n\treturn {\n\t\tprotected: (resource.protectedSubdomains ?? []).map(\n\t\t\t(label) => `${label}.${domain}`,\n\t\t),\n\t\t...(resource.hosts && port\n\t\t\t? {\n\t\t\t\t\thosts: {\n\t\t\t\t\t\tupstream: `http://${HOST_GATEWAY}:${port}`,\n\t\t\t\t\t\turi: `${resource.hosts.path}?domain={host}`,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/** The port a local address answers on, defaulting by scheme. */\nfunction portOf(address: string): string | undefined {\n\ttry {\n\t\tconst { port, protocol } = new URL(address);\n\n\t\treturn port || (protocol === 'https:' ? '443' : '80');\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Where one file server answers, including the stage its name carries.\n *\n * The project is a label rather than a decoration: it is what keeps two\n * checkouts from answering on one address. Omitted when there is no project to\n * name, because an empty label makes `uploads..localhost` — a host nothing\n * resolves and no certificate can be issued for.\n */\nexport function hostFor(resource: PlannedResource, project: string): string {\n\t// The root site answers on the project's bare host, as it does on the base\n\t// domain deployed; everything else on a subdomain of it. A stage other than\n\t// the local one keeps a label — the stage — because one edge serves every\n\t// stage, and `gkm test` claiming the bare host would take it from `gkm dev`.\n\t// Only under a project: without one, the \"bare host\" is `localhost` itself,\n\t// which is nobody's domain to take.\n\tconst label =\n\t\tresource.root && project ? stageOf(resource) : labelOf(resource);\n\n\t// A wildcard site answers on every label under the stage's own domain —\n\t// `*.shop.localhost`, `*.test.shop.localhost` — so a stage is a label of\n\t// that domain rather than a suffix on the `*`.\n\tif (resource.subdomain === WILDCARD_SUBDOMAIN) {\n\t\treturn [WILDCARD_SUBDOMAIN, stageOf(resource), project, LOCAL_TLD]\n\t\t\t.filter(Boolean)\n\t\t\t.join('.');\n\t}\n\n\treturn [label, project, LOCAL_TLD].filter(Boolean).join('.');\n}\n\n/**\n * A resource's own label: its `subdomain` where it declared one — the label a\n * deploy uses too — with the stage it carries kept, so `gkm test` and `gkm dev`\n * still answer on different hosts.\n */\nfunction labelOf(resource: PlannedResource): string {\n\tif (!resource.subdomain) return resource.name;\n\tconst stage = stageOf(resource);\n\treturn stage ? `${resource.subdomain}-${stage}` : resource.subdomain;\n}\n\n/** The stage a resource's name carries, or nothing for the local stage's. */\nfunction stageOf(resource: PlannedResource): string | undefined {\n\tconst base = resource.id.toLowerCase();\n\treturn resource.name === base\n\t\t? undefined\n\t\t: resource.name.slice(base.length + 1);\n}\n\n/**\n * The static root config, which only ever imports.\n *\n * Written once and identical for every stage, because the *sites* are what\n * differ and they live in their own files. That split is not tidiness: one\n * container serves every stage — the same way one Postgres holds `orders` and\n * `orders_test` — so a single Caddyfile would mean `gkm test` deleting the\n * routes `gkm dev` is serving, and each command silently breaking the other.\n */\nexport function caddyfileRoot(): string {\n\treturn `${GENERATED}\n{\n\t# No ACME, no public DNS: the CA is local and so are the names.\n\tlocal_certs\n\tauto_https disable_redirects\n}\n\n# One file per stage, so two stages share this edge the way they already share\n# one Postgres and one MinIO.\nimport /etc/caddy/sites/*.caddy\n`;\n}\n\n/**\n * One stage's sites, as the file imported above.\n *\n * `rewrite` rather than a path prefix on the address: the bucket is the\n * origin's business, and the client asks for the key it stored.\n *\n * `header_up Host {upstream_hostport}` matters more than it looks. MinIO routes\n * and signs on the Host header, so forwarding the requested hostname would make\n * it look for a bucket named after the domain.\n */\nexport function toCaddyfile(sites: readonly CaddySite[]): string {\n\tif (sites.length === 0) {\n\t\treturn `${GENERATED}\n# No file server is declared in this stage, so it routes nothing.\n`;\n\t}\n\n\tconst blocks = sites.map(\n\t\t({ host, upstream, rewrite, processors, tenants }) => {\n\t\t\tconst proxy = `reverse_proxy ${upstream} {${\n\t\t\t\trewrite\n\t\t\t\t\t? `\n\t\trewrite ${rewrite}\n\t\t# MinIO routes and signs on the Host header, so forwarding the requested\n\t\t# hostname would make it look for a bucket named after the domain.\n\t\theader_up Host {upstream_hostport}`\n\t\t\t\t\t: `\n\t\t# The application reads whatever address was injected, so it has to see\n\t\t# the one a caller used — that is what makes a redirect, a cookie domain\n\t\t# and a generated link point back here rather than at the upstream.\n\t\theader_up Host {host}\n\t\theader_up X-Forwarded-Proto {scheme}`\n\t\t\t}\n\t}`;\n\n\t\t\treturn `\nhttps://${host} {\n\ttls internal\n\n\t# gkm's own header, which only a service of this stack may send: the auth\n\t# server rate-limits by the client address it carries.\n\trequest_header -${CLIENT_IP_HEADER}\n${\n\tprocessors\n\t\t? `\n\t# Its processors' patterns, to the dev server holding them — under the\n\t# route it mounts them on. Answered there, so the bucket below never is.\n\t@processors path ${processors.prefixes.map((prefix) => `${prefix}*`).join(' ')}\n\thandle @processors {\n\t\treverse_proxy ${processors.upstream} {\n\t\t\trewrite ${processors.under}{uri}\n\t\t\theader_up Host {host}\n\t\t}\n\t}\n`\n\t\t: ''\n}${tenants ? tenantBlock(tenants, proxy) : `\t${proxy}`}\n}`;\n\t\t},\n\t);\n\n\treturn `${GENERATED}${blocks.join('\\n')}\\n`;\n}\n\n/**\n * A wildcard site's routes: a protected host refused, every other host asked\n * about before it is proxied. `handle` blocks rather than bare directives,\n * because Caddy orders directives itself and would proxy before it refused.\n */\nfunction tenantBlock(\n\ttenants: NonNullable<CaddySite['tenants']>,\n\tproxy: string,\n): string {\n\tconst refused = tenants.protected.length\n\t\t? `\n\t# Labels an app answers on, or that the workspace protects: never a\n\t# tenant's, whether or not anything is running on them.\n\t@protected host ${tenants.protected.join(' ')}\n\thandle @protected {\n\t\trespond 404\n\t}\n`\n\t\t: '';\n\tconst check = tenants.hosts\n\t\t? `\n\t\t# Which hosts are tenants is the app's to say: its \\`hosts\\` route\n\t\t# answers 200 to serve this one, and anything else goes back as is.\n\t\tforward_auth ${tenants.hosts.upstream} {\n\t\t\turi ${tenants.hosts.uri}\n\t\t}\n`\n\t\t: '';\n\n\treturn `${refused}\n\thandle {${check}\n\t\t${proxy.replaceAll('\\n', '\\n\\t')}\n\t}`;\n}\n\nconst GENERATED = `# Generated by gkm from the construct manifest — do not edit.\n#\n# One host per declared file server, in front of the object store that holds its\n# objects. This is the shape a file server has deployed — a domain serving a\n# bucket — which MinIO alone cannot produce: its virtual-host mode reads the\n# leading label as the bucket name.\n#\n# Certificates come from Caddy's own CA. \"gkm dev\" and \"gkm test\" export its\n# root and point Node at it, so nothing has to be installed to use these URLs\n# from code; a browser needs the root trusted once.\n`;\n","/**\n * Which processes use a `Telemetry` node — read off the manifest's edges.\n *\n * A process uses telemetry when its own declaration names the node: a\n * surface's `telemetry`, a worker's. A surface's process runs its own\n * endpoints, so a worker's edge never counts for it.\n *\n * A site's edge is recorded and never followed here: a site is handed none of\n * the node's keys (see `PUBLIC.telemetry`).\n */\n\nimport {\n\ttype ConstructManifest,\n\tTELEMETRY_KEYS,\n\ttype TelemetryDeclaration,\n} from '@geekmidas/manifest';\nimport { appKey } from '../workspace/derive.js';\nimport type { StageTelemetryConfig } from '../workspace/types.js';\nimport { stageSampleRate } from './config.js';\n\n/** The `OTEL_*` keys a `Telemetry` node provides. */\nexport const TELEMETRY_ENV_KEYS: readonly string[] = TELEMETRY_KEYS;\n\n/** Whether `key` is one of the keys a `Telemetry` node provides. */\nexport function isTelemetryKey(key: string): boolean {\n\treturn TELEMETRY_ENV_KEYS.includes(key);\n}\n\n/** The node a declaration's `telemetry` edge names, when it names one. */\nfunction nodeOf(\n\tmanifest: ConstructManifest,\n\tid: string | undefined,\n): TelemetryDeclaration | undefined {\n\tif (!id) return undefined;\n\tconst node = manifest[id];\n\treturn node?.kind === 'telemetry' ? node : undefined;\n}\n\n/**\n * The `Telemetry` node the process for `id` — a surface, a worker, or a file\n * server's processor unit, by construct id — emits through, or undefined\n * when it has no edge to one.\n */\nexport function telemetryOf(\n\tmanifest: ConstructManifest,\n\tid: string,\n): TelemetryDeclaration | undefined {\n\tconst declaration = manifest[id];\n\tif (!declaration) return undefined;\n\n\tif (declaration.kind === 'worker' || declaration.kind === 'file-server') {\n\t\treturn nodeOf(manifest, declaration.telemetry);\n\t}\n\tif (declaration.kind !== 'rest-api' && declaration.kind !== 'websocket-api')\n\t\treturn undefined;\n\n\treturn nodeOf(manifest, declaration.telemetry);\n}\n\n/**\n * The `Telemetry` node the app `appName` emits through — its surface's, or\n * undefined for a site, an app without one, or one with no edge.\n */\nexport function appTelemetry(\n\tmanifest: ConstructManifest,\n\tappName: string,\n): TelemetryDeclaration | undefined {\n\tconst id = Object.entries(manifest).find(\n\t\t([id, d]) =>\n\t\t\t(d.kind === 'rest-api' || d.kind === 'websocket-api') &&\n\t\t\tappKey(id) === appName,\n\t)?.[0];\n\treturn id ? telemetryOf(manifest, id) : undefined;\n}\n\n/** Whether any process in the manifest emits through a `Telemetry` node. */\nexport function usesTelemetry(manifest: ConstructManifest): boolean {\n\treturn Object.entries(manifest).some(\n\t\t([id, d]) =>\n\t\t\t(d.kind === 'rest-api' ||\n\t\t\t\td.kind === 'websocket-api' ||\n\t\t\t\td.kind === 'worker' ||\n\t\t\t\td.kind === 'file-server') &&\n\t\t\ttelemetryOf(manifest, id) !== undefined,\n\t);\n}\n\n/**\n * One process's share of the telemetry keys a stage resolved: all of them,\n * named for the process, when it has an edge to the node — and none\n * otherwise.\n *\n * `env` is everything else the process is handed; its `OTEL_*` keys are\n * replaced, never merged, so a process without the edge cannot inherit them.\n */\nexport function scopeTelemetryEnv(\n\tenv: Readonly<Record<string, string>>,\n\toptions: {\n\t\t/** Whether the process has an edge to the node. */\n\t\tuses: boolean;\n\t\t/** The process's name — `OTEL_SERVICE_NAME`. */\n\t\tserviceName: string;\n\t\t/** What the stage resolved for the node, or nothing when it is off. */\n\t\ttelemetry?: Readonly<Record<string, string>>;\n\t},\n): Record<string, string> {\n\tconst scoped = Object.fromEntries(\n\t\tObject.entries(env).filter(([key]) => !isTelemetryKey(key)),\n\t);\n\tif (!options.uses || !options.telemetry) return scoped;\n\n\tconst values = Object.fromEntries(\n\t\tObject.entries(options.telemetry).filter(([key]) => isTelemetryKey(key)),\n\t);\n\tif (!values.OTEL_EXPORTER_OTLP_ENDPOINT) return scoped;\n\treturn {\n\t\t...scoped,\n\t\t...values,\n\t\tOTEL_SERVICE_NAME: options.serviceName,\n\t};\n}\n\n/** Whether the site `siteId` has an edge to a `Telemetry` node. */\nexport function siteUsesTelemetry(\n\tmanifest: ConstructManifest,\n\tsiteId: string,\n): boolean {\n\tconst site = manifest[siteId];\n\treturn (\n\t\tsite?.kind === 'site' && nodeOf(manifest, site.telemetry) !== undefined\n\t);\n}\n\n/**\n * Whether the client of the surface `surfaceId` propagates trace context:\n * when a site that calls it has an edge to a `Telemetry` node. One client\n * serves every site that calls the surface on the host, so one with the\n * edge turns it on; a site's image generates its own, from its own edge.\n */\nexport function surfaceClientTraced(\n\tmanifest: ConstructManifest,\n\tsurfaceId: string,\n): boolean {\n\treturn Object.entries(manifest).some(\n\t\t([id, d]) =>\n\t\t\td.kind === 'site' &&\n\t\t\tsiteUsesTelemetry(manifest, id) &&\n\t\t\td.dependencies.some((edge) => edge.target === surfaceId),\n\t);\n}\n\n/**\n * Whether the site app `appName`'s clients propagate trace context, and at\n * what rate: when the site has an edge to a `Telemetry` construct, at the\n * stage's sample rate — a public value, every trace locally — and not at all\n * for a stage that sends no telemetry.\n */\nexport function siteClientTelemetry(\n\tmanifest: ConstructManifest,\n\tappName: string,\n\tworkspace: {\n\t\tstages: { local: string };\n\t\tdeploy?: { telemetry?: Readonly<Record<string, StageTelemetryConfig>> };\n\t},\n\t/** The stage being built for — the local stage when absent. */\n\tstage?: string,\n): { sampleRate: number } | undefined {\n\tconst id = Object.entries(manifest).find(\n\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t)?.[0];\n\tif (!id || !siteUsesTelemetry(manifest, id)) return undefined;\n\tconst sampleRate = stageSampleRate(\n\t\tworkspace.deploy?.telemetry,\n\t\tstage ?? workspace.stages.local,\n\t\t!stage || stage === workspace.stages.local,\n\t);\n\treturn sampleRate === undefined ? undefined : { sampleRate };\n}\n","/**\n * The reconcile plan — what a manifest wants to exist, for one stage.\n *\n * Pure. Turning the plan into running containers and provisioned resources is\n * the applier's job; deciding *what* should exist is this, so the decisions can\n * be asserted as data rather than by starting Docker.\n *\n * One plan serves every stage. `gkm dev` reconciles `development` and `gkm test`\n * reconciles `test`; they differ only in what the resources are called, never in\n * what infrastructure exists. Roles are cluster-scoped in Postgres while grants\n * are per-object, so one container and one role pair serve both.\n */\n\nimport {\n\tbucketExpiry,\n\ttype ConstructManifest,\n\ttype Declaration,\n\ttype DeclarationKind,\n\tdependentsOf,\n\tisWildcardSite,\n\ttype PostgresVersion,\n\tprovidedKeyFor,\n\tpublicEnvFor,\n\ttype SecretFormat,\n\ttype SiteHosts,\n\tWILDCARD_SUBDOMAIN,\n} from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport { usesTelemetry } from '../telemetry/edges.js';\nimport {\n\ttype CacheBackend,\n\tDEFAULT_CACHE,\n\ttype EventsBackend,\n\tholdsEveryCache,\n} from '../types';\nimport { appKey } from '../workspace/derive.js';\nimport { rootSite } from '../workspace/rootSite.js';\nimport { protectedSubdomains } from '../workspace/subdomains.js';\nimport { EDGE_KINDS } from './caddyfile';\nimport { fakeKey, type PlannedFake } from './containers';\nimport type { LocalFake } from './fakes';\n\n/**\n * Which container serves a kind.\n *\n * Derived kinds map to the same container as their parent — a schema tenant\n * lives in its parent's Postgres — so the set is deduplicated rather than\n * counted.\n */\nconst CONTAINERS: Partial<Record<DeclarationKind, string>> = {\n\tdatabase: 'postgres',\n\t'database-reader': 'postgres',\n\t'database-schema': 'postgres',\n\tobjects: 'minio',\n\t// The server is not the bucket. Its own container is the local edge, which\n\t// is what lets it answer on a *host* rather than on a path under MinIO —\n\t// the shape it has deployed, and the one MinIO's virtual-host mode cannot\n\t// produce because that mode reads the leading label as the bucket name.\n\t//\n\t// MinIO still runs: it is implied by the bucket this server is declared\n\t// over, which is a parent it always has.\n\t'file-server': 'caddy',\n\t// Every mail backend speaks SMTP, so locally there is one answer whichever\n\t// one is selected — which is the same reason the declaration has no\n\t// `provider` field.\n\temail: 'mailpit',\n\t// Locally mail is received the way it is sent: into Mailpit, whose\n\t// webhook hands `gkm dev` each message an inbox receives at.\n\tinbox: 'mailpit',\n\t// A WebSocket surface answers on its app's port like a REST one, but its\n\t// publisher is Redis pub/sub: an endpoint in another process reaches a\n\t// socket through it, so it runs wherever the surface is declared.\n\t'websocket-api': 'redis',\n};\n\n/**\n * The container a cache backend needs locally.\n *\n * Each one matches the protocol its deployed form speaks, which is the property\n * worth having: a cache that behaves differently in the two places is worse than\n * a slower one.\n *\n * `db` is deliberately absent, the same way `pgboss` is absent from\n * `EVENT_CONTAINERS`: the cache is a table in a database the manifest already\n * declares, so mapping it here would start a container for a project that needs\n * none.\n */\nconst CACHE_CONTAINERS: Partial<Record<CacheBackend, string>> = {\n\t// The proxy, not the Redis behind it: the client speaks HTTP with a token\n\t// wherever it runs, which is what makes dev and prod the same client.\n\tupstash: 'redis-http',\n\t// The wire protocol, which is what ElastiCache offers — so dev speaks it too.\n\telasticache: 'redis',\n\t// The stack's own Redis: the same container, on the stack's network.\n\tredis: 'redis',\n};\n\n/**\n * Kinds that resolve a value without anything running.\n *\n * A secret is the case: it has no address, so there is nothing to start and\n * nothing to connect to — but it still appears in the plan, because the target\n * still has to resolve it.\n */\nconst CONTAINERLESS: Partial<Record<DeclarationKind, true>> = {\n\tsecret: true,\n\t// A credential has no address either — and unlike a secret it has no value\n\t// this target can derive, because it was issued by somebody else.\n\tcredential: true,\n\t// An encryption key is a value too: a keyring the target derives, the way\n\t// it derives a secret.\n\tencryption: true,\n\t// A surface answers on the app's own port. It is the first kind whose\n\t// address belongs to something gkm starts rather than something Docker does.\n\t'rest-api': true,\n\t// A site is the second: it is served by its own framework's dev server, and\n\t// what the target resolves for it is only where that server answers.\n\tsite: true,\n\t// A mobile app resolves its scheme, which nothing has to be running for.\n\t'mobile-app': true,\n\t// An external API is answered by its fake. A module fake runs in no\n\t// container — gkm serves it — and an image's container is added per API,\n\t// since no kind-wide table can name it.\n\t'external-api': true,\n\t// Telemetry is collected by OpenObserve, which runs only where a process\n\t// uses the node — see `planFor`.\n\ttelemetry: true,\n};\n\n/** The container that collects telemetry locally, and serves its UI. */\nexport const TELEMETRY_CONTAINER = 'openobserve';\n\n/**\n * Containers that cannot run alone.\n *\n * The one case is the cache: `serverless-redis-http` is a proxy and needs the\n * Redis it proxies. Kept here rather than in the compose definition so the plan\n * -- which is what decides what must be running -- still names everything.\n */\nconst REQUIRES: Readonly<Record<string, readonly string[]>> = {\n\t'redis-http': ['redis'],\n};\n\n/**\n * The role each kind's one key plays, where it is not a URL.\n *\n * The twin of `ProvidesByKind` in `@geekmidas/manifest`: that is what a\n * construct declares, this is what the local target resolves, and both derive\n * the key from the same `provideKey` so they cannot disagree.\n */\nconst ROLES: Partial<Record<DeclarationKind, string>> = {\n\tqueue: 'publisherConnectionString',\n\ttopic: 'publisherConnectionString',\n\tcredential: 'credentials',\n\t'mobile-app': 'scheme',\n};\n\n/** The kinds whose container is the events backend's rather than their own. */\nconst EVENT_KINDS: Partial<Record<DeclarationKind, true>> = {\n\tqueue: true,\n\ttopic: true,\n};\n\n/**\n * Which kinds provision something *inside* their container.\n *\n * A database creates a database, a bucket creates a bucket; mail creates\n * nothing — Mailpit accepts whatever is sent to it and has no per-stage object\n * to name. Both still appear in the plan, because both still resolve a URL; the\n * flag is the difference between \"must be running\" and \"must be created\".\n */\nconst PROVISIONS: Partial<Record<DeclarationKind, true>> = {\n\tdatabase: true,\n\t'database-reader': true,\n\t'database-schema': true,\n\tobjects: true,\n\t// Only a cache that lives in a database creates anything — its table. The\n\t// other backends have nothing to create inside the container they use.\n\tcache: true,\n\t// The open patterns become a bucket policy on the origin — real\n\t// enforcement locally, from the same declaration the CDN behaviour comes\n\t// from deployed.\n\t'file-server': true,\n};\n// Queues and topics are absent deliberately: pg-boss creates its own schema and\n// tables on first connect, and a RabbitMQ exchange is declared by the client\n// that binds to it. Both still appear in the plan, because both still resolve a\n// connection string.\n\n/**\n * The container each events backend needs, where it needs one of its own.\n *\n * `pgboss` is deliberately absent rather than mapped to `postgres`: it is a\n * schema tenant in a database the manifest already declares, so mapping it here\n * would start a Postgres for a project that declared no database at all.\n *\n * This one comes from config rather than from a declaration because there are\n * no `topic` or `queue` kinds yet. When they land the mapping moves to\n * {@link CONTAINERS} keyed by kind, and this constant goes with them.\n */\nconst EVENT_CONTAINERS: Partial<Record<EventsBackend, string>> = {\n\tsns: 'localstack',\n\trabbitmq: 'rabbitmq',\n};\n\n/** The backend a project gets when it declares queues or topics and says nothing. */\nexport const DEFAULT_EVENTS: EventsBackend = 'pgboss';\n\n/**\n * How a resource of each kind separates its stage suffix.\n *\n * Postgres identifiers are snake_case and a hyphen would need quoting\n * everywhere; buckets and queues are kebab and disallow underscores in some\n * providers. The suffix is the same word either way.\n */\nconst SEPARATORS: Partial<Record<DeclarationKind, string>> = {\n\tdatabase: '_',\n\t'database-reader': '_',\n\t'database-schema': '_',\n\tobjects: '-',\n};\n\n/** One thing that must exist, and what it is called in this stage. */\nexport interface PlannedResource {\n\t/** The construct's canonical id, e.g. `Orders`. */\n\tid: string;\n\tkind: DeclarationKind;\n\t/** The container that serves it, e.g. `postgres`. Absent for a secret. */\n\tcontainer?: string;\n\t/** The stage-scoped name, e.g. `orders_test`. */\n\tname: string;\n\t/**\n\t * An inbox's addressing and the topic it declared — what the receiver\n\t * routes a message by, and where it announces it.\n\t */\n\tinbox?: {\n\t\taddresses: readonly string[];\n\t\tsubdomains: boolean;\n\t\ttopic: string;\n\t};\n\t/** The env key it resolves onto anything depending on it. */\n\tenvKey: string;\n\t/** The parent it derives from, for kinds that provision nothing themselves. */\n\tof?: string;\n\t/**\n\t * Whether anything has to be created inside the container for this.\n\t *\n\t * False for mail: Mailpit takes whatever is sent to it. The applier skips\n\t * these; the env writer still resolves their URL.\n\t */\n\tprovisions: boolean;\n\t/**\n\t * The site the base domain points at, by the rule a deploy uses\n\t * (`rootSite`) — so locally it answers on the project's bare host, the\n\t * shape production serves, rather than a subdomain of it.\n\t */\n\troot?: true;\n\t/**\n\t * The label a surface or site answers on, its declaration's `subdomain` —\n\t * the same one a deploy puts under the stage's domain.\n\t */\n\tsubdomain?: string;\n\t/** The schema a tenant pins on its roles' `search_path`. */\n\tschema?: string;\n\t/** For a secret: the format it is derived in, as a deploy generates it. */\n\tformat?: SecretFormat;\n\t/** For a cache in a database: the table entries are kept in. */\n\ttable?: string;\n\t/**\n\t * Whether to provision the owner/runtime role split.\n\t *\n\t * `false` is the documented downgrade — both URLs fall back to the cluster's\n\t * master credential — and it is a choice someone made rather than a default\n\t * they got, which is why it is carried through rather than inferred.\n\t */\n\troles?: boolean;\n\t/**\n\t * For a database: the engine major version to run.\n\t *\n\t * Carried like `schema` and `roles` — read off the declaration so the\n\t * container tag and the deployed engine come from one statement. They used\n\t * to come from two, and had drifted a major apart with nothing recording it.\n\t */\n\tversion?: PostgresVersion;\n\t/** For a database: the image it named in place of `postgres:<version>`. */\n\timage?: string;\n\t/**\n\t * For a database: the extensions to create in it, as the master, before\n\t * any migration. In this database alone.\n\t */\n\textensions?: readonly string[];\n\t/**\n\t * For a file server: the paths it serves without a signature.\n\t *\n\t * Carried into the plan because the local target enforces them for real — a\n\t * bucket policy with prefix resources, from the same declaration the CDN\n\t * behaviour comes from deployed. An open path that is open locally and shut\n\t * in production is the bug this avoids.\n\t */\n\topen?: readonly string[];\n\t/**\n\t * For a file server: the literal prefixes its processors answer — `/i/` —\n\t * which the local edge sends to the dev server holding them.\n\t */\n\tprocessors?: readonly string[];\n\t/**\n\t * For a bucket: days kept under each prefix before it deletes them.\n\t *\n\t * Carried for the same reason as `open`: the local MinIO expires them too,\n\t * so a prefix that empties itself in production empties itself here.\n\t */\n\texpire?: Readonly<Record<string, number>>;\n\t/**\n\t * For an external API: the port key its fake answers on, and the\n\t * credentials it accepts — what a local stage is handed in place of the\n\t * provider and the stage's own.\n\t */\n\tfake?: { key: string; credentials: string };\n\t/**\n\t * For a credential: its fake's value, as `<ID>_CREDENTIALS` holds it — what\n\t * a plan made with fakes hands the stage in place of its own.\n\t */\n\tfakeCredentials?: string;\n\t/**\n\t * For an external API with no fake in this plan: the URL it is called at,\n\t * as declared — one string, or one per stage name.\n\t */\n\turl?: string | Readonly<Record<string, string>>;\n\t/**\n\t * For a site: the keys its bundle needs, mapped to the key each value comes\n\t * from — `{ VITE_API_URL: 'API_URL' }`.\n\t *\n\t * One neutral name from the construct and one serialisation per framework.\n\t * The prefix is the whole of what varies, which is why the mapping is a\n\t * rename rather than a second derivation: `API_URL` is resolved once, by the\n\t * same code that resolves it for the server, and a site simply reads it\n\t * under the name its bundler will inline.\n\t */\n\tpublicEnv?: Record<string, string>;\n\t/** For a mobile app: the scheme it gave, when not the project's name. */\n\tscheme?: string;\n\t/**\n\t * The ids that depend on this one — the graph read backwards.\n\t *\n\t * Carried on surfaces, where it is the whole answer to \"who may call this\":\n\t * CORS origins, trusted origins, and the cookie domain are three readings of\n\t * this one list. And on buckets, where it says whether a surface a mobile\n\t * app calls hands out their links. Resolved to addresses by the target, because the manifest\n\t * knows which constructs call which and only the target knows where any of\n\t * them answer.\n\t */\n\tcallers?: string[];\n\t/**\n\t * For a wildcard site: the labels no tenant may take — every app's own\n\t * and the workspace's `protectedSubdomains` — which it resolves as\n\t * `<ID>_PROTECTED_SUBDOMAINS`, and which an edge never sends to it.\n\t */\n\tprotectedSubdomains?: string[];\n\t/**\n\t * For a wildcard site: the route its edge asks before serving a host,\n\t * `GET <path>?domain=<host>` on `surface` — the declaration's `hosts`.\n\t */\n\thosts?: SiteHosts;\n}\n\nexport interface Plan {\n\tstage: string;\n\t/**\n\t * The events backend this plan was built for.\n\t *\n\t * Carried on the plan rather than passed alongside it, because everything\n\t * downstream that composes a connection string needs it and reading it off\n\t * the plan is what keeps the two from disagreeing.\n\t */\n\tevents: EventsBackend;\n\t/** Where the cache lives, for everything downstream that composes its URL. */\n\tcache: CacheBackend;\n\t/**\n\t * A worker is declared and the broker is pg-boss, so the broker is needed\n\t * whether or not a queue or topic is.\n\t *\n\t * On a server a worker's crons are scheduled through the events broker —\n\t * the app's one pg-boss. Crons are not in the manifest (a worker does not\n\t * list them), so the worker is the signal. pg-boss is a schema in the\n\t * declared database, so this starts nothing and provisions nothing; it only\n\t * means the broker's connection strings are resolved.\n\t */\n\tworkerBroker?: true;\n\t/** Containers to start, deduplicated. */\n\tcontainers: string[];\n\t/**\n\t * Each external API's fake, by its port key — `<id>-fake`. An image fake's\n\t * key is also in `containers`; a module fake's is a port gkm serves on.\n\t */\n\tfakes?: Record<string, PlannedFake>;\n\t/**\n\t * Everything the stage resolves a URL for, parents before children.\n\t *\n\t * Not all of it is provisioned — see `PlannedResource.provisions`.\n\t */\n\tresources: PlannedResource[];\n}\n\n/** What the plan needs that the manifest cannot tell it. */\nexport interface PlanOptions {\n\t/**\n\t * The project's local stage (`stages.local`), whose resources carry no\n\t * suffix. Absent, every stage is suffixed — which is right for a deploy,\n\t * since a deployed stage is never the local one.\n\t */\n\tlocalStage?: string;\n\t/**\n\t * Whether the local edge fronts the addresses this plan resolves.\n\t *\n\t * On by default, because deployed every surface, site and file server has a\n\t * real hostname and a certificate, and the point of the local target is to\n\t * be the same shape rather than a near-enough one. Off falls back to\n\t * `http://localhost:<port>`.\n\t *\n\t * Config rather than declaration for the same reason `cache` is: the\n\t * application reads whichever address was injected and composes none, so it\n\t * cannot tell the difference.\n\t */\n\tedge?: boolean;\n\t/**\n\t * Where a declared cache lives, which decides both the container it needs\n\t * locally and the protocol its URL speaks.\n\t *\n\t * Config rather than declaration, because the same application code caches\n\t * into any of them — the same reason `events` is config.\n\t */\n\tcache?: CacheBackend;\n\t/**\n\t * The events backend, which selects a container of its own for everything\n\t * except pg-boss.\n\t *\n\t * Config rather than declaration only until `topic` and `queue` are kinds —\n\t * see {@link EVENT_CONTAINERS}.\n\t */\n\tevents?: EventsBackend;\n\t/**\n\t * Containers no construct implies — the escape hatch, and the whole of what\n\t * the workspace `services:` block becomes.\n\t *\n\t * A list of exceptions rather than a list you maintain: everything a\n\t * construct implies is already in the plan before this is read.\n\t */\n\textraContainers?: readonly string[];\n\t/**\n\t * Each external API's fake, by id — read from `test/fakes` by `readFakes`,\n\t * since the declaration never names one. An external API without one\n\t * resolves no URL.\n\t */\n\tfakes?: Readonly<Record<string, LocalFake>>;\n\t/**\n\t * Each credential's fake value, by id — read from `test/fakes` by\n\t * `readCredentialFakes`, for a plan made with fakes (`gkm test`,\n\t * `gkm dev --fake`). A credential without one is the stage's own.\n\t */\n\tcredentialFakes?: Readonly<Record<string, string>>;\n\t/**\n\t * The workspace's `protectedSubdomains`: the names, beyond every app's\n\t * own, that a wildcard site's tenants may never take.\n\t */\n\tprotectedSubdomains?: readonly string[];\n}\n\n/**\n * The stage-scoped name for a resource.\n *\n * The local stage carries no suffix, so `gkm dev` keeps using `orders` and a\n * developer's psql history, saved connections, and muscle memory survive a\n * change of stage name. Every other stage is suffixed.\n */\nexport function resourceName(\n\tid: string,\n\tkind: DeclarationKind,\n\tstage: string,\n\t/** The project's local stage, whose names are unsuffixed. */\n\tlocalStage?: string,\n): string {\n\tconst base = id.toLowerCase();\n\tif (stage === localStage) return base;\n\n\treturn `${base}${SEPARATORS[kind] ?? '-'}${stage}`;\n}\n\n/**\n * The container a kind needs, or `undefined` if it needs none.\n *\n * Queues and topics have no container of their own — they live in whichever\n * broker the project selected, which is why the backend is an argument here\n * rather than a second pass that adds containers after the fact.\n */\nexport function containerFor(\n\tkind: DeclarationKind,\n\tevents: EventsBackend = DEFAULT_EVENTS,\n\t// The target-aware choice is made upstream, in `reconcile/workspace.ts`,\n\t// where the workspace knows where it deploys. This fires only for a caller\n\t// that passed nothing at all.\n\tcache: CacheBackend = DEFAULT_CACHE.aws,\n\t/** Whether the declaration named a parent — see the `cache` branch. */\n\tderived = false,\n\t/** Whether the local edge exists — see the `file-server` branch. */\n\tedge = true,\n): string | undefined {\n\tif (EVENT_KINDS[kind]) {\n\t\t// pg-boss is deliberately absent from EVENT_CONTAINERS: it is a schema\n\t\t// tenant in a database the manifest already declares, so its container is\n\t\t// that database's.\n\t\treturn EVENT_CONTAINERS[events] ?? CONTAINERS.database;\n\t}\n\n\t// A file server answers on the edge, which is what gives it a host of its\n\t// own. With the edge off it falls back to the object store that holds its\n\t// objects — a path under MinIO, which works and is not the deployed shape.\n\tif (kind === 'file-server') return edge ? 'caddy' : CONTAINERS.objects;\n\n\t// The same shape: a cache in the database lives in the database's container.\n\tif (kind === 'cache') {\n\t\t// A cache that *named* a database is in it whatever the backend config\n\t\t// says — the declaration is the stronger statement, and config choosing\n\t\t// otherwise would move a cache the app said lives here — except where\n\t\t// the backend holds every cache (the stack's own Redis).\n\t\tif (derived && !holdsEveryCache(cache)) return CONTAINERS.database;\n\n\t\treturn CACHE_CONTAINERS[cache] ?? CONTAINERS.database;\n\t}\n\n\treturn CONTAINERS[kind];\n}\n\n/**\n * Build the plan for a manifest and stage.\n *\n * `order` is the caller's provisioning order — parents before children — which\n * `provisionOrder` produces from the manifest. Passing it in keeps this\n * function free of the traversal and makes the ordering assertable on its own.\n */\nexport function planFor(\n\tmanifest: ConstructManifest,\n\tstage: string,\n\torder: readonly string[],\n\toptions: PlanOptions = {},\n): Plan {\n\tconst containers = new Set<string>();\n\tconst resources: PlannedResource[] = [];\n\tconst fakes: Record<string, PlannedFake> = {};\n\n\tconst events = options.events ?? DEFAULT_EVENTS;\n\tconst cache = options.cache ?? DEFAULT_CACHE.aws;\n\n\tfor (const id of order) {\n\t\tconst declaration: Declaration | undefined = manifest[id];\n\t\tif (!declaration) continue;\n\n\t\tconst local =\n\t\t\tdeclaration.kind === 'external-api' ? options.fakes?.[id] : undefined;\n\t\tconst fake = local && { key: fakeKey(id), ...local };\n\t\tif (fake) {\n\t\t\tfakes[fake.key] = {\n\t\t\t\tid,\n\t\t\t\t...(fake.image ? { image: fake.image, port: fake.port } : {}),\n\t\t\t};\n\t\t}\n\n\t\t// A cache whose backend holds every cache is detached from the database\n\t\t// it was declared from: it has no `of` and no table, so nothing\n\t\t// downstream composes a database URL for it or creates its table.\n\t\tconst detached = declaration.kind === 'cache' && holdsEveryCache(cache);\n\n\t\tconst container = fake?.image\n\t\t\t? fake.key\n\t\t\t: declaration.kind === 'telemetry'\n\t\t\t\t? usesTelemetry(manifest)\n\t\t\t\t\t? TELEMETRY_CONTAINER\n\t\t\t\t\t: undefined\n\t\t\t\t: containerFor(\n\t\t\t\t\t\tdeclaration.kind,\n\t\t\t\t\t\tevents,\n\t\t\t\t\t\tcache,\n\t\t\t\t\t\t'of' in declaration && typeof declaration.of === 'string',\n\t\t\t\t\t\toptions.edge !== false,\n\t\t\t\t\t);\n\t\tif (!container && !CONTAINERLESS[declaration.kind]) continue;\n\n\t\tif (container) {\n\t\t\tcontainers.add(container);\n\t\t\tfor (const required of REQUIRES[container] ?? [])\n\t\t\t\tcontainers.add(required);\n\t\t}\n\n\t\tresources.push({\n\t\t\tid,\n\t\t\tkind: declaration.kind,\n\t\t\t...(container ? { container } : {}),\n\t\t\tname: resourceName(id, declaration.kind, stage, options.localStage),\n\t\t\t// Through the shared derivation: a secret's name *is* its key, and\n\t\t\t// this target and the deploy target must not answer that separately.\n\t\t\tenvKey: providedKeyFor(\n\t\t\t\tid,\n\t\t\t\tdeclaration.kind,\n\t\t\t\tROLES[declaration.kind] ?? 'url',\n\t\t\t),\n\t\t\tprovisions: PROVISIONS[declaration.kind] === true,\n\t\t\t// For surfaces and buckets. A surface's callers are who may call it;\n\t\t\t// a bucket's say whether its links can end up on a phone (`envFor`).\n\t\t\t// Every other kind is reached by a URL that says nothing about who\n\t\t\t// holds it, so a caller list would be a fact with no reader.\n\t\t\t...(declaration.kind === 'rest-api' ||\n\t\t\tdeclaration.kind === 'websocket-api' ||\n\t\t\tdeclaration.kind === 'objects' ||\n\t\t\tdeclaration.kind === 'file-server'\n\t\t\t\t? { callers: dependentsOf(manifest, id) }\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'site'\n\t\t\t\t? { publicEnv: publicEnvFor(declaration, manifest) }\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'mobile-app'\n\t\t\t\t? {\n\t\t\t\t\t\tpublicEnv: publicEnvFor(declaration, manifest),\n\t\t\t\t\t\t...(declaration.scheme ? { scheme: declaration.scheme } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'file-server' && declaration.open?.length\n\t\t\t\t? { open: declaration.open }\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'file-server' && declaration.processors?.length\n\t\t\t\t? {\n\t\t\t\t\t\tprocessors: [\n\t\t\t\t\t\t\t...new Set(declaration.processors.map((p) => p.prefix)),\n\t\t\t\t\t\t].sort(),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'inbox'\n\t\t\t\t? {\n\t\t\t\t\t\tinbox: {\n\t\t\t\t\t\t\taddresses: declaration.addresses,\n\t\t\t\t\t\t\tsubdomains: declaration.subdomains === true,\n\t\t\t\t\t\t\ttopic: declaration.topic,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'objects' && bucketExpiry(manifest, id)\n\t\t\t\t? { expire: bucketExpiry(manifest, id) }\n\t\t\t\t: {}),\n\t\t\t...((declaration.kind === 'rest-api' ||\n\t\t\t\tdeclaration.kind === 'websocket-api' ||\n\t\t\t\tdeclaration.kind === 'site') &&\n\t\t\tdeclaration.subdomain\n\t\t\t\t? { subdomain: declaration.subdomain }\n\t\t\t\t: {}),\n\t\t\t...(isWildcardSite(declaration)\n\t\t\t\t? {\n\t\t\t\t\t\tprotectedSubdomains: protectedSubdomains(\n\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\toptions.protectedSubdomains,\n\t\t\t\t\t\t),\n\t\t\t\t\t\t...(declaration.hosts ? { hosts: declaration.hosts } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(fake\n\t\t\t\t? { fake: { key: fake.key, credentials: fake.credentials } }\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'external-api' && !fake\n\t\t\t\t? { url: declaration.url }\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'credential' &&\n\t\t\toptions.credentialFakes?.[id] !== undefined\n\t\t\t\t? { fakeCredentials: options.credentialFakes[id] }\n\t\t\t\t: {}),\n\t\t\t...(declaration.kind === 'secret' &&\n\t\t\t(declaration.length !== undefined || declaration.symbols !== undefined)\n\t\t\t\t? {\n\t\t\t\t\t\tformat: {\n\t\t\t\t\t\t\t...(declaration.length !== undefined\n\t\t\t\t\t\t\t\t? { length: declaration.length }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t...(declaration.symbols !== undefined\n\t\t\t\t\t\t\t\t? { symbols: declaration.symbols }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...('of' in declaration && !detached ? { of: declaration.of } : {}),\n\t\t\t...('schema' in declaration && declaration.schema\n\t\t\t\t? { schema: declaration.schema }\n\t\t\t\t: {}),\n\t\t\t...('version' in declaration && declaration.version\n\t\t\t\t? { version: declaration.version }\n\t\t\t\t: {}),\n\t\t\t...('image' in declaration && declaration.image\n\t\t\t\t? { image: declaration.image }\n\t\t\t\t: {}),\n\t\t\t...('extensions' in declaration && declaration.extensions?.length\n\t\t\t\t? { extensions: declaration.extensions }\n\t\t\t\t: {}),\n\t\t\t...('roles' in declaration && declaration.roles === false\n\t\t\t\t? { roles: false }\n\t\t\t\t: {}),\n\t\t\t...('table' in declaration && declaration.table && !detached\n\t\t\t\t? { table: declaration.table }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\n\t// The edge serves anything that owns a public address — a surface and a site\n\t// as much as a file server. Added here rather than in `containerFor` because\n\t// those two are containerless in every other sense: nothing runs them in\n\t// Docker, and what the edge does is put a hostname and a certificate in\n\t// front of a process on the host.\n\t//\n\t// `edge: false` opts out, and then every local address is\n\t// `http://localhost:<port>` as before. The application cannot tell: it reads\n\t// whichever address was injected and composes none.\n\tif (\n\t\toptions.edge !== false &&\n\t\tresources.some((r) => EDGE_KINDS[r.kind] === true)\n\t) {\n\t\tcontainers.add('caddy');\n\t}\n\n\tfor (const extra of options.extraContainers ?? []) containers.add(extra);\n\n\t// pg-boss lives in a declared database. Without one there is nothing for it\n\t// to live in, and starting a Postgres to hold only a queue would be the\n\t// container this design refuses to invent.\n\tif (\n\t\tevents === 'pgboss' &&\n\t\tresources.some((r) => EVENT_KINDS[r.kind]) &&\n\t\t!resources.some((r) => r.kind === 'database')\n\t) {\n\t\tthrow new PgBossNeedsDatabase(\n\t\t\tresources.filter((r) => EVENT_KINDS[r.kind]).map((r) => r.id),\n\t\t);\n\t}\n\n\t// A cache the deploy target placed in a database becomes an *edge*, here,\n\t// once.\n\t//\n\t// A server target's `'db'` cache names something that exists in this graph, which\n\t// makes it different in kind from `upstash` or `elasticache`: those name a\n\t// backend nothing declares, while this one names a database sitting right\n\t// there. So it is resolved to `of` — the same field `database.cache()` sets\n\t// — and every reader downstream follows an edge instead of re-deriving the\n\t// answer from a string.\n\t//\n\t// It also turns a silent guess into an error. \"The declared database\" is\n\t// unambiguous with one and arbitrary with two, and picking whichever came\n\t// first would put the cache in a database nobody chose.\n\t//\n\t// A cache that named its parent is untouched: the declaration is the\n\t// stronger statement, and its parent is checked by `assertDerivations`,\n\t// which names the database that is missing rather than reporting that some\n\t// database is.\n\tif (cache === 'db') {\n\t\tconst placeless = resources.filter((r) => r.kind === 'cache' && !r.of);\n\n\t\tif (placeless.length > 0) {\n\t\t\tconst databases = resources.filter((r) => r.kind === 'database');\n\t\t\tconst [only] = databases;\n\n\t\t\t// Starting a Postgres to hold only a cache would be the container this\n\t\t\t// design refuses to invent.\n\t\t\tif (!only) {\n\t\t\t\tthrow new CacheNeedsDatabase(\n\t\t\t\t\tresources.filter((r) => r.kind === 'cache').map((r) => r.id),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (databases.length > 1) {\n\t\t\t\tthrow new CacheIsAmbiguous(\n\t\t\t\t\tplaceless.map((r) => r.id),\n\t\t\t\t\tdatabases.map((r) => r.id),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tfor (const resource of placeless) resource.of = only.id;\n\t\t}\n\t}\n\n\t// The site the base domain points at: the same answer a deploy gives, so the\n\t// local edge serves it on the bare host.\n\t// Never a wildcard site, which answers on every subdomain instead.\n\tconst sites = resources.filter(\n\t\t(r) => r.kind === 'site' && r.subdomain !== WILDCARD_SUBDOMAIN,\n\t);\n\tconst root = rootSite(\n\t\tsites.map((r) => {\n\t\t\tconst declared = manifest[r.id];\n\t\t\treturn {\n\t\t\t\tname: appKey(r.id),\n\t\t\t\t...(declared?.kind === 'site' && declared.root ? { root: true } : {}),\n\t\t\t};\n\t\t}),\n\t);\n\tfor (const site of sites) {\n\t\tif (appKey(site.id) === root) site.root = true;\n\t}\n\n\tconst workerBroker =\n\t\tevents === 'pgboss' &&\n\t\tObject.values(manifest).some((d) => d?.kind === 'worker') &&\n\t\tresources.some((r) => r.kind === 'database');\n\n\treturn {\n\t\tstage,\n\t\tevents,\n\t\tcache,\n\t\tcontainers: [...containers],\n\t\tresources,\n\t\t...(Object.keys(fakes).length ? { fakes } : {}),\n\t\t...(workerBroker ? { workerBroker: true as const } : {}),\n\t};\n}\n\n/**\n * Queues or topics were declared with pg-boss and no database to hold them.\n *\n * Not a reconcile failure but a manifest one: the fix is a line of application\n * code either way — declare a database, or select a backend that brings its own\n * broker.\n */\nexport class CacheNeedsDatabase extends GkmError {\n\tconstructor(readonly ids: readonly string[]) {\n\t\tsuper(\n\t\t\t`A cache backed by the database needs a declared database, and none ` +\n\t\t\t\t`was declared, and on this deploy target that is where a cache lives. ` +\n\t\t\t\t`Declare one. Caches affected: ${ids.join(', ')}.`,\n\t\t);\n\t\tthis.name = 'CacheNeedsDatabase';\n\t}\n}\n\n/**\n * A `'db'` cache — a server target's default — in an app that declares more\n * than one database.\n *\n * The target says *a* database and the graph offers several, so there is no\n * answer to give — and the wrong kind of failure would be to pick one, since a\n * cache silently landing in the wrong database is a bug that surfaces as\n * missing rows much later. The fix is a stronger statement in application code:\n * `orders.cache('Sessions')` names the database, which is a fact about the\n * application rather than a deployment choice.\n */\nexport class CacheIsAmbiguous extends GkmError {\n\tconstructor(\n\t\treadonly ids: readonly string[],\n\t\treadonly databases: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`A cache backed by the database needs to know which one, and this app ` +\n\t\t\t\t`declares ${databases.length}: ${databases.join(', ')}. Declare the ` +\n\t\t\t\t`cache from its database — e.g. ${databases[0]}.cache('Sessions') — ` +\n\t\t\t\t`rather than as a bare new Cache(). Caches affected: ${ids.join(', ')}.`,\n\t\t);\n\t\tthis.name = 'CacheIsAmbiguous';\n\t}\n}\n\nexport class PgBossNeedsDatabase extends GkmError {\n\tconstructor(readonly ids: readonly string[]) {\n\t\tsuper(\n\t\t\t`pg-boss keeps its queues in a declared database, and none was declared. ` +\n\t\t\t\t`Declare one: on this deploy target, events are carried by pg-boss. ` +\n\t\t\t\t`Queues and topics affected: ${ids.join(', ')}.`,\n\t\t);\n\t\tthis.name = 'PgBossNeedsDatabase';\n\t}\n}\n","/**\n * The URLs a reconciled stage injects.\n *\n * One `<NAME>_URL` per construct, and the protocol picks the driver. This is the\n * seam between the target that writes a URL and the client that parses it, so\n * every component of it is read off the resource — never inherited from ambient\n * environment. A bucket can live in a different region than the function reading\n * it, and `AWS_REGION` in a Lambda is the *function's* region, so a URL that\n * omits `?region=` breaks cross-region silently at runtime.\n *\n * Locally that self-containment is what lets the port be whatever was free: the\n * app reads `ORDERS_URL` and never sees a host or a port.\n */\n\nimport { createHash } from 'node:crypto';\nimport { formatKeyring } from '@geekmidas/constructs/encryption';\nimport { ownerRole, readerRole } from '@geekmidas/db/pg/roles';\nimport * as snsUrl from '@geekmidas/events/sns/url';\nimport * as sqsUrl from '@geekmidas/events/sqs/url';\nimport {\n\tcacheTable,\n\tcookieDomain,\n\tdrawSecret,\n\texternalApiUrl,\n\tmobileOrigins,\n\tprovideKey,\n\tschemeBase,\n\twildcardDomainOf,\n} from '@geekmidas/manifest';\nimport { LOGS_ORG, otlpHeaders } from '../compose/logs.js';\nimport { GkmError } from '../errors';\nimport { telemetryEnv } from '../telemetry/config.js';\nimport { hostFor } from './caddyfile';\nimport { primaryPortKey } from './containers';\nimport {\n\tEMULATOR_REGION,\n\temulatorEndpoint,\n\temulatorQueueUrl,\n\temulatorTopicArn,\n} from './emulator';\nimport { INBOX_RELAY_TOKEN_KEY, inboxRelayToken } from './inboxRelay';\nimport type { ContainerCredentials } from './localCredentials';\nimport { objectsWebhookToken } from './objectEvents';\nimport { PgBossNeedsDatabase, type Plan, type PlannedResource } from './plan';\nimport type { PortAssignments } from './ports';\n\n/** The host containers are published on. */\nconst LOCAL_HOST = 'localhost';\n\n/** The region local buckets claim, so the client has one to sign with. */\nconst LOCAL_REGION = 'us-east-1';\n\n/**\n * The credentials the S3 client resolves for MinIO.\n *\n * An `s3://` URL deliberately carries none: deployed, the SDK reads them from\n * the execution role, so a URL that embedded a key would be one more thing to\n * rotate and one more thing to leak into a log. Locally there is no role, and\n * the same chain reads these — which is why they are injected beside the URL\n * rather than written into it.\n */\nfunction storageCredentials(\n\tcredentials: ContainerCredentials,\n): Record<string, string> {\n\treturn {\n\t\tAWS_ACCESS_KEY_ID: credentials.minio.user,\n\t\tAWS_SECRET_ACCESS_KEY: credentials.minio.password,\n\t\tAWS_REGION: LOCAL_REGION,\n\t};\n}\n\n/** The port Mailpit's inbox — its web UI and HTTP API — is published under. */\nconst MAILPIT_INBOX_PORT = 'mailpit-web';\n\n/** The schema pg-boss keeps its tables in, inside the declared database. */\nconst PGBOSS_SCHEMA = 'pgboss';\n\n/** The exchange every local topic and queue shares on RabbitMQ. */\nconst RABBITMQ_EXCHANGE = 'gkm.events';\n\nexport interface EnvOptions {\n\t/** Assigned ports, keyed by port key. */\n\tports: PortAssignments;\n\t/**\n\t * The buckets, by construct id, whose MinIO posts their events to be\n\t * relayed onto the broker — see `objectEvents.ts`. Only these resolve an\n\t * events key and a token: a bucket nothing watches has neither.\n\t */\n\trelayedBuckets?: readonly string[];\n\t/**\n\t * The project, which seeds any secret this stage derives.\n\t *\n\t * Derived rather than random so it survives a restart -- a signing key that\n\t * changed on every `gkm dev` would invalidate every session you were in the\n\t * middle of -- and seeded by the project so two checkouts do not share one.\n\t */\n\tproject?: string;\n\t/**\n\t * Where each address-owning construct answers, keyed by id — surfaces and\n\t * sites, e.g. `{ Api: 'http://localhost:3000', Console: 'http://localhost:5173' }`\n\t * — and a file server a target placed at a host of its own (`gkm compose`'s\n\t * edge).\n\t *\n\t * Not container addresses: `gkm dev` assigns these, which is why they arrive\n\t * here rather than being read off a published port. Keyed by id rather than\n\t * being one `surface` string because there is more than one address in a\n\t * workspace and the difference between them is exactly what CORS is about.\n\t */\n\taddresses?: Readonly<Record<string, string>>;\n\t/**\n\t * This machine's address on the local network — what a phone running the\n\t * app reaches it on. Only a local stage has one, and only a project with a\n\t * mobile app reads it: its `exp://` origins, and the address sign-in links\n\t * for the app are built on.\n\t */\n\tlanAddress?: string;\n\t/** Each mobile app's Metro port, by id — the exact port its `exp://` origins name. */\n\tmetroPorts?: Readonly<Record<string, number>>;\n\t/**\n\t * The domain mail is sent from locally.\n\t *\n\t * Stage config, exactly as it is deployed — the difference is only that here\n\t * nobody had to verify it.\n\t */\n\tmailFrom?: string;\n\t/**\n\t * The stage's random seed, salting every derived role password.\n\t *\n\t * The local stages' is generated once per machine with their logins; a\n\t * stack that serves a deployed stage passes the seed its store keeps, so\n\t * its passwords are the ones a deploy derives. Either way they are not\n\t * computable from the repo.\n\t */\n\tseed?: string;\n\t/**\n\t * What every container was brought up with — the cluster's superuser,\n\t * MinIO's root, the cache's token, the emulator's key pair.\n\t *\n\t * pg-boss and a `roles: false` database connect as the superuser, so its\n\t * login is in their URLs.\n\t */\n\tcredentials: ContainerCredentials;\n}\n\n/**\n * The credentials a stage's URLs carry: the containers' logins and the seed\n * role passwords are salted with.\n */\ninterface StageCredential {\n\tcontainers: ContainerCredentials;\n\tseed?: string;\n}\n\n/** The credential `options` describe. */\nfunction credentialOf(options: {\n\tseed?: string;\n\tcredentials: ContainerCredentials;\n}): StageCredential {\n\treturn {\n\t\tcontainers: options.credentials,\n\t\t...(options.seed ? { seed: options.seed } : {}),\n\t};\n}\n\n/**\n * What project code run against a stage is handed — a migration, a seed, an\n * app under `gkm dev`, `gkm exec`'s command, `gkm compose`'s seeds: the\n * stage's stored secrets, under every value the stage resolved.\n *\n * One merge for every command, so a seed sees the same keys whichever one\n * runs it. Each command supplies only what is its own — the ports it reaches\n * the containers on, their logins — as inputs to {@link envFor}.\n *\n * The resolved values win: they are the statement of what exists, and a\n * stored URL naming an old port is the drift resolution replaces. A command\n * whose stage says a value by hand (a deployed stack's) leaves that key out\n * of `resolved`.\n */\nexport function stageEnv(\n\tstored: Readonly<Record<string, string>>,\n\tresolved: Readonly<Record<string, string>>,\n): Record<string, string> {\n\treturn { ...stored, ...resolved };\n}\n\n/**\n * Every env key a reconciled plan resolves, and its value.\n *\n * Keys come from the declaration rather than being re-derived, so what the build\n * publishes and what the app reads cannot drift.\n */\nexport function envFor(\n\tplan: Plan,\n\toptions: EnvOptions,\n): Record<string, string> {\n\tconst env: Record<string, string> = {};\n\tconst credential = credentialOf(options);\n\n\t// Resolved once, up front, because a surface's cookie domain and origin list\n\t// are derived from *other constructs'* addresses — and reading them as the\n\t// loop happened to reach them would make the answer depend on the order the\n\t// manifest was keyed in.\n\tconst resolved: Record<string, string> = {};\n\tconst devices = options.lanAddress ? deviceBuckets(plan) : new Set<string>();\n\tfor (const resource of plan.resources) {\n\t\tconst url = urlFor(\n\t\t\tresource,\n\t\t\tplan,\n\t\t\toptions.ports,\n\t\t\toptions.project ?? '',\n\t\t\toptions.addresses,\n\t\t\tcredential,\n\t\t\tdevices.has(resource.id) ? options.lanAddress : undefined,\n\t\t);\n\t\tif (url) resolved[resource.id] = url;\n\t}\n\n\tfor (const resource of plan.resources) {\n\t\tconst url = resolved[resource.id];\n\n\t\t// A surface carries the origins its callers may come from, and they are\n\t\t// its inbound edges — nothing more. Better Auth's CSRF check applies to\n\t\t// every caller and not only to browsers, so a sibling service calling it\n\t\t// is rejected unless its origin is listed; that this list is now the\n\t\t// graph rather than every app the workspace happens to run is what makes\n\t\t// it the same list deployed, where no workspace is watching.\n\t\tif (resource.kind === 'rest-api') {\n\t\t\tObject.assign(\n\t\t\t\tenv,\n\t\t\t\tsurfaceEnv(resource, url, resolved, {\n\t\t\t\t\tplan,\n\t\t\t\t\t...(options.addresses ? { addresses: options.addresses } : {}),\n\t\t\t\t\t...(options.lanAddress ? { lanAddress: options.lanAddress } : {}),\n\t\t\t\t\t...(options.metroPorts ? { metroPorts: options.metroPorts } : {}),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tif (resource.kind === 'websocket-api') {\n\t\t\t// Who may open it from a browser, read off its inbound edges as a\n\t\t\t// REST surface's are. A socket carries no cookie scope of its own.\n\t\t\tconst origins = surfaceEnv(resource, url, resolved)[\n\t\t\t\tprovideKey(resource.id, 'trustedOrigins')\n\t\t\t];\n\t\t\tif (origins !== undefined) {\n\t\t\t\tenv[provideKey(resource.id, 'trustedOrigins')] = origins;\n\t\t\t}\n\t\t\tconst publisher = webSocketPublisher(\n\t\t\t\tresource,\n\t\t\t\toptions.ports,\n\t\t\t\toptions.project ?? '',\n\t\t\t\tcredential,\n\t\t\t);\n\t\t\tif (publisher) {\n\t\t\t\tenv[provideKey(resource.id, 'publisherConnectionString')] = publisher;\n\t\t\t}\n\t\t}\n\t\tif (url) env[resource.envKey] = url;\n\n\t\t// A wildcard site's tenant is the leading label of the host it is\n\t\t// reached on: the domain under its `*` is what that label comes off,\n\t\t// and the protected labels are the ones no tenant can be.\n\t\tif (resource.kind === 'site' && resource.protectedSubdomains && url) {\n\t\t\tconst domain = wildcardDomainOf(new URL(url).hostname);\n\t\t\tif (domain) {\n\t\t\t\tenv[provideKey(resource.id, 'domain')] = domain;\n\t\t\t\tenv[provideKey(resource.id, 'protectedSubdomains')] =\n\t\t\t\t\tresource.protectedSubdomains.join(',');\n\t\t\t}\n\t\t}\n\n\t\t// A database owns a second key, and it is deliberately not in `provides`:\n\t\t// the owner URL is what a migrator connects with, so no edge in any\n\t\t// manifest can name it and nothing can be granted DDL rights by mistake.\n\t\t// `gkm exec` injects it; a handler never sees it.\n\t\tif (isDatabase(resource.kind) && resource.roles !== false) {\n\t\t\tconst owner = ownerUrl(\n\t\t\t\tresource,\n\t\t\t\tplan,\n\t\t\t\toptions.ports,\n\t\t\t\toptions.project ?? '',\n\t\t\t\tcredential,\n\t\t\t);\n\t\t\tif (owner) env[provideKey(resource.id, 'ownerUrl')] = owner;\n\t\t}\n\n\t\t// An external API owns a second key. Faked, it is the fake's; otherwise\n\t\t// it is the stage's own, from its secrets like any value it was given.\n\t\tif (resource.kind === 'external-api' && url && resource.fake) {\n\t\t\tenv[provideKey(resource.id, 'credentials')] = resource.fake.credentials;\n\t\t}\n\n\t\t// A credential resolves nothing (see `urlFor`) — unless the plan was\n\t\t// made with fakes and it has one: then the stage is handed the fake's\n\t\t// value in place of its own, as an external API is handed its fake's.\n\t\tif (\n\t\t\tresource.kind === 'credential' &&\n\t\t\tresource.fakeCredentials !== undefined\n\t\t) {\n\t\t\tenv[resource.envKey] = resource.fakeCredentials;\n\t\t}\n\n\t\t// Telemetry owns the rest of OpenTelemetry's keys: how to sign in to\n\t\t// OpenObserve, and the sampler — every trace, locally. The service's\n\t\t// name is each process's own, so it is not resolved here.\n\t\tif (resource.kind === 'telemetry' && url) {\n\t\t\tconst login = options.credentials.logs;\n\t\t\tObject.assign(\n\t\t\t\tenv,\n\t\t\t\ttelemetryEnv(\n\t\t\t\t\t{ endpoint: url, headers: otlpHeaders(login.email, login.password) },\n\t\t\t\t\t1,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\t// Mail owns a second key. It is the sending identity, which is the one\n\t\t// thing about mail that differs per stage — so it travels with the URL\n\t\t// rather than being written into the construct.\n\t\t// An inbox owns two more. Its domain, as a wildcard site's is locally:\n\t\t// the project's own under `localhost`, with a label for any stage but\n\t\t// the local one — `test.shop.localhost` — so `gkm test` never receives\n\t\t// what `gkm dev` does; a tenant is a label under it, as deployed. And,\n\t\t// locally, where mail is delivered to it: Mailpit's SMTP, which a test\n\t\t// sends through as any sender would.\n\t\tif (resource.kind === 'inbox' && url) {\n\t\t\tconst base = resource.id.toLowerCase();\n\t\t\tconst stage =\n\t\t\t\tresource.name === base\n\t\t\t\t\t? undefined\n\t\t\t\t\t: resource.name.slice(base.length + 1);\n\t\t\tenv[provideKey(resource.id, 'domain')] = [\n\t\t\t\tstage,\n\t\t\t\toptions.project,\n\t\t\t\tLOCAL_HOST,\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join('.');\n\t\t\tconst smtp = options.ports[primaryPortKey('mailpit')];\n\t\t\tif (smtp !== undefined) {\n\t\t\t\tenv[provideKey(resource.id, 'smtpUrl')] =\n\t\t\t\t\t`smtp://${LOCAL_HOST}:${smtp}`;\n\t\t\t}\n\t\t}\n\n\t\tif (resource.kind === 'email' && url) {\n\t\t\tenv[provideKey(resource.id, 'from')] =\n\t\t\t\toptions.mailFrom ?? `noreply@${LOCAL_HOST}`;\n\n\t\t\t// And, locally, a third: where the mail it sent can be read back.\n\t\t\t// Mailpit answers SMTP on one port and its inbox on another; a feature\n\t\t\t// test signs in by opening the email that was actually sent, and this\n\t\t\t// is how it finds it. Deployed mail has no inbox, so nothing deployed\n\t\t\t// publishes this key.\n\t\t\tconst inbox = options.ports[MAILPIT_INBOX_PORT];\n\t\t\tif (inbox !== undefined) {\n\t\t\t\tenv[provideKey(resource.id, 'inboxUrl')] =\n\t\t\t\t\t`http://${LOCAL_HOST}:${inbox}`;\n\t\t\t}\n\t\t}\n\t}\n\n\t// After the loop, and deliberately: a site's keys are renames of values the\n\t// constructs it depends on resolved, so every source has to exist before any\n\t// of them can be read. Doing it inline would make the result depend on the\n\t// order the manifest happened to be keyed in.\n\tObject.assign(env, publicEnv(plan, env, options.addresses));\n\n\tObject.assign(env, brokerEnv(plan, options.ports, credential));\n\n\t// A bucket in MinIO has no topic of its own to publish its events to:\n\t// MinIO posts them to the process that runs the bucket's subscribers, which\n\t// relays them onto the one broker — so that broker is where they are\n\t// delivered from, and the token is what MinIO presents. On SNS a bucket's\n\t// events come from a topic the storage publishes to instead.\n\tconst relay = env.EVENT_PUBLISHER_CONNECTION_STRING;\n\tif (relay && options.relayedBuckets?.length) {\n\t\tfor (const resource of plan.resources) {\n\t\t\tif (resource.kind !== 'objects' || resource.container !== 'minio') {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!options.relayedBuckets.includes(resource.id)) continue;\n\t\t\tif (!env[resource.envKey]) continue;\n\t\t\tenv[provideKey(resource.id, 'eventsConnectionString')] = relay;\n\t\t\tenv[provideKey(resource.id, 'eventsToken')] = objectsWebhookToken(\n\t\t\t\toptions.project ?? '',\n\t\t\t\tresource.id,\n\t\t\t\tcredential.seed,\n\t\t\t);\n\t\t}\n\t}\n\n\t// The token Mailpit's webhook presents to the worker that receives for\n\t// every inbox — derived beside its URL, so the two cannot disagree.\n\tif (plan.resources.some((r) => r.kind === 'inbox' && env[r.envKey])) {\n\t\tenv[INBOX_RELAY_TOKEN_KEY] = inboxRelayToken(\n\t\t\toptions.project ?? '',\n\t\t\tcredential.seed,\n\t\t);\n\t}\n\n\t// Only once a bucket actually resolved: an unresolvable plan resolves\n\t// nothing, and credentials for a container that is not running are noise.\n\tif (plan.resources.some((r) => r.kind === 'objects' && env[r.envKey])) {\n\t\tObject.assign(env, storageCredentials(options.credentials));\n\t}\n\n\treturn env;\n}\n\n/**\n * The values a site's bundler inlines, under the names it inlines them by.\n *\n * A rename and nothing more. `API_URL` was resolved once, by the same code that\n * resolved it for the server; a site reads the same value under `VITE_API_URL`\n * because that prefix is how its bundler is told to ship it. Nothing is derived\n * twice, so a site and its API cannot come to disagree about where the API is.\n *\n * A source that resolved to nothing is skipped rather than written empty: an\n * inlined empty string is a frontend that builds and then fails at runtime\n * against `http:///`, where a missing variable fails at build with the name of\n * the thing that is missing.\n */\nfunction publicEnv(\n\tplan: Plan,\n\tresolved: Record<string, string>,\n\t/** Where each surface answers on its own port — what a mobile app is given. */\n\taddresses: Readonly<Record<string, string>> = {},\n): Record<string, string> {\n\tconst env: Record<string, string> = {};\n\t// Which construct each key belongs to, so a mobile app can be handed the\n\t// surface's own port rather than the edge's hostname.\n\tconst owners = new Map(plan.resources.map((r) => [r.envKey, r.id]));\n\n\tfor (const resource of plan.resources) {\n\t\tfor (const [key, source] of Object.entries(resource.publicEnv ?? {})) {\n\t\t\t// A phone cannot open `https://api-dev.shop.localhost` — the hostname\n\t\t\t// resolves only on this machine, and the edge routes by it, so no LAN\n\t\t\t// address can stand in for it. The surface's own port can: the app\n\t\t\t// swaps `localhost` for the host Metro was served from, and reaches it.\n\t\t\tconst direct =\n\t\t\t\tresource.kind === 'mobile-app'\n\t\t\t\t\t? addresses[owners.get(source) ?? '']\n\t\t\t\t\t: undefined;\n\t\t\tconst value = direct ?? resolved[source];\n\t\t\tif (value) env[key] = value;\n\t\t}\n\t}\n\n\treturn env;\n}\n\n/**\n * What a surface publishes beyond its own address: who may call it, and where\n * a cookie set by it is readable.\n *\n * Both are read off the same list — the constructs that declared an edge to\n * this surface — which is why neither appears in application code. A surface\n * that listed its own callers would be edited every time something new called\n * it, and the thing being edited is already recorded in the graph.\n *\n * An empty origin list is written, and a surface with no address writes nothing\n * at all. The two cases look alike and are not: \"nothing depends on this yet\" is\n * a real state a target should publish, while \"this surface has no address here\"\n * means it is not running in this stage, and keys belong with the address they\n * describe.\n */\nfunction surfaceEnv(\n\tresource: PlannedResource,\n\turl: string | undefined,\n\t/**\n\t * Every construct's *resolved* address, keyed by id — not the raw ones the\n\t * workspace assigned.\n\t *\n\t * The difference is the feature. Behind the edge a surface and its callers\n\t * are `api.shop.localhost` and `console.shop.localhost`, which share a\n\t * parent and therefore a cookie; the addresses they were assigned are\n\t * `localhost:3000` and `localhost:5173`, which are one host with two ports\n\t * and share nothing. Deriving from the wrong one produces a local cookie\n\t * model that is *different* from the deployed one rather than matching it.\n\t */\n\tresolved: Readonly<Record<string, string>> = {},\n\tlocal: {\n\t\tplan?: Plan;\n\t\taddresses?: Readonly<Record<string, string>>;\n\t\tlanAddress?: string;\n\t\tmetroPorts?: Readonly<Record<string, number>>;\n\t} = {},\n): Record<string, string> {\n\tif (!url) return {};\n\n\tconst origins = [\n\t\t...new Set(\n\t\t\t(resource.callers ?? [])\n\t\t\t\t.map((caller) => resolved[caller])\n\t\t\t\t.filter((address): address is string => Boolean(address))\n\t\t\t\t.map(originOf)\n\t\t\t\t.filter((origin): origin is string => Boolean(origin)),\n\t\t),\n\t].sort();\n\n\t// Its own address belongs in the cookie derivation but not in the origin\n\t// list: a surface does not need permission to call itself, and adding it\n\t// would make every surface trust every other one that shares a port.\n\tconst domain = cookieDomain([url, ...origins]);\n\n\t// A mobile caller is reached by its scheme, not an address, so it adds its\n\t// scheme — and, on this local stage, the `exp://` hosts Expo Go sends from —\n\t// rather than an origin read off a URL. After the cookie domain on purpose:\n\t// a scheme is not a host anything shares a cookie with.\n\tconst mobile = (resource.callers ?? [])\n\t\t.map((caller) =>\n\t\t\tlocal.plan?.resources.find(\n\t\t\t\t(r) => r.id === caller && r.kind === 'mobile-app',\n\t\t\t),\n\t\t)\n\t\t.filter((caller): caller is PlannedResource => Boolean(caller));\n\tconst hosts = [...(local.lanAddress ? [local.lanAddress] : []), LOCAL_HOST];\n\tconst schemes = mobile.flatMap((caller) => {\n\t\tconst scheme = resolved[caller.id];\n\t\tconst port = local.metroPorts?.[caller.id];\n\t\treturn scheme\n\t\t\t? mobileOrigins(scheme, { hosts, ...(port ? { port } : {}) })\n\t\t\t: [];\n\t});\n\n\t// Where a phone reaches this surface: its own port on the LAN address. What\n\t// the auth server builds a sign-in link on when the app asked for it — the\n\t// link is opened on the phone, which cannot resolve the edge's hostname.\n\tconst own = local.addresses?.[resource.id];\n\tconst device =\n\t\tmobile.length > 0 && local.lanAddress && own\n\t\t\t? own.replace(\n\t\t\t\t\t/\\/\\/(localhost|127\\.0\\.0\\.1)(?=[:/]|$)/,\n\t\t\t\t\t`//${local.lanAddress}`,\n\t\t\t\t)\n\t\t\t: undefined;\n\n\treturn {\n\t\t[provideKey(resource.id, 'trustedOrigins')]: [\n\t\t\t...origins,\n\t\t\t...new Set(schemes),\n\t\t].join(','),\n\t\t...(domain ? { [provideKey(resource.id, 'cookieDomain')]: domain } : {}),\n\t\t...(device ? { [provideKey(resource.id, 'deviceUrl')]: device } : {}),\n\t};\n}\n\n/**\n * The buckets whose links a phone opens: those a surface a mobile app calls\n * depends on.\n *\n * The surface hands the app a URL it built — a file server's public link, a\n * bucket's presigned one — and the phone cannot resolve `*.localhost`, or\n * reach `localhost` at all. A presigned URL's signature covers its host, so\n * nothing downstream can move it either: the bucket has to be resolved on the\n * LAN address in the first place.\n */\nfunction deviceBuckets(plan: Plan): Set<string> {\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\tconst fromApp = (id: string): boolean => {\n\t\tconst caller = byId.get(id);\n\t\tif (caller?.kind === 'mobile-app') return true;\n\t\treturn (\n\t\t\t(caller?.kind === 'rest-api' || caller?.kind === 'websocket-api') &&\n\t\t\t(caller.callers ?? []).some((c) => byId.get(c)?.kind === 'mobile-app')\n\t\t);\n\t};\n\n\tconst buckets = new Set(\n\t\tplan.resources\n\t\t\t.filter((r) => r.kind === 'objects' || r.kind === 'file-server')\n\t\t\t.filter((r) => (r.callers ?? []).some(fromApp))\n\t\t\t.map((r) => r.id),\n\t);\n\t// A `FileServer` is one construct declaring two nodes, and a handler's\n\t// edge is to the bucket — so the server fronting a bucket a phone's links\n\t// come from serves the phone too.\n\tfor (const r of plan.resources) {\n\t\tif (r.kind === 'file-server' && r.of && buckets.has(r.of)) {\n\t\t\tbuckets.add(r.id);\n\t\t}\n\t}\n\treturn buckets;\n}\n\n/**\n * Where a WebSocket surface's publisher meets its sockets: the local Redis,\n * on channels named for the project and the surface, so two projects sharing\n * one Redis never see each other's frames.\n */\nexport function webSocketPublisher(\n\tresource: PlannedResource,\n\tports: PortAssignments,\n\tproject: string,\n\tcredential: StageCredential,\n): string | undefined {\n\tconst port = ports[primaryPortKey('redis')];\n\tif (port === undefined) return undefined;\n\n\tconst channel = encodeURIComponent(\n\t\t`gkm:ws:${project ? `${project}:` : ''}${resource.id}`,\n\t);\n\treturn `redis://:${encodeURIComponent(credential.containers.redis.password)}@${LOCAL_HOST}:${port}?channel=${channel}`;\n}\n\n/**\n * An address reduced to the origin a browser compares against.\n *\n * A WebSocket surface's address is `wss://`, but its host is served over\n * HTTPS like any other: its origin is that one, and a non-web scheme among the\n * origins means a mobile app to whoever reads the list.\n */\nfunction originOf(address: string): string | undefined {\n\ttry {\n\t\treturn new URL(address.replace(/^ws(s?):/, 'http$1:')).origin;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * The runtime role of whatever a derived node hangs off.\n *\n * A reader's parent may itself be a schema tenant, so this follows `of` by one\n * hop rather than assuming the cluster — the reader of a tenant reads that\n * tenant's schema, not the database's.\n */\nfunction parentRole(resource: PlannedResource, plan: Plan): string {\n\tconst parent = plan.resources.find((r) => r.id === resource.of);\n\n\treturn parent ? localRole(parent) : resource.name;\n}\n\n/** Whether a kind connects to Postgres and therefore has an owner role. */\nfunction isDatabase(kind: PlannedResource['kind']): boolean {\n\treturn kind === 'database' || kind === 'database-schema';\n}\n\n/**\n * The URL a migrator connects with — the owner role, which can create, alter\n * and drop.\n *\n * Never in `provides`, which is the whole point. A handler that could reach this\n * could `DROP TABLE`, and the security property the role split exists for is\n * that it cannot: the value is injected by `gkm exec` for the migrate step and\n * by nothing else.\n */\nfunction ownerUrl(\n\tresource: PlannedResource,\n\tplan: Plan,\n\tports: PortAssignments,\n\tproject: string,\n\tcredential: StageCredential,\n): string | undefined {\n\tif (!resource.container) return undefined;\n\n\tconst port = ports[primaryPortKey(resource.container)];\n\tif (port === undefined) return undefined;\n\n\tconst owner = ownerRole(localRole(resource));\n\n\treturn postgres(port, rootDatabase(resource, plan), {\n\t\tuser: owner,\n\t\tpassword: localRolePassword(project, plan, owner, credential.seed),\n\t});\n}\n\n/**\n * The shared broker keys, when anything is published or consumed.\n *\n * A queue's own key is the producer's. These two are the *connection* itself,\n * which locally is one broker for every queue and topic in the project: the\n * generated pollers open a single connection and subscribe each worker by name\n * on it. Deployed there is no such thing — a Lambda is handed its own event\n * source — so this pair exists for the local target and says so.\n */\nfunction brokerEnv(\n\tplan: Plan,\n\tports: PortAssignments,\n\tcredential: StageCredential,\n): Record<string, string> {\n\tconst carrier = plan.resources.find(\n\t\t(r) => r.kind === 'queue' || r.kind === 'topic',\n\t);\n\n\tconst publisher = carrier\n\t\t? urlFor(carrier, plan, ports, '', {}, credential)\n\t\t: plan.workerBroker\n\t\t\t? workerBroker(plan, ports, credential)\n\t\t\t: undefined;\n\tif (!publisher) return {};\n\n\t// One broker address only where there is one broker: pg-boss and RabbitMQ.\n\t// On SNS every topic and queue is its own address, carried by its own\n\t// `<ID>_PUBLISHER_CONNECTION_STRING`, and no single string stands for them.\n\tif (plan.events === 'sns') return {};\n\n\treturn { EVENT_PUBLISHER_CONNECTION_STRING: publisher };\n}\n\n/**\n * The broker a worker schedules its crons through, when nothing else declared\n * one — pg-boss in the declared database, on that database's port.\n */\nfunction workerBroker(\n\tplan: Plan,\n\tports: PortAssignments,\n\tcredential: StageCredential,\n): string | undefined {\n\tconst database = plan.resources.find((r) => r.kind === 'database');\n\tif (!database?.container) return undefined;\n\n\tconst port = ports[primaryPortKey(database.container)];\n\treturn port === undefined ? undefined : broker(plan, port, credential);\n}\n\n/**\n * The URL for one planned resource.\n *\n * Every part of it comes from the resource and the port it was published on.\n */\nfunction urlFor(\n\tresource: PlannedResource,\n\tplan: Plan,\n\tports: PortAssignments,\n\tproject: string,\n\taddresses: Readonly<Record<string, string>> | undefined,\n\tcredential: StageCredential,\n\t/**\n\t * The LAN address, for a bucket whose links a phone opens — see\n\t * `deviceBuckets`. Undefined for everything else.\n\t */\n\tlan?: string,\n): string | undefined {\n\t// A secret has no address, so there is no port to wait for.\n\tif (resource.kind === 'secret') return localSecret(project, plan, resource);\n\n\t// Nor has an encryption key: a keyring derived the way a secret is.\n\tif (resource.kind === 'encryption') {\n\t\treturn localKeyring(project, plan, resource);\n\t}\n\n\t// A mobile app resolves its scheme — the same on every stage.\n\tif (resource.kind === 'mobile-app') {\n\t\treturn schemeBase(project, resource.scheme);\n\t}\n\n\t// A credential resolves to nothing here, deliberately. A secret is derived\n\t// because the platform owns it; a credential was issued by a third party, so\n\t// inventing a value would produce a Stripe key that is not a Stripe key and\n\t// fail at the first call rather than at the first read. It comes from\n\t// `gkm secrets` or `.env` like any other supplied value, and the construct's\n\t// own schema is what reports it missing — or, on a stage that fakes, from\n\t// its fake (`envFor`).\n\tif (resource.kind === 'credential') return undefined;\n\n\t// An external API is the provider, at its URL for this stage — unless the\n\t// plan was made with fakes (`gkm test`, `gkm dev --fake`), and then it is\n\t// its fake, on the port its key was assigned.\n\tif (resource.kind === 'external-api') {\n\t\tif (!resource.fake) {\n\t\t\treturn resource.url === undefined\n\t\t\t\t? undefined\n\t\t\t\t: externalApiUrl({ id: resource.id, url: resource.url }, plan.stage);\n\t\t}\n\t\tconst port = ports[resource.fake.key];\n\t\treturn port === undefined ? undefined : `http://${LOCAL_HOST}:${port}`;\n\t}\n\n\t// A surface answers on the app's own port, and a site on its dev server's —\n\t// both assigned by the workspace, neither published by a container.\n\t//\n\t// Behind the edge when there is one, which is what gives them a hostname and\n\t// a certificate rather than a port on localhost. The application cannot tell\n\t// the difference: it reads whichever address was injected and composes none,\n\t// so this is the target's decision alone.\n\tif (resource.kind === 'rest-api' || resource.kind === 'site') {\n\t\tconst address = addresses?.[resource.id];\n\t\tconst edge = plan.containers.includes('caddy')\n\t\t\t? ports[primaryPortKey('caddy')]\n\t\t\t: undefined;\n\n\t\treturn address && edge !== undefined\n\t\t\t? `https://${hostFor(resource, project)}:${edge}`\n\t\t\t: address;\n\t}\n\n\t// The same address, in the scheme a WebSocket client opens.\n\tif (resource.kind === 'websocket-api') {\n\t\tconst address = addresses?.[resource.id];\n\t\tconst edge = plan.containers.includes('caddy')\n\t\t\t? ports[primaryPortKey('caddy')]\n\t\t\t: undefined;\n\n\t\treturn address && edge !== undefined\n\t\t\t? `wss://${hostFor(resource, project)}:${edge}`\n\t\t\t: address?.replace(/^http/, 'ws');\n\t}\n\n\tif (!resource.container) return undefined;\n\n\tconst port = ports[primaryPortKey(resource.container)];\n\tif (port === undefined) return undefined;\n\n\tswitch (resource.kind) {\n\t\tcase 'database':\n\t\tcase 'database-schema':\n\t\tcase 'database-reader': {\n\t\t\t// A tenant and a reader both live in the *parent's* database; what\n\t\t\t// separates them is the role's grants and the `search_path` pinned on\n\t\t\t// that role, never a database of their own.\n\t\t\tconst database = rootDatabase(resource, plan);\n\n\t\t\t// The runtime role, which can read and write rows and create nothing.\n\t\t\t// `search_path` is pinned on the role by the DDL rather than carried\n\t\t\t// here, so a connection string cannot forget it — and forgetting it\n\t\t\t// looks like an empty database rather than an error.\n\t\t\t//\n\t\t\t// `roles: false` is the documented downgrade: both URLs fall back to\n\t\t\t// the cluster's master credential, and the schema goes back into the\n\t\t\t// URL because there is no role to pin it on.\n\t\t\tif (resource.roles === false) {\n\t\t\t\tconst schema = schemaOf(resource, plan);\n\n\t\t\t\tconst master = credential.containers.postgres;\n\t\t\t\treturn schema\n\t\t\t\t\t? `${postgres(port, database, master)}?search_path=${schema}`\n\t\t\t\t\t: postgres(port, database, master);\n\t\t\t}\n\n\t\t\t// A reader connects as the read-only role on its parent, not as a role\n\t\t\t// of its own: read-only is enforced by the grants, which is what makes\n\t\t\t// falling back to the writer's endpoint safe where no replica exists.\n\t\t\tconst role =\n\t\t\t\tresource.kind === 'database-reader'\n\t\t\t\t\t? readerRole(parentRole(resource, plan))\n\t\t\t\t\t: localRole(resource);\n\n\t\t\treturn postgres(port, database, {\n\t\t\t\tuser: role,\n\t\t\t\tpassword: localRolePassword(project, plan, role, credential.seed),\n\t\t\t});\n\t\t}\n\n\t\tcase 'telemetry':\n\t\t\t// OpenObserve takes OTLP/HTTP under its organisation's API.\n\t\t\treturn `http://${LOCAL_HOST}:${port}/api/${LOGS_ORG}`;\n\n\t\tcase 'email':\n\t\t\t// The same scheme the deployed target writes; only host and credentials\n\t\t\t// differ, which is what lets the client never branch on provider.\n\t\t\treturn `smtp://${LOCAL_HOST}:${port}`;\n\n\t\tcase 'inbox': {\n\t\t\t// Where its raw messages are read from: Mailpit's API, which keeps\n\t\t\t// every message it receives. Deployed it is the bucket SES stores\n\t\t\t// them in; the decoder reads by key from whichever this names.\n\t\t\tconst api = ports[MAILPIT_INBOX_PORT];\n\t\t\treturn api === undefined ? undefined : `http://${LOCAL_HOST}:${api}`;\n\t\t}\n\n\t\tcase 'objects':\n\t\t\t// `?endpoint=` is what points the same S3 client at MinIO — the client\n\t\t\t// is identical, only the URL differs. Path-style addressing goes with\n\t\t\t// it: virtual-host style resolves `bucket.localhost`, which is not\n\t\t\t// MinIO and not anything.\n\t\t\t//\n\t\t\t// On the LAN address when a phone opens its links: a presigned URL is\n\t\t\t// signed for the endpoint's host, so it is the endpoint that moves.\n\t\t\t// MinIO answers on it from this machine too.\n\t\t\treturn `s3://${resource.name}?region=${LOCAL_REGION}&endpoint=http://${lan ?? LOCAL_HOST}:${port}&forcePathStyle=true`;\n\n\t\tcase 'file-server': {\n\t\t\t// A host of its own, over TLS — the shape it has deployed, and the one\n\t\t\t// MinIO alone cannot produce: its virtual-host mode reads the leading\n\t\t\t// label *as the bucket name*, so it matches only when the server's id\n\t\t\t// and the bucket's agree and never for a server fronting two buckets.\n\t\t\t// The local edge in front of it does the mapping instead, and issues\n\t\t\t// the certificate. An AWS emulator supplies neither: CloudFront\n\t\t\t// emulation is control plane only, and this is the data plane.\n\t\t\t//\n\t\t\t// The port is in the address because ports are assigned rather than\n\t\t\t// fixed, so two projects can run at once. Nothing that reads a\n\t\t\t// hostname — a cookie domain, a CORS origin — looks at it.\n\t\t\tconst origin = plan.resources.find((r) => r.id === resource.of);\n\t\t\tif (!origin) return undefined;\n\n\t\t\t// Where a target put it — a stack's edge, at the host its links are\n\t\t\t// built on — which is the one address a link stored by a seed stays\n\t\t\t// right at.\n\t\t\tconst placed = addresses?.[resource.id];\n\t\t\tif (placed) return placed;\n\n\t\t\t// A phone resolves no `*.localhost` host, and the edge routes on it,\n\t\t\t// so a file server whose links reach one is the path under MinIO on\n\t\t\t// the LAN address — the one address that needs no Host routing.\n\t\t\t// Not with processors: they answer only through the edge, and a link\n\t\t\t// past it would serve the original rather than what was asked for.\n\t\t\tconst objects = origin.container\n\t\t\t\t? ports[primaryPortKey(origin.container)]\n\t\t\t\t: undefined;\n\t\t\tif (lan && !resource.processors?.length && objects !== undefined) {\n\t\t\t\treturn `http://${lan}:${objects}/${origin.name}`;\n\t\t\t}\n\n\t\t\t// With the edge off, the honest local answer is the address that\n\t\t\t// works: a path under the object store. It is not the deployed shape,\n\t\t\t// and the application still cannot tell — it reads the key it was\n\t\t\t// given and never composes one.\n\t\t\treturn plan.containers.includes('caddy')\n\t\t\t\t? `https://${hostFor(resource, project)}:${port}`\n\t\t\t\t: `http://${LOCAL_HOST}:${port}/${origin.name}`;\n\t\t}\n\n\t\tcase 'cache':\n\t\t\t// The scheme is the backend, and the backend is the same one deployed —\n\t\t\t// which is what lets a driver registered at build time match the URL\n\t\t\t// resolved at run time.\n\t\t\t//\n\t\t\t// A cache in a database has no address of its own: no second host and\n\t\t\t// no second credential, just its parent's URL. Reached by following\n\t\t\t// `of` and nothing else — `planFor` has already resolved a\n\t\t\t// `cache: 'db'` backend into that edge, so there is one way a cache\n\t\t\t// lands in a database and one way to find out.\n\t\t\tif (resource.of) {\n\t\t\t\tconst parent = plan.resources.find((r) => r.id === resource.of);\n\t\t\t\tconst url = parent\n\t\t\t\t\t? urlFor(parent, plan, ports, project, addresses, credential)\n\t\t\t\t\t: undefined;\n\n\t\t\t\t// The parent's address plus the one thing that distinguishes this\n\t\t\t\t// cache from another in the same database: its table. Two caches on\n\t\t\t\t// one database resolve the same connection string, so without it a\n\t\t\t\t// client built from the URL cannot tell them apart.\n\t\t\t\treturn url\n\t\t\t\t\t? withTable(url, resource.table ?? cacheTable(resource.id))\n\t\t\t\t\t: undefined;\n\t\t\t}\n\n\t\t\tswitch (plan.cache) {\n\t\t\t\tcase 'elasticache':\n\t\t\t\tcase 'redis':\n\t\t\t\t\t// The wire protocol, with the password the container requires.\n\t\t\t\t\t// Deployed it is `rediss://` inside a VPC; the client is the\n\t\t\t\t\t// same either way.\n\t\t\t\t\treturn `redis://:${encodeURIComponent(credential.containers.redis.password)}@${LOCAL_HOST}:${port}`;\n\n\t\t\t\tdefault:\n\t\t\t\t\t// The token in the userinfo, because an address and the credential\n\t\t\t\t\t// that opens it are one fact. Deployed the scheme is https and the\n\t\t\t\t\t// host is the provider's; nothing else differs.\n\t\t\t\t\treturn `http://:${encodeURIComponent(credential.containers.cacheToken)}@${LOCAL_HOST}:${port}`;\n\t\t\t}\n\n\t\tcase 'queue':\n\t\tcase 'topic':\n\t\t\treturn broker(plan, port, credential, resource);\n\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * The producer's connection string, composed from the backend the plan chose.\n *\n * The protocol is what picks the transport, so a producer never branches: the\n * same `.publish()` reaches pg-boss here and SQS deployed because the string it\n * was handed said so.\n */\nfunction broker(\n\tplan: Plan,\n\tport: number,\n\tcredential: StageCredential,\n\t/** The topic or queue — needed where each is its own address (SNS/SQS). */\n\tresource?: PlannedResource,\n): string {\n\tswitch (plan.events) {\n\t\tcase 'pgboss': {\n\t\t\t// A schema tenant of the database the app already declared, which is\n\t\t\t// why nothing here invents a Postgres of its own.\n\t\t\tconst database = plan.resources.find((r) => r.kind === 'database');\n\t\t\tif (!database) throw new PgBossNeedsDatabase([]);\n\n\t\t\tconst { user, password } = credential.containers.postgres;\n\t\t\treturn `pgboss://${user}:${encodeURIComponent(password)}@${LOCAL_HOST}:${port}/${database.name}?schema=${PGBOSS_SCHEMA}`;\n\t\t}\n\n\t\tcase 'rabbitmq': {\n\t\t\t// The exchange is declared by whichever client connects first, so\n\t\t\t// naming it here is the whole of the setup.\n\t\t\tconst { user, password } = credential.containers.rabbitmq;\n\t\t\treturn `rabbitmq://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${LOCAL_HOST}:${port}?exchange=${RABBITMQ_EXCHANGE}`;\n\t\t}\n\n\t\tcase 'sns': {\n\t\t\t// The emulator's ARNs and queue URLs are deterministic, so the address\n\t\t\t// is composed here and the topic or queue is created beside it by the\n\t\t\t// applier (`applyCarriers`). Credentials ride in the string: the\n\t\t\t// emulator's are not the developer's AWS profile, and must not be\n\t\t\t// picked up from it.\n\t\t\tif (!resource) throw new UnprovisionedEventsBackend('sns');\n\t\t\tconst endpoint = emulatorEndpoint(port);\n\t\t\tconst address =\n\t\t\t\tresource.kind === 'topic'\n\t\t\t\t\t? snsUrl.build({\n\t\t\t\t\t\t\ttopicArn: emulatorTopicArn(resource.name),\n\t\t\t\t\t\t\tregion: EMULATOR_REGION,\n\t\t\t\t\t\t\tendpoint,\n\t\t\t\t\t\t})\n\t\t\t\t\t: sqsUrl.build({\n\t\t\t\t\t\t\tqueueUrl: emulatorQueueUrl(resource.name, port),\n\t\t\t\t\t\t\tregion: EMULATOR_REGION,\n\t\t\t\t\t\t\tendpoint,\n\t\t\t\t\t\t});\n\t\t\tconst url = new URL(address);\n\t\t\tconst { accessKeyId, secretAccessKey } = credential.containers.emulator;\n\t\t\turl.searchParams.set('accessKeyId', accessKeyId);\n\t\t\turl.searchParams.set('secretAccessKey', secretAccessKey);\n\t\t\treturn url.toString();\n\t\t}\n\t}\n}\n\n/** A local Postgres URL, with the login it connects as. */\nfunction postgres(\n\tport: number,\n\tdatabase: string,\n\tcredential: { user: string; password: string },\n): string {\n\treturn `postgres://${credential.user}:${encodeURIComponent(credential.password)}@${LOCAL_HOST}:${port}/${database}`;\n}\n\n/**\n * The role a handler connects as, for one database or tenant.\n *\n * The construct's id, lowercased and stage-scoped exactly as its database or\n * schema is — so `Orders` in the `test` stage connects as `orders_test`, and two\n * stages sharing one cluster cannot share a credential. Roles are cluster-scoped\n * in Postgres, which is why the suffix is not optional here the way it is for a\n * schema.\n */\nexport function localRole(resource: PlannedResource): string {\n\treturn resource.name;\n}\n\n/**\n * The password for a derived local role.\n *\n * Derived rather than random, for the same reason the local secret is: a\n * password that changed on every `gkm dev` would lock a developer out of the\n * data they had a moment ago. Seeded by the project so two checkouts do not\n * share one, and by the stage so `test` and `development` do not.\n *\n * Without a seed it is a *local* credential by construction — the cluster is\n * on loopback and everything it is derived from is in the repo. `gkm compose`\n * serving a deployed stage passes that stage's random seed, which is what\n * makes the same derivation a secret.\n */\nexport function localRolePassword(\n\tproject: string,\n\tplan: Plan,\n\trole: string,\n\t/**\n\t * A deployed stage's random seed. Given, the derivation is the one a\n\t * deploy makes — the seed first — so a stack serving that stage connects\n\t * with the passwords its roles were created with.\n\t */\n\tseed?: string,\n): string {\n\treturn createHash('sha256')\n\t\t.update(`${seed ? `${seed}:` : ''}${project}:${plan.stage}:role:${role}`)\n\t\t.digest('base64url')\n\t\t.slice(0, 32);\n}\n\n/**\n * A cache's address: its database's URL, carrying the table it reads.\n *\n * Appended rather than kept beside the URL as a second key, for the reason the\n * design gives everywhere else — an address and what it opens are one fact, and\n * two keys are one more thing to keep in step.\n */\nfunction withTable(url: string, table: string): string {\n\tconst parsed = new URL(url);\n\tparsed.searchParams.set('table', table);\n\n\treturn parsed.toString();\n}\n\n/**\n * The physical database a derived resource lives in.\n *\n * Walks `of` to the top rather than reading the immediate parent, because a\n * reader's parent may itself be a schema tenant — two hops from the database\n * that actually exists.\n */\nexport function rootDatabase(resource: PlannedResource, plan: Plan): string {\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\tlet current = resource;\n\n\twhile (current.of) {\n\t\tconst parent = byId.get(current.of);\n\t\tif (!parent) break;\n\t\tcurrent = parent;\n\t}\n\n\treturn current.name;\n}\n\n/** The schema a derived resource puts on its search path, if it has one. */\nfunction schemaOf(resource: PlannedResource, plan: Plan): string | undefined {\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\tlet current: PlannedResource | undefined = resource;\n\n\t// A reader has no schema of its own; it reads whatever its parent addresses.\n\twhile (current) {\n\t\tif (current.kind === 'database-schema') return current.schema;\n\t\tcurrent = current.of ? byId.get(current.of) : undefined;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A broker address asked for without the topic or queue it would name.\n *\n * On SNS each topic and queue is its own address, so there is no project-wide\n * one to hand out — a cron's schedule store, say, cannot live there.\n */\nexport class UnprovisionedEventsBackend extends GkmError {\n\tconstructor(readonly backend: string) {\n\t\tsuper(\n\t\t\t`'${backend}' has no single broker address: each topic and queue is ` +\n\t\t\t\t`addressed by its own ARN. Something asked for one without naming ` +\n\t\t\t\t`the topic or queue.`,\n\t\t);\n\t\tthis.name = 'UnprovisionedEventsBackend';\n\t}\n}\n\n/**\n * The keyring an `Encryption` construct resolves to locally.\n *\n * Derived like a secret — stable across restarts, distinct per project, stage\n * and construct, never written to disk — so what `gkm dev` encrypted yesterday\n * still opens today. One key, because nothing local is worth rotating: a\n * server stage's keyring is generated and rotated in its secrets instead.\n */\nfunction localKeyring(\n\tproject: string,\n\tplan: Plan,\n\tresource: PlannedResource,\n): string {\n\tconst derive = (purpose: string) =>\n\t\tcreateHash('sha256')\n\t\t\t.update(`${project}:${plan.stage}:${resource.id}:${purpose}`)\n\t\t\t.digest();\n\n\treturn formatKeyring({\n\t\tkeys: [{ id: 'k1', key: derive('k1') }],\n\t\tindex: derive('index'),\n\t});\n}\n\n/**\n * The value a secret resolves to locally.\n *\n * A hash of what identifies it, so it is stable, distinct per project, stage\n * and construct, and never written to disk as a literal. Deployed this is the\n * one kind whose value does *not* come from here — a secret manager generates\n * it once and the target reads it back. Drawn in the format the deploy draws\n * it in, so a value that passes a third party's rules here passes them there.\n */\nfunction localSecret(\n\tproject: string,\n\tplan: Plan,\n\tresource: PlannedResource,\n): string {\n\treturn drawSecret(\n\t\thashStream(`${project}:${plan.stage}:${resource.id}`),\n\t\tresource.format,\n\t);\n}\n\n/**\n * Integers in `[0, n)` drawn from a hash of `seed`, the same every time —\n * what a local secret is drawn with instead of `crypto`, so `gkm dev` and\n * `gkm test` need nothing stored. Rejection-sampled, so no character is\n * likelier than another.\n */\nfunction hashStream(seed: string): (n: number) => number {\n\tlet block = 0;\n\tlet bytes = Buffer.alloc(0);\n\tlet offset = 0;\n\n\tconst next = (): number => {\n\t\tif (offset === bytes.length) {\n\t\t\tbytes = createHash('sha256').update(`${seed}:${block++}`).digest();\n\t\t\toffset = 0;\n\t\t}\n\t\treturn bytes[offset++] as number;\n\t};\n\n\treturn (n) => {\n\t\tconst limit = 256 - (256 % n);\n\t\tfor (;;) {\n\t\t\tconst byte = next();\n\t\t\tif (byte < limit) return byte % n;\n\t\t}\n\t};\n}\n","/**\n * A bucket's lifecycle, as the constructs declare it: one expiry rule per\n * prefix, merged into whatever else the bucket's lifecycle already holds.\n *\n * S3 — and MinIO, which speaks the same API — keeps one lifecycle document\n * per bucket, and a write replaces all of it. So gkm owns only the rules it\n * names (`gkm-…`): every other rule is read and put back as it was, a rule of\n * gkm's that is no longer declared is dropped, and nothing is written when\n * gkm's rules already say what the manifest does.\n *\n * Shared by the `s3` provider and the MinIO a local or compose stack runs,\n * so a prefix expires the same way on both.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { LifecycleRule } from '@aws-sdk/client-s3';\n\n/** The id every rule gkm writes starts with — and the only ones it touches. */\nexport const GKM_RULE_PREFIX = 'gkm-';\n\n/**\n * The rule id for one prefix: readable, and unique however the prefix is\n * spelled — `a/b` and `a-b` read alike once sanitised, so a short hash of the\n * prefix itself follows.\n */\nexport function expireRuleId(prefix: string): string {\n\tconst readable = prefix\n\t\t.replace(/[^A-Za-z0-9._-]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.slice(0, 200);\n\tconst hash = createHash('sha256').update(prefix).digest('hex').slice(0, 8);\n\treturn `${GKM_RULE_PREFIX}expire-${readable ? `${readable}-` : ''}${hash}`;\n}\n\n/** The rules a bucket's expiry asks for, in a stable order. */\nexport function expireRules(\n\texpire: Readonly<Record<string, number>> | undefined,\n): LifecycleRule[] {\n\treturn Object.entries(expire ?? {})\n\t\t.map(\n\t\t\t([prefix, days]): LifecycleRule => ({\n\t\t\t\tID: expireRuleId(prefix),\n\t\t\t\tStatus: 'Enabled',\n\t\t\t\tFilter: { Prefix: prefix },\n\t\t\t\tExpiration: { Days: days },\n\t\t\t}),\n\t\t)\n\t\t.sort((a, b) => a.ID!.localeCompare(b.ID!));\n}\n\n/** What to do to a bucket's lifecycle, if anything. */\nexport interface LifecycleMerge {\n\t/** Whether gkm's rules differ from what the bucket holds. */\n\tchanged: boolean;\n\t/** The whole document to write: the bucket's other rules, then gkm's. */\n\trules: LifecycleRule[];\n\t/** What changes, said for a plan or a log line. */\n\tdescribe: string;\n}\n\n/**\n * Merge the declared expiry into the bucket's current rules.\n *\n * @param current the bucket's rules, or nothing when it has no lifecycle\n */\nexport function mergeLifecycle(\n\tcurrent: readonly LifecycleRule[] | undefined,\n\texpire: Readonly<Record<string, number>> | undefined,\n): LifecycleMerge {\n\tconst wanted = expireRules(expire);\n\tconst rules = current ?? [];\n\tconst others = rules.filter((r) => !r.ID?.startsWith(GKM_RULE_PREFIX));\n\tconst ours = rules.filter((r) => r.ID?.startsWith(GKM_RULE_PREFIX));\n\n\tconst changed =\n\t\tcanonical(ours) !== canonical(wanted) ||\n\t\t// A second rule under one of gkm's ids is drift too.\n\t\tnew Set(ours.map((r) => r.ID)).size !== ours.length;\n\n\treturn {\n\t\tchanged,\n\t\trules: [...others, ...wanted],\n\t\tdescribe: describeExpiry(expire),\n\t};\n}\n\n/** `expire quotes/ after 30 days, tmp/ after 1 day` — or what removing says. */\nfunction describeExpiry(\n\texpire: Readonly<Record<string, number>> | undefined,\n): string {\n\tconst entries = Object.entries(expire ?? {}).sort(([a], [b]) =>\n\t\ta.localeCompare(b),\n\t);\n\tif (entries.length === 0) return 'remove expiry rules';\n\treturn `expire ${entries\n\t\t.map(\n\t\t\t([prefix, days]) => `${prefix} after ${days} day${days === 1 ? '' : 's'}`,\n\t\t)\n\t\t.join(', ')}`;\n}\n\n/** gkm's rules as the fields it sets, order-free. */\nfunction canonical(rules: readonly LifecycleRule[]): string {\n\treturn JSON.stringify(\n\t\trules\n\t\t\t.map((r) => ({\n\t\t\t\tid: r.ID,\n\t\t\t\tstatus: r.Status,\n\t\t\t\t// The legacy top-level `Prefix` reads the same as a filter's.\n\t\t\t\tprefix: r.Filter?.Prefix ?? r.Prefix ?? '',\n\t\t\t\tdays: r.Expiration?.Days ?? null,\n\t\t\t}))\n\t\t\t.sort((a, b) => (a.id ?? '').localeCompare(b.id ?? '')),\n\t);\n}\n","/**\n * Creating what the URLs name.\n *\n * Convergent and idempotent: every statement asks whether the thing exists\n * first, so reconciling repeatedly is free and a half-applied run recovers by\n * being run again. That property is what lets `gkm dev` do this on every start.\n *\n * The line the design draws is at data, not at side effects — this creates\n * databases, schemas, and buckets, and it never seeds, resets, or drops. A\n * developer who wants their data gone asks for it explicitly.\n *\n * Statement generation is separated from application for the reason the design\n * gives: the same DDL has to run in-process locally and from a provisioner in a\n * VPC, and one implementation is what stops \"works locally, fails deployed\".\n * When the role DDL lands in `@geekmidas/db` this delegates to it rather than\n * growing its own.\n */\n\nimport type { LifecycleRule } from '@aws-sdk/client-s3';\nimport { cacheTableStatements } from '@geekmidas/cache/postgres';\nimport { ownerRole, readerRole, roleStatements } from '@geekmidas/db/pg/roles';\nimport { cacheTable } from '@geekmidas/manifest';\nimport { mergeLifecycle } from '../providers/s3/lifecycle';\nimport { localRole, localRolePassword, rootDatabase } from './env';\nimport {\n\tminioNotificationRule,\n\tNOTIFICATION_RULE_PREFIX,\n} from './objectEvents';\nimport type { Plan, PlannedResource } from './plan';\n\n/** One thing to create, and how to tell whether it already exists. */\nexport interface Statement {\n\t/** The construct this is for, so a failure can name it. */\n\tid: string;\n\t/** What it does, in the line reconcile prints. */\n\tdescribe: string;\n\t/** The database to connect to. Absent means the cluster's default. */\n\tdatabase?: string;\n\t/**\n\t * Answers \"does this already exist\", parameterised.\n\t *\n\t * Absent for a statement that is idempotent in itself — a `GRANT` re-granting\n\t * what is already granted is a no-op, and checking would cost a round trip to\n\t * learn nothing. Those run every time and report unchanged.\n\t */\n\texists?: { sql: string; values: unknown[] };\n\t/**\n\t * The DDL, run only when `exists` returns nothing.\n\t *\n\t * Not parameterised, because identifiers cannot be — which is why\n\t * {@link quoteIdentifier} exists and why names are canonicalised long before\n\t * they reach here.\n\t */\n\tcreate: string;\n}\n\n/**\n * The Postgres work a plan implies.\n *\n * Databases before the schemas inside them, which `provisionOrder` already\n * guarantees by putting parents first.\n */\nexport function postgresStatements(\n\tplan: Plan,\n\t/**\n\t * Seeds the derived role passwords. The same project seeds the same\n\t * passwords, so a restart does not lock a developer out of their own data —\n\t * and two checkouts do not share a credential.\n\t */\n\tproject = '',\n\t/**\n\t * A deployed stage's random seed, salting the role passwords the way a\n\t * deploy does — see `localRolePassword`. Absent for the local stages.\n\t */\n\tseed?: string,\n): Statement[] {\n\tconst statements: Statement[] = [];\n\t// A cache's table, run once every database and its roles exist: a cache\n\t// can sort before the database it lives in (`Cache`, `Database`), and its\n\t// table cannot be looked for in a database not yet created.\n\tconst cacheTables: Statement[] = [];\n\n\tfor (const resource of plan.resources) {\n\t\tif (!resource.provisions || resource.container !== 'postgres') continue;\n\n\t\tif (resource.kind === 'database') {\n\t\t\tstatements.push({\n\t\t\t\tid: resource.id,\n\t\t\t\tdescribe: `database ${resource.name}`,\n\t\t\t\texists: {\n\t\t\t\t\tsql: 'SELECT 1 FROM pg_database WHERE datname = $1',\n\t\t\t\t\tvalues: [resource.name],\n\t\t\t\t},\n\t\t\t\t// `CREATE DATABASE` cannot run inside a transaction, which is why\n\t\t\t\t// each statement is applied on its own rather than batched.\n\t\t\t\tcreate: `CREATE DATABASE ${quoteIdentifier(resource.name)}`,\n\t\t\t});\n\n\t\t\t// After the database, never before: roles are cluster-scoped but their\n\t\t\t// grants are not, so every statement after the first two has to run\n\t\t\t// against a database that exists.\n\t\t\tif (resource.schema) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t...rolesFor(resource, resource.schema, plan, project, seed),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (resource.kind === 'database-schema' && resource.schema) {\n\t\t\t// The schema *and* the roles that reach it, from one generator shared\n\t\t\t// with the deploy target — the same DDL has to run in-process here and\n\t\t\t// from a provisioner in a VPC, and one implementation is what stops\n\t\t\t// \"works locally, fails deployed\".\n\t\t\tstatements.push(\n\t\t\t\t...rolesFor(resource, resource.schema, plan, project, seed),\n\t\t\t);\n\t\t}\n\n\t\t// A cache that lives in a database is a table in it, and a table is DDL —\n\t\t// so the owner creates it, not the handler's role, which may not create\n\t\t// anything. The same reason the driver does not do it lazily.\n\t\t//\n\t\t// `of` is the whole test: `planFor` resolves a `cache: 'db'` backend into\n\t\t// that edge before anything reads the plan, so a cache lands in a\n\t\t// database exactly one way and this does not have to know the config\n\t\t// existed.\n\t\tconst cacheHome =\n\t\t\tresource.kind === 'cache' && resource.of\n\t\t\t\t? plan.resources.find((r) => r.id === resource.of)\n\t\t\t\t: undefined;\n\n\t\tif (cacheHome) {\n\t\t\tcacheTables.push(...cacheTableDdl(resource, cacheHome, plan));\n\t\t}\n\n\t\t// A reader provisions nothing: it is a set of grants on an endpoint that\n\t\t// already exists, and falling back to the writer where no replica exists\n\t\t// stays safe because read-only is enforced by the role.\n\t}\n\n\treturn [...statements, ...cacheTables];\n}\n\n/**\n * A cache's table, in the schema the role that reads it resolves names in.\n *\n * Two things have to line up, and neither is the table's contents. The driver\n * names the table unqualified and lets the connection's `search_path` place it\n * — which the role carries — so creating it from the master connection, whose\n * path is `public`, leaves a table the application cannot see and a\n * `relation \"cache\" does not exist` on the first request. And the default\n * privileges that make a tenant's tables reachable are granted *for the owner\n * role*, so nothing covers a table the master created.\n *\n * Hence: qualified with the tenant's schema, handed to its owner, and granted\n * explicitly — `roleStatements` grants what exists at the time it runs, and\n * this table does not exist yet.\n *\n * A database that opted out of roles needs none of it: everything connects as\n * the master, whose `search_path` finds `public`, and the table it creates\n * there is the table it reads.\n */\nfunction cacheTableDdl(\n\tcache: PlannedResource,\n\thome: PlannedResource,\n\tplan: Plan,\n): Statement[] {\n\tconst database = rootDatabase(home, plan);\n\tconst schema = home.roles === false ? undefined : home.schema;\n\t// The same default the URL carries — `cacheTable` is read by both, so the\n\t// table a client reads and the table a target creates cannot drift.\n\tconst name = cache.table ?? cacheTable(cache.id);\n\tconst table = schema ? `${schema}.${name}` : name;\n\n\tconst created = cacheTableStatements({ table }).map((statement) => ({\n\t\tid: cache.id,\n\t\tdescribe: statement.describe,\n\t\tdatabase,\n\t\t...(statement.exists ? { exists: statement.exists } : {}),\n\t\tcreate: statement.sql,\n\t}));\n\n\tif (!schema) return created;\n\n\tconst runtime = localRole(home);\n\tconst owner = ownerRole(runtime);\n\tconst qualified = table\n\t\t.split('.')\n\t\t.map((part) => quoteIdentifier(part))\n\t\t.join('.');\n\n\treturn [\n\t\t...created,\n\t\t{\n\t\t\tid: cache.id,\n\t\t\tdescribe: `cache table ${table} is owned by ${owner}`,\n\t\t\tdatabase,\n\t\t\tcreate: `ALTER TABLE ${qualified} OWNER TO ${quoteIdentifier(owner)}`,\n\t\t},\n\t\t{\n\t\t\tid: cache.id,\n\t\t\tdescribe: `${runtime} may read and write ${table}`,\n\t\t\tdatabase,\n\t\t\tcreate:\n\t\t\t\t`GRANT SELECT, INSERT, UPDATE, DELETE ON ${qualified} ` +\n\t\t\t\t`TO ${quoteIdentifier(runtime)}`,\n\t\t},\n\t];\n}\n\n/**\n * The roles and schema for one database or tenant.\n *\n * Skipped entirely when the construct declared `roles: false` — the documented\n * downgrade, where both URLs fall back to the cluster's master credential. It\n * is a choice someone made rather than a default they got.\n */\nfunction rolesFor(\n\tresource: PlannedResource,\n\tschema: string,\n\tplan: Plan,\n\tproject: string,\n\tseed?: string,\n): Statement[] {\n\tif (resource.roles === false) return [];\n\n\tconst runtime = localRole(resource);\n\tconst owner = ownerRole(runtime);\n\n\t// A reader role only where something reads through one. Creating roles\n\t// nothing connects as is noise in `\\du` and one more thing to explain.\n\tconst reader = plan.resources.some(\n\t\t(r) => r.kind === 'database-reader' && r.of === resource.id,\n\t)\n\t\t? readerRole(runtime)\n\t\t: undefined;\n\n\treturn roleStatements({\n\t\truntime,\n\t\towner,\n\t\t...(reader ? { reader } : {}),\n\t\tschema,\n\t\t// A database's owner may create in it — trusted extensions; a tenant's\n\t\t// stays confined to its schema.\n\t\t...(resource.kind === 'database'\n\t\t\t? { database: rootDatabase(resource, plan) }\n\t\t\t: {}),\n\t\t...(resource.extensions ? { extensions: resource.extensions } : {}),\n\t\tpasswords: {\n\t\t\truntime: localRolePassword(project, plan, runtime, seed),\n\t\t\towner: localRolePassword(project, plan, owner, seed),\n\t\t\t...(reader\n\t\t\t\t? { reader: localRolePassword(project, plan, reader, seed) }\n\t\t\t\t: {}),\n\t\t},\n\t}).map((statement) => ({\n\t\tid: resource.id,\n\t\tdescribe: statement.describe,\n\t\t// Inside the parent's database — a tenant is a schema, never a database\n\t\t// of its own. Roles are cluster-scoped, but the grants are not, so all of\n\t\t// it has to run against the database the objects live in.\n\t\tdatabase: rootDatabase(resource, plan),\n\t\t...(statement.exists ? { exists: statement.exists } : {}),\n\t\tcreate: statement.sql,\n\t}));\n}\n\n/** The buckets a plan implies. */\nexport function bucketNames(plan: Plan): string[] {\n\treturn plan.resources\n\t\t.filter((r) => r.provisions && r.kind === 'objects')\n\t\t.map((r) => r.name);\n}\n\n/**\n * Quote an identifier for use in DDL.\n *\n * Names reaching here are already canonical and stage-suffixed, so this is\n * defence rather than sanitisation — but DDL cannot be parameterised, and an\n * unquoted identifier is the one place a name could ever be more than a name.\n */\nexport function quoteIdentifier(name: string): string {\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** What applying a statement did. */\nexport interface Applied {\n\tid: string;\n\tdescribe: string;\n\t/** False when it already existed — the converged case. */\n\tcreated: boolean;\n}\n\n/** The database operations the applier needs, so it can be run against a fake. */\nexport interface SqlClient {\n\t/** Run a query against one database, returning its rows. */\n\tquery(\n\t\tdatabase: string | undefined,\n\t\tsql: string,\n\t\tvalues?: unknown[],\n\t): Promise<unknown[]>;\n}\n\n/**\n * Apply the plan's Postgres statements.\n *\n * Each is checked before it is run, so this converges rather than erroring on a\n * second pass.\n */\nexport async function applyPostgres(\n\tclient: SqlClient,\n\tstatements: readonly Statement[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const statement of statements) {\n\t\t// No check means the statement is idempotent in itself — a GRANT\n\t\t// re-granting what is already granted is a no-op — so it runs and\n\t\t// reports unchanged, and a converged reconcile still says converged.\n\t\tif (!statement.exists) {\n\t\t\tawait client.query(statement.database, statement.create);\n\t\t\tapplied.push({\n\t\t\t\tid: statement.id,\n\t\t\t\tdescribe: statement.describe,\n\t\t\t\tcreated: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst rows = await client.query(\n\t\t\tstatement.database,\n\t\t\tstatement.exists.sql,\n\t\t\tstatement.exists.values,\n\t\t);\n\n\t\tif (rows.length > 0) {\n\t\t\tapplied.push({\n\t\t\t\tid: statement.id,\n\t\t\t\tdescribe: statement.describe,\n\t\t\t\tcreated: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.query(statement.database, statement.create);\n\t\tapplied.push({\n\t\t\tid: statement.id,\n\t\t\tdescribe: statement.describe,\n\t\t\tcreated: true,\n\t\t});\n\t}\n\n\treturn applied;\n}\n\n/**\n * What each bucket's open paths are, if anything serves it.\n *\n * Keyed by the *origin*, because that is where the policy lives: two servers\n * over one bucket contribute to one policy, so the patterns are unioned rather\n * than the last one winning.\n */\nexport function bucketPolicies(\n\tplan: Plan,\n): { bucket: string; open: string[] }[] {\n\tconst byBucket = new Map<string, Set<string>>();\n\n\tfor (const resource of plan.resources) {\n\t\tif (resource.kind !== 'file-server' || !resource.open?.length) continue;\n\n\t\tconst origin = plan.resources.find((r) => r.id === resource.of);\n\t\tif (!origin) continue;\n\n\t\tconst patterns = byBucket.get(origin.name) ?? new Set<string>();\n\t\tfor (const pattern of resource.open) patterns.add(pattern);\n\t\tbyBucket.set(origin.name, patterns);\n\t}\n\n\treturn [...byBucket]\n\t\t.map(([bucket, open]) => ({ bucket, open: [...open].sort() }))\n\t\t.sort((a, b) => a.bucket.localeCompare(b.bucket));\n}\n\n/**\n * What each bucket keeps, and for how long: the buckets that declare an\n * expiry, by their stage-scoped name.\n *\n * Every bucket in the plan, not only those that declare one, is what a\n * removed expiry needs — its rules are dropped from a bucket that no longer\n * asks for them — so a bucket with none is listed with an empty expiry.\n */\nexport function bucketLifecycles(\n\tplan: Plan,\n): { bucket: string; expire: Readonly<Record<string, number>> }[] {\n\treturn plan.resources\n\t\t.filter((r) => r.kind === 'objects' && r.provisions)\n\t\t.map((r) => ({ bucket: r.name, expire: r.expire ?? {} }))\n\t\t.sort((a, b) => a.bucket.localeCompare(b.bucket));\n}\n\n/**\n * One bucket's open paths as an S3 bucket policy.\n *\n * Anonymous `s3:GetObject` on the named prefixes and nothing else — which is\n * what \"open\" means everywhere: the server serves that path without a\n * signature, and the bucket stays private for everything else.\n *\n * One fidelity note, stated rather than discovered: an S3 policy resource's `*`\n * crosses `/`, so a single-star pattern is *wider* here than the construct's own\n * runtime check, which stops at a segment boundary. The construct is the\n * stricter of the two, so a key it refuses to serve unsigned is never one this\n * policy was relied on to refuse — but a key fetched directly, bypassing the\n * client, can be admitted by the policy where the client would have said no.\n * Prefer `**` where crossing segments is what you meant.\n */\nexport function bucketPolicy(bucket: string, open: readonly string[]): string {\n\treturn JSON.stringify({\n\t\tVersion: '2012-10-17',\n\t\tStatement: [\n\t\t\t{\n\t\t\t\tSid: 'GkmOpenPaths',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tPrincipal: { AWS: ['*'] },\n\t\t\t\tAction: ['s3:GetObject'],\n\t\t\t\tResource: open.map(\n\t\t\t\t\t(pattern) =>\n\t\t\t\t\t\t`arn:aws:s3:::${bucket}/${pattern.replace(/\\*\\*/g, '*')}`,\n\t\t\t\t),\n\t\t\t},\n\t\t],\n\t});\n}\n\n/**\n * The topics and queues to create on the AWS emulator.\n *\n * Only on the `sns` backend: pg-boss makes its own tables on first connect and\n * a RabbitMQ exchange is declared by the client, but an SNS topic and an SQS\n * queue must exist before anything can publish to them.\n */\nexport function carrierNames(plan: Plan): {\n\ttopics: string[];\n\tqueues: string[];\n} {\n\tif (plan.events !== 'sns') return { topics: [], queues: [] };\n\n\tconst named = (kind: 'topic' | 'queue') =>\n\t\tplan.resources.filter((r) => r.kind === kind).map((r) => r.name);\n\n\treturn { topics: named('topic'), queues: named('queue') };\n}\n\n/** The emulator operations the applier needs. Both creates are idempotent. */\nexport interface CarrierClient {\n\ttopicExists(name: string): Promise<boolean>;\n\tcreateTopic(name: string): Promise<void>;\n\tqueueExists(name: string): Promise<boolean>;\n\tcreateQueue(name: string): Promise<void>;\n}\n\n/** Create each topic and queue the plan names, skipping those that exist. */\nexport async function applyCarriers(\n\tclient: CarrierClient,\n\tcarriers: { topics: readonly string[]; queues: readonly string[] },\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const name of carriers.topics) {\n\t\tconst created = !(await client.topicExists(name));\n\t\tif (created) await client.createTopic(name);\n\t\tapplied.push({ id: name, describe: `topic ${name}`, created });\n\t}\n\tfor (const name of carriers.queues) {\n\t\tconst created = !(await client.queueExists(name));\n\t\tif (created) await client.createQueue(name);\n\t\tapplied.push({ id: name, describe: `queue ${name}`, created });\n\t}\n\n\treturn applied;\n}\n\n/** The Postgres databases the plan creates — each is a `CREATE DATABASE`. */\nexport function postgresDatabaseNames(plan: Plan): string[] {\n\treturn plan.resources\n\t\t.filter(\n\t\t\t(resource) =>\n\t\t\t\tresource.kind === 'database' &&\n\t\t\t\tresource.provisions &&\n\t\t\t\tresource.container === 'postgres',\n\t\t)\n\t\t.map((resource) => resource.name);\n}\n\n/**\n * Whether every one of these databases exists. A database dropped behind the\n * recorded state's back — by another checkout's test teardown, against the\n * same container — makes the state a lie, and only asking Postgres finds out.\n * Unreachable counts as missing: applying again is what finds out why.\n */\nexport async function databasesExist(\n\tclient: SqlClient,\n\tnames: readonly string[],\n): Promise<boolean> {\n\tif (names.length === 0) return true;\n\ttry {\n\t\tconst rows = (await client.query(\n\t\t\tundefined,\n\t\t\t'SELECT datname FROM pg_catalog.pg_database WHERE datname = ANY($1)',\n\t\t\t[names],\n\t\t)) as { datname: string }[];\n\t\treturn new Set(rows.map((row) => row.datname)).size === names.length;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** The object-storage operations the applier needs. */\nexport interface BucketClient {\n\texists(bucket: string): Promise<boolean>;\n\tcreate(bucket: string): Promise<void>;\n\t/** The bucket's current policy, or `undefined` where it has none. */\n\tpolicy(bucket: string): Promise<string | undefined>;\n\tsetPolicy(bucket: string, policy: string): Promise<void>;\n\t/** The bucket's notification configuration — empty where it has none. */\n\tnotification(bucket: string): Promise<BucketNotification>;\n\tsetNotification(\n\t\tbucket: string,\n\t\tnotification: BucketNotification,\n\t): Promise<void>;\n\t/** The bucket's lifecycle rules, or `undefined` where it has none. */\n\tlifecycle(bucket: string): Promise<LifecycleRule[] | undefined>;\n\t/** Replace its lifecycle with these rules — none removes it. */\n\tsetLifecycle(bucket: string, rules: LifecycleRule[]): Promise<void>;\n}\n\n/** A queue rule of a bucket's notification, as the S3 API shapes it. */\nexport interface BucketNotificationRule {\n\tId?: string;\n\tQueueArn?: string;\n\tEvents?: string[];\n\tFilter?: unknown;\n}\n\n/**\n * A bucket's notification configuration, as the S3 API shapes it. The topic\n * and function rules are carried through untouched: gkm writes queue rules —\n * which is what a MinIO webhook target is — and keeps whatever else is there.\n */\nexport interface BucketNotification {\n\tQueueConfigurations?: BucketNotificationRule[];\n\tTopicConfigurations?: unknown[];\n\tLambdaFunctionConfigurations?: unknown[];\n}\n\n/**\n * Point each watched bucket's events at its webhook target, and stop sending\n * an unwatched one's.\n *\n * Merged rather than written whole: only the rule gkm owns on a bucket\n * (`gkm-<Bucket>`) is added or removed, and every other rule — one somebody\n * added by hand — is kept. Compared before writing, so a converged reconcile\n * changes nothing.\n *\n * @param buckets - each bucket the plan names, by construct id and name\n * @param watched - the construct ids whose events are relayed\n */\nexport async function applyNotifications(\n\tclient: BucketClient,\n\tbuckets: readonly { id: string; name: string }[],\n\twatched: ReadonlySet<string>,\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const { id, name } of buckets) {\n\t\tconst current = await client.notification(name);\n\t\tconst queues = current.QueueConfigurations ?? [];\n\t\tconst others = queues.filter(\n\t\t\t(rule) => !rule.Id?.startsWith(NOTIFICATION_RULE_PREFIX),\n\t\t);\n\t\tconst wanted = watched.has(id)\n\t\t\t? [...others, minioNotificationRule(id)]\n\t\t\t: others;\n\n\t\t// Nothing of gkm's there, and nothing to add: not this bucket's concern.\n\t\tif (!watched.has(id) && others.length === queues.length) continue;\n\n\t\tconst describe = `object events from ${name}`;\n\t\tconst ours = queues.filter((rule) =>\n\t\t\trule.Id?.startsWith(NOTIFICATION_RULE_PREFIX),\n\t\t);\n\t\tconst converged = watched.has(id)\n\t\t\t? ours.length === 1 && sameRule(ours[0]!, minioNotificationRule(id))\n\t\t\t: ours.length === 0;\n\t\tif (converged) {\n\t\t\tapplied.push({ id: `${name}:events`, describe, created: false });\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.setNotification(name, {\n\t\t\t...current,\n\t\t\tQueueConfigurations: wanted,\n\t\t});\n\t\tapplied.push({ id: `${name}:events`, describe, created: true });\n\t}\n\n\treturn applied;\n}\n\n/**\n * Whether a rule read back says what gkm wrote: the same target, the same\n * events in any order, and no filter — the store may hand back an empty one.\n */\nfunction sameRule(\n\tcurrent: BucketNotificationRule,\n\twanted: BucketNotificationRule,\n): boolean {\n\tconst filter = current.Filter as\n\t\t| { Key?: { FilterRules?: unknown[] } }\n\t\t| undefined;\n\treturn (\n\t\tcurrent.Id === wanted.Id &&\n\t\tcurrent.QueueArn === wanted.QueueArn &&\n\t\tJSON.stringify([...(current.Events ?? [])].sort()) ===\n\t\t\tJSON.stringify([...(wanted.Events ?? [])].sort()) &&\n\t\t(filter?.Key?.FilterRules?.length ?? 0) === 0\n\t);\n}\n\n/**\n * Apply each bucket's expiry, beside whatever other rules it has, skipping\n * those already correct — the same merge the `s3` provider makes deployed.\n */\nexport async function applyLifecycles(\n\tclient: BucketClient,\n\tlifecycles: readonly {\n\t\tbucket: string;\n\t\texpire: Readonly<Record<string, number>>;\n\t}[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const { bucket, expire } of lifecycles) {\n\t\tconst merge = mergeLifecycle(await client.lifecycle(bucket), expire);\n\t\tconst id = `${bucket}:lifecycle`;\n\t\tconst describe = `${merge.describe} on ${bucket}`;\n\n\t\t// Nothing declared and nothing of gkm's there: not worth a line.\n\t\tif (!merge.changed && Object.keys(expire).length === 0) continue;\n\t\tif (!merge.changed) {\n\t\t\tapplied.push({ id, describe, created: false });\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.setLifecycle(bucket, merge.rules);\n\t\tapplied.push({ id, describe, created: true });\n\t}\n\n\treturn applied;\n}\n\n/**\n * Apply each served bucket's open-path policy, skipping those already correct.\n *\n * Compared as parsed JSON rather than as text: the same policy re-serialised\n * with different key order is the same policy, and rewriting it every reconcile\n * would report a change on every start.\n */\nexport async function applyPolicies(\n\tclient: BucketClient,\n\tpolicies: readonly { bucket: string; open: string[] }[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const { bucket, open } of policies) {\n\t\tconst wanted = bucketPolicy(bucket, open);\n\t\tconst describe = `open paths on ${bucket}`;\n\n\t\tif (equivalent(await client.policy(bucket), wanted)) {\n\t\t\tapplied.push({ id: `${bucket}:policy`, describe, created: false });\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.setPolicy(bucket, wanted);\n\t\tapplied.push({ id: `${bucket}:policy`, describe, created: true });\n\t}\n\n\treturn applied;\n}\n\n/** Whether two policy documents say the same thing. */\nfunction equivalent(current: string | undefined, wanted: string): boolean {\n\tif (!current) return false;\n\n\ttry {\n\t\treturn (\n\t\t\tJSON.stringify(JSON.parse(current)) === JSON.stringify(JSON.parse(wanted))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Create every bucket the plan names, skipping those that exist. */\nexport async function applyBuckets(\n\tclient: BucketClient,\n\tbuckets: readonly string[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const bucket of buckets) {\n\t\tif (await client.exists(bucket)) {\n\t\t\tapplied.push({\n\t\t\t\tid: bucket,\n\t\t\t\tdescribe: `bucket ${bucket}`,\n\t\t\t\tcreated: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.create(bucket);\n\t\tapplied.push({ id: bucket, describe: `bucket ${bucket}`, created: true });\n\t}\n\n\treturn applied;\n}\n","import { isAbsolute, join, relative, sep } from 'node:path';\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport { appKey } from '../workspace/derive.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/**\n * A Worker as a deploy unit: one process, one image, one service.\n *\n * A worker declares no app — it names a process, not a directory — so the\n * image is built from the app whose code holds its work: `gkm build` there\n * writes the worker's entry beside the server's, and the worker's image\n * copies that bundle out instead.\n */\nexport interface WorkerUnit {\n\t/** The construct, `Jobs`. */\n\tid: string;\n\t/** Its service and image name, `jobs`. */\n\tname: string;\n\t/** The backend app whose build writes its entry, `api`. */\n\tapp: string;\n}\n\n/** A worker with background work and no backend app to build it from. */\nexport class WorkerHasNoApp extends GkmError {\n\tconstructor(readonly worker: string) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' has crons, queues or subscribers, and the ` +\n\t\t\t\t`workspace has no backend app that builds a server to carry its ` +\n\t\t\t\t`entry. Declare a RestApi whose app holds the worker's code.`,\n\t\t);\n\t\tthis.name = 'WorkerHasNoApp';\n\t}\n}\n\n/** A worker whose service name an app already has. */\nexport class WorkerNameTaken extends GkmError {\n\tconstructor(\n\t\treadonly worker: string,\n\t\treadonly service: string,\n\t) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' runs as the service '${service}', and an app is ` +\n\t\t\t\t`already called that. Rename the worker — new Worker('${worker}Worker') ` +\n\t\t\t\t`— so each container has a name of its own.`,\n\t\t);\n\t\tthis.name = 'WorkerNameTaken';\n\t}\n}\n\n/**\n * The workers a workspace deploys — each one that has background work — and\n * the app each is built from.\n *\n * The host is the backend app whose directory holds the most of the worker's\n * files; one whose work sits outside every app (a shared `jobs/` directory)\n * is built by the first backend, by name, that generates a server. An app\n * with its own entry is never one — gkm's generators do not build it — and a\n * surface that serves itself, an auth server, only when it holds the work.\n *\n * @param background Each worker's files, from discovery's `background`.\n */\nexport function workerUnits(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tbackground: Readonly<Record<string, readonly string[]>>,\n): WorkerUnit[] {\n\tconst hosts = hostApps(workspace, manifest);\n\n\tconst units: WorkerUnit[] = [];\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration.kind !== 'worker') continue;\n\t\tconst files = background[id] ?? [];\n\t\tif (files.length === 0) continue;\n\n\t\tconst name = appKey(id);\n\t\tif (workspace.apps[name]) throw new WorkerNameTaken(id, name);\n\n\t\tconst host = hostFor(hosts, files);\n\t\tif (!host) throw new WorkerHasNoApp(id);\n\n\t\tunits.push({ id, name, app: host.name });\n\t}\n\n\treturn units.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/** The service and image name of a file server's processors: `assets-processors`. */\nexport function processorUnitName(fileServerId: string): string {\n\treturn `${appKey(fileServerId.replace(/Server$/, ''))}-processors`;\n}\n\n/** A file server's processors as a deploy unit: one process, one image. */\nexport interface ProcessorUnit {\n\t/** The file server's surface, `AssetsServer`. */\n\tid: string;\n\t/** Its service and image name, `assets-processors`. */\n\tname: string;\n\t/** The backend app whose build writes its entry, `api`. */\n\tapp: string;\n}\n\n/** A file server with processors and no backend app to build them from. */\nexport class ProcessorsHaveNoApp extends GkmError {\n\tconstructor(readonly fileServer: string) {\n\t\tsuper(\n\t\t\t`The file server '${fileServer}' has processors, and the workspace has ` +\n\t\t\t\t`no backend app that builds a server to carry their entry. Declare a ` +\n\t\t\t\t`RestApi whose app holds the processors' code.`,\n\t\t);\n\t\tthis.name = 'ProcessorsHaveNoApp';\n\t}\n}\n\n/**\n * The processor units a workspace deploys — each file server with processors\n * — and the app each is built from, chosen as a worker's is: the backend app\n * holding the most of its processors' files.\n */\nexport function processorUnits(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): ProcessorUnit[] {\n\tconst hosts = hostApps(workspace, manifest);\n\n\tconst units: ProcessorUnit[] = [];\n\tfor (const declaration of Object.values(manifest)) {\n\t\tif (declaration.kind !== 'file-server') continue;\n\t\tconst processors = declaration.processors ?? [];\n\t\tif (processors.length === 0) continue;\n\n\t\t// Each handler is its source, `apps/api/processors/thumbs.ts#thumbs`,\n\t\t// until a build replaces it.\n\t\tconst files = processors.map(({ handler }) => {\n\t\t\tconst file = handler.split('#')[0] ?? handler;\n\t\t\treturn isAbsolute(file) ? file : join(workspace.root, file);\n\t\t});\n\t\tconst host = hostFor(hosts, files);\n\t\tif (!host) throw new ProcessorsHaveNoApp(declaration.id);\n\n\t\tconst name = processorUnitName(declaration.id);\n\t\tif (workspace.apps[name]) throw new WorkerNameTaken(declaration.id, name);\n\t\tunits.push({ id: declaration.id, name, app: host.name });\n\t}\n\n\treturn units.sort((a, b) => a.name.localeCompare(b.name));\n}\n\ninterface HostApp {\n\tname: string;\n\troot: string;\n\tgenerated: boolean;\n}\n\n/** The backend apps whose builds generate a server, each where it lives. */\nfunction hostApps(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): HostApp[] {\n\treturn Object.entries(workspace.apps)\n\t\t.filter(([, app]) => app.type === 'backend' && !app.entry)\n\t\t.map(([name, app]) => {\n\t\t\tconst surface = Object.entries(manifest).find(\n\t\t\t\t([id, d]) =>\n\t\t\t\t\t(d.kind === 'rest-api' || d.kind === 'websocket-api') &&\n\t\t\t\t\tappKey(id) === name,\n\t\t\t)?.[1];\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\troot: isAbsolute(app.path) ? app.path : join(workspace.root, app.path),\n\t\t\t\t// A surface that serves itself — an auth server — has a build that\n\t\t\t\t// generates no server. A WebSocket surface always serves itself.\n\t\t\t\tgenerated: !(\n\t\t\t\t\tsurface?.kind === 'websocket-api' ||\n\t\t\t\t\t(surface?.kind === 'rest-api' && surface.servesItself === true)\n\t\t\t\t),\n\t\t\t};\n\t\t})\n\t\t.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * The app holding the most of these files; then one that generates a server;\n * then by name. None when no app holds any and none generates a server.\n */\nfunction hostFor(\n\thosts: readonly HostApp[],\n\tfiles: readonly string[],\n): HostApp | undefined {\n\tconst ranked = hosts\n\t\t.map((host) => ({\n\t\t\thost,\n\t\t\tholds: files.filter((file) => isUnder(file, host.root)).length,\n\t\t}))\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.holds - a.holds ||\n\t\t\t\tNumber(b.host.generated) - Number(a.host.generated),\n\t\t);\n\tconst host = ranked[0]?.host;\n\tif (!host || (ranked[0]!.holds === 0 && !host.generated)) return undefined;\n\treturn host;\n}\n\n/** Whether `file` is inside `dir`. */\nexport function isUnder(file: string, dir: string): boolean {\n\tconst rel = relative(dir, file);\n\treturn rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n\t\t? !rel.startsWith(`..${sep}`)\n\t\t: false;\n}\n","import {\n\ttype ConstructManifest,\n\ttype MobileAppDeclaration,\n\tPUBLIC_PREFIX,\n\tprovideKey,\n\tpublicEnvFor,\n\ttype SiteDeclaration,\n} from '@geekmidas/manifest';\n\n/**\n * What a site's image is built with — or a mobile app's EAS build: every\n * value its build reads, resolved for the stage, and so every `ARG` a site's\n * Dockerfile declares.\n *\n * - **Its edges' public values and its own address**, under the variant's\n * public prefix (`publicEnvFor`): what the bundler inlines.\n * - **Its own address under its own name** (`WEB_URL`). Server code runs at\n * build too — `next build` prerenders, and a page's `metadataBase` is read\n * then — and `gkm exec -- next build` has it locally, so the image build\n * must, or a site that builds locally fails in CI. A mobile app has no\n * address: its own value is its scheme (`APP_SCHEME`), which its\n * `app.config.ts` reads when EAS builds it.\n * - **Every stage secret already named for the bundle**: a key carrying the\n * variant's public prefix (`NEXT_PUBLIC_APP_STORE_URL` on a `next` site) was\n * declared public by whoever named it, so it is passed. Anything else is\n * not: a secret without the prefix never reaches a site's build.\n *\n * A value the stage resolves to nothing is left out rather than passed empty.\n * A derived value wins over a stage secret of the same name: the site's\n * addresses are the construct's, not a copy someone set.\n */\nexport function publicBuildValues(\n\tsite: SiteDeclaration | MobileAppDeclaration,\n\tmanifest: ConstructManifest,\n\tresolve: (key: string) => string | undefined,\n\tsecrets: Readonly<Record<string, string>>,\n): Record<string, string> {\n\tconst args: Record<string, string> = {};\n\n\tconst own = provideKey(site.id, site.kind === 'site' ? 'url' : 'scheme');\n\tconst ownValue = resolve(own);\n\tif (ownValue) args[own] = ownValue;\n\n\tfor (const [key, source] of Object.entries(publicEnvFor(site, manifest))) {\n\t\tconst value = resolve(source);\n\t\tif (value) args[key] = value;\n\t}\n\n\tconst prefix = PUBLIC_PREFIX[site.variant];\n\tfor (const [key, value] of Object.entries(secrets)) {\n\t\tif (key.startsWith(prefix) && args[key] === undefined && value) {\n\t\t\targs[key] = value;\n\t\t}\n\t}\n\n\treturn args;\n}\n","import { PUBLIC_ENV_PREFIXES } from '../workspace/publicEnv.js';\n\n/**\n * Set by a site's Dockerfile in its builder stage: this process is building\n * an image.\n *\n * Inside an image there is no stage to load secrets for and no local\n * container to resolve an address from — the public URLs the bundle inlines\n * arrived as the Dockerfile's build args, already in the environment. So\n * `gkm exec -- next build` there injects exactly those, and never the\n * `localhost` addresses a workspace resolves on a developer's machine.\n */\nexport const IMAGE_BUILD_ENV = 'GKM_IMAGE_BUILD';\n\n/** Whether this process is building an image. */\nexport function isImageBuild(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn env[IMAGE_BUILD_ENV] === '1';\n}\n\n/**\n * What `gkm exec` injects inside an image build: the public values its build\n * args set — every `NEXT_PUBLIC_*`, `VITE_*` and `EXPO_PUBLIC_*` — and\n * nothing read from a secrets store, a file or a container.\n */\nexport function imageBuildCredentials(\n\tenv: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n\tconst credentials: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (value === undefined) continue;\n\t\tif (PUBLIC_ENV_PREFIXES.some((prefix) => key.startsWith(prefix))) {\n\t\t\tcredentials[key] = value;\n\t\t}\n\t}\n\treturn credentials;\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, parse } from 'node:path';\nimport { externalsManifestName } from '../build/native';\nimport { IMAGE_BUILD_ENV } from '../exec/imageBuild';\nimport {\n\ttype ClientTelemetryDefault,\n\ttelemetryArgs,\n} from '../generators/clientTelemetry';\nimport type { CacheBackend, DockerConfig, GkmConfig } from '../types';\n\nexport type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';\n\n/**\n * The turbo every image prunes and builds with when the build root resolves\n * none of its own: a repository without turbo still needs `turbo prune` to\n * cut its slice of the workspace, and an unpinned `turbo` is whatever the\n * registry says on the day of the build.\n */\nexport const TURBO_VERSION = '2.5.4';\n\n/**\n * Caddy, which serves a static site's files. A 2.x tag, so a rebuild picks\n * up patch releases and never a major.\n */\nexport const STATIC_SITE_IMAGE = 'caddy:2.10-alpine';\n\n/**\n * The image generated Dockerfiles build on unless one is configured. Pinned to\n * a Node security release, not the floating `node:22-alpine` tag, so a cached\n * or older image can't put a build below the patched version — and the\n * Dockerfile says which version it runs.\n */\nexport const DEFAULT_BASE_IMAGE = 'node:22.23.4-alpine';\n\n/**\n * How an image is built: every template prunes the build root to the app's\n * slice, installs it, builds it and copies the result into a runner.\n *\n * Every path is relative to the build root — the directory that holds the\n * lockfile, which is the gkm workspace's root in a project of its own and the\n * monorepo's root when the workspace is nested inside one.\n */\nexport interface ImageTemplateOptions {\n\t/** The image the Dockerfile builds; informational. */\n\timageName?: string;\n\tbaseImage: string;\n\tport: number;\n\t/** The app's directory, relative to the build root. */\n\tappPath: string;\n\t/** The app's package, which turbo prunes to. */\n\tturboPackage: string;\n\t/** Detected package manager */\n\tpackageManager: PackageManager;\n\t/**\n\t * The exact version the build root's `packageManager` field names. Absent,\n\t * the image installs the package manager's latest.\n\t */\n\tpackageManagerVersion?: string;\n\t/** The turbo the build root resolves; `TURBO_VERSION` otherwise. */\n\tturboVersion?: string;\n\t/**\n\t * Whether the build root is a workspace of packages, which turbo prunes. A\n\t * single package is copied whole. Defaults to true.\n\t */\n\tmonorepo?: boolean;\n\t/**\n\t * Other packages the slice keeps: a gkm workspace nested in a monorepo is a\n\t * package of its own, holding the config and constructs the app is built\n\t * from.\n\t */\n\tprunePackages?: string[];\n\t/** The gkm workspace's root, relative to the build root. Defaults to `.` */\n\tgkmRoot?: string;\n\t/**\n\t * What under the gkm root the build reads besides the app — its config and\n\t * the directories its construct globs start in. `turbo prune` keeps\n\t * packages; these are copied beside them.\n\t */\n\tgkmPaths?: string[];\n\t/**\n\t * A site's: the backends whose typed clients it imports, each generated\n\t * in the builder — `gkm openapi --app <app>` from the backend's directory\n\t * (relative to the build root) — before the site is built.\n\t */\n\tclients?: {\n\t\tapp: string;\n\t\tpath: string;\n\t\t/**\n\t\t * Whether this client propagates trace context by default — passed as\n\t\t * `--telemetry [rate]`. Off when absent; the site's edge to a\n\t\t * `Telemetry` construct is what sets it.\n\t\t */\n\t\ttelemetry?: ClientTelemetryDefault;\n\t}[];\n}\n\nexport interface FrontendDockerfileOptions extends ImageTemplateOptions {\n\t/**\n\t * Public URL build args to include in the Dockerfile.\n\t * These will be declared as ARG and converted to ENV for the build.\n\t * Example: ['NEXT_PUBLIC_API_URL', 'NEXT_PUBLIC_AUTH_URL']\n\t */\n\tpublicUrlArgs?: string[];\n}\n\nconst LOCKFILES: [string, PackageManager][] = [\n\t['pnpm-lock.yaml', 'pnpm'],\n\t['bun.lockb', 'bun'],\n\t['yarn.lock', 'yarn'],\n\t['package-lock.json', 'npm'],\n];\n\n/**\n * Detect package manager from lockfiles\n * Walks up the directory tree to find lockfile (for monorepos)\n */\nexport function detectPackageManager(\n\tcwd: string = process.cwd(),\n): PackageManager {\n\tconst lockfile = findLockfilePath(cwd);\n\tif (!lockfile) return 'pnpm';\n\tconst name = lockfile.slice(dirname(lockfile).length + 1);\n\treturn LOCKFILES.find(([file]) => file === name)?.[1] ?? 'pnpm';\n}\n\n/**\n * Find the lockfile path by walking up the directory tree\n * Returns the full path to the lockfile, or null if not found\n */\nexport function findLockfilePath(cwd: string = process.cwd()): string | null {\n\tfor (const dir of upFrom(cwd)) {\n\t\tfor (const [lockfile] of LOCKFILES) {\n\t\t\tconst lockfilePath = join(dir, lockfile);\n\t\t\tif (existsSync(lockfilePath)) {\n\t\t\t\treturn lockfilePath;\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The directory every image is built from: the nearest at or above `cwd`\n * holding a lockfile or a `pnpm-workspace.yaml` — the package manager's root,\n * which is what an install resolves the workspace's dependencies against.\n *\n * In a project of its own that is the gkm workspace's root. A gkm workspace\n * nested inside a monorepo, whose dependencies are the monorepo's\n * `workspace:*` packages, is built from the monorepo's root. `cwd` itself\n * when neither is found.\n */\nexport function findBuildRoot(cwd: string = process.cwd()): string {\n\tfor (const dir of upFrom(cwd)) {\n\t\tif (existsSync(join(dir, 'pnpm-workspace.yaml'))) return dir;\n\t\tfor (const [lockfile] of LOCKFILES) {\n\t\t\tif (existsSync(join(dir, lockfile))) return dir;\n\t\t}\n\t}\n\treturn cwd;\n}\n\n/** `cwd` and every directory above it, the filesystem root last. */\nfunction upFrom(cwd: string): string[] {\n\tconst dirs: string[] = [];\n\tconst root = parse(cwd).root;\n\tlet dir = cwd;\n\twhile (dir !== root) {\n\t\tdirs.push(dir);\n\t\tdir = dirname(dir);\n\t}\n\tdirs.push(root);\n\treturn dirs;\n}\n\n/** What a build root builds its images with. */\nexport interface BuildTools {\n\tpackageManager: PackageManager;\n\t/** From `packageManager` in the build root's package.json, if set. */\n\tpackageManagerVersion?: string;\n\t/** The turbo the build root resolves, or `TURBO_VERSION`. */\n\tturboVersion: string;\n\t/** Whether the build root is a workspace of packages. */\n\tmonorepo: boolean;\n}\n\n/** The package manager, its version, turbo's and the shape of a build root. */\nexport function resolveBuildTools(buildRoot: string): BuildTools {\n\tconst pkg = readJson(join(buildRoot, 'package.json'));\n\tconst packageManager = detectPackageManager(buildRoot);\n\tconst field =\n\t\ttypeof pkg?.packageManager === 'string' ? pkg.packageManager : '';\n\t// `pnpm@10.30.1+sha512.…` — the hash is corepack's, the version is ours.\n\tconst match = /^([a-z]+)@(\\d[^+\\s]*)/.exec(field);\n\tconst packageManagerVersion =\n\t\tmatch && match[1] === packageManager ? match[2] : undefined;\n\n\treturn {\n\t\tpackageManager,\n\t\t...(packageManagerVersion ? { packageManagerVersion } : {}),\n\t\tturboVersion: resolveTurboVersion(buildRoot) ?? TURBO_VERSION,\n\t\tmonorepo:\n\t\t\texistsSync(join(buildRoot, 'pnpm-workspace.yaml')) ||\n\t\t\tpkg?.workspaces !== undefined,\n\t};\n}\n\n/**\n * The turbo version a build root resolves: what is installed, or what its\n * lockfile pins. Undefined when it has none.\n */\nexport function resolveTurboVersion(buildRoot: string): string | undefined {\n\tconst installed = readJson(\n\t\tjoin(buildRoot, 'node_modules', 'turbo', 'package.json'),\n\t);\n\tif (typeof installed?.version === 'string') return installed.version;\n\n\tconst read = (file: string) => {\n\t\ttry {\n\t\t\treturn readFileSync(join(buildRoot, file), 'utf-8');\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t};\n\n\tconst pnpm = read('pnpm-lock.yaml');\n\tconst fromPnpm = pnpm && /^ {2}'?turbo@(\\d[^:'(\\s]*)'?:/m.exec(pnpm);\n\tif (fromPnpm) return fromPnpm[1];\n\n\tconst npm = read('package-lock.json');\n\tif (npm) {\n\t\tconst lock = safeParse(npm) as {\n\t\t\tpackages?: Record<string, { version?: string }>;\n\t\t};\n\t\tconst version = lock?.packages?.['node_modules/turbo']?.version;\n\t\tif (version) return version;\n\t}\n\n\tconst yarn = read('yarn.lock');\n\tconst fromYarn =\n\t\tyarn && /^\"?turbo@[^\\n]*:\\n\\s+version:? \"?(\\d[^\"\\s]*)\"?/m.exec(yarn);\n\tif (fromYarn) return fromYarn[1];\n\n\treturn undefined;\n}\n\nfunction readJson(path: string): Record<string, unknown> | undefined {\n\ttry {\n\t\treturn safeParse(readFileSync(path, 'utf-8'));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction safeParse(text: string): Record<string, unknown> | undefined {\n\ttry {\n\t\tconst value = JSON.parse(text);\n\t\treturn value && typeof value === 'object' ? value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Get the lockfile name for a package manager\n */\nexport function getLockfileName(pm: PackageManager): string {\n\tconst lockfileMap: Record<PackageManager, string> = {\n\t\tpnpm: 'pnpm-lock.yaml',\n\t\tnpm: 'package-lock.json',\n\t\tyarn: 'yarn.lock',\n\t\tbun: 'bun.lockb',\n\t};\n\treturn lockfileMap[pm];\n}\n\n/**\n * Check if we're in a monorepo (lockfile is in a parent directory)\n */\nexport function isMonorepo(cwd: string = process.cwd()): boolean {\n\tconst lockfilePath = findLockfilePath(cwd);\n\tif (!lockfilePath) {\n\t\treturn false;\n\t}\n\n\t// Check if lockfile is in a parent directory (not in cwd)\n\tconst lockfileDir = dirname(lockfilePath);\n\treturn lockfileDir !== cwd;\n}\n\n/**\n * Check if turbo.json exists (walks up directory tree)\n */\nexport function hasTurboConfig(cwd: string = process.cwd()): boolean {\n\treturn upFrom(cwd).some((dir) => existsSync(join(dir, 'turbo.json')));\n}\n\n/**\n * Package manager specific commands. `version` pins what corepack (or npm,\n * for bun) installs; without it, the latest.\n */\nfunction getPmConfig(pm: PackageManager, version?: string) {\n\tconst configs = {\n\t\tpnpm: {\n\t\t\tinstall: `corepack enable && corepack prepare pnpm@${version ?? 'latest'} --activate`,\n\t\t\tlockfile: 'pnpm-lock.yaml',\n\t\t\t// turbo prune writes a lockfile for the slice, not the repository's,\n\t\t\t// so the install cannot be frozen to it.\n\t\t\tinstallCmd: 'pnpm install',\n\t\t\tcacheTarget: '/root/.local/share/pnpm/store',\n\t\t\tcacheId: 'pnpm',\n\t\t\trun: 'pnpm run',\n\t\t\tdlx: 'pnpm dlx',\n\t\t},\n\t\tnpm: {\n\t\t\tinstall: version ? `npm install -g npm@${version}` : '',\n\t\t\tlockfile: 'package-lock.json',\n\t\t\tinstallCmd: 'npm install',\n\t\t\tcacheTarget: '/root/.npm',\n\t\t\tcacheId: 'npm',\n\t\t\trun: 'npm run',\n\t\t\tdlx: 'npx --yes',\n\t\t},\n\t\tyarn: {\n\t\t\tinstall: `corepack enable && corepack prepare yarn@${version ?? 'stable'} --activate`,\n\t\t\tlockfile: 'yarn.lock',\n\t\t\tinstallCmd: 'yarn install',\n\t\t\tcacheTarget: '/root/.yarn/cache',\n\t\t\tcacheId: 'yarn',\n\t\t\trun: 'yarn run',\n\t\t\tdlx: 'yarn dlx',\n\t\t},\n\t\tbun: {\n\t\t\tinstall: `npm install -g bun@${version ?? 'latest'}`,\n\t\t\tlockfile: 'bun.lockb',\n\t\t\tinstallCmd: 'bun install',\n\t\t\tcacheTarget: '/root/.bun/install/cache',\n\t\t\tcacheId: 'bun',\n\t\t\trun: 'bun run',\n\t\t\tdlx: 'bunx',\n\t\t},\n\t};\n\treturn configs[pm];\n}\n\n/** What every template's first three stages need, resolved from options. */\nfunction layout(options: ImageTemplateOptions) {\n\tconst pm = getPmConfig(options.packageManager, options.packageManagerVersion);\n\tconst turbo = `${pm.dlx} turbo@${options.turboVersion ?? TURBO_VERSION}`;\n\tconst gkmRoot = options.gkmRoot ?? '.';\n\treturn {\n\t\tpm,\n\t\tturbo,\n\t\tinstallPm: pm.install ? `RUN ${pm.install}` : '',\n\t\tmonorepo: options.monorepo ?? true,\n\t\tgkmRoot,\n\t\t/** The app, absolute inside the image. */\n\t\tapp: `/app/${options.appPath}`.replace(/\\/\\.$/, ''),\n\t};\n}\n\n/**\n * The pruner stage: the build context cut to the app's slice, in turbo's\n * `out/` layout — `out/json` for the install, `out/full` for the build.\n *\n * `turbo prune` keeps the packages the app depends on and nothing else at\n * the root, so the root's own files (a `tsconfig.base.json` the packages\n * extend, the config their build reads) and what the gkm workspace keeps\n * outside any package are copied in beside them. A single package is copied\n * whole.\n */\n/**\n * The Node image every stage builds on, as a build argument: declared before\n * the first `FROM`, so each stage can read it, and defaulted to the configured\n * image. A compose file's `build.args`, or `docker build --build-arg`, picks\n * another version without regenerating the Dockerfile.\n */\nfunction nodeImageArg(options: ImageTemplateOptions): string {\n\treturn `# The Node image; override with --build-arg NODE_IMAGE=node:<version>-alpine\nARG NODE_IMAGE=${options.baseImage}`;\n}\n\nfunction prunerStage(options: ImageTemplateOptions): string {\n\tconst { pm, turbo, installPm, monorepo, gkmRoot } = layout(options);\n\tconst scopes = [options.turboPackage, ...(options.prunePackages ?? [])].join(\n\t\t' ',\n\t);\n\n\tif (!monorepo) {\n\t\treturn `${nodeImageArg(options)}\n\n# Stage 1: The build context, in the layout the stages below read\nFROM \\${NODE_IMAGE} AS pruner\nWORKDIR /app\nCOPY . .\nRUN mkdir -p /tmp/out/json /tmp/out/full && \\\\\n cp package.json /tmp/out/json/ && \\\\\n cp ${pm.lockfile} /tmp/out/ && \\\\\n cp -a . /tmp/out/full/ && \\\\\n mv /tmp/out ./out`;\n\t}\n\n\tconst gkmPaths = options.gkmPaths ?? [];\n\tconst nested = gkmRoot !== '.';\n\tconst dest = nested ? `/app/out/full/${gkmRoot}` : '/app/out/full';\n\tconst copyGkm = gkmPaths.length\n\t\t? `\n\n# What the gkm workspace keeps outside any package — its config, the\n# directories its constructs are declared in — beside the slice.\nRUN ${nested ? `cd ${gkmRoot} && ` : ''}for path in ${gkmPaths.join(' ')}; do \\\\\n if [ -e \"$path\" ]; then \\\\\n mkdir -p \"${dest}\" && cp -rn \"$path\" \"${dest}/\"; \\\\\n fi; \\\\\n done`\n\t\t: '';\n\n\treturn `${nodeImageArg(options)}\n\n# Stage 1: Prune the monorepo to the app's slice\nFROM \\${NODE_IMAGE} AS pruner\nWORKDIR /app\n${installPm}\nCOPY . .\nRUN ${turbo} prune ${scopes} --docker\n\n# The root's own files — the tsconfig the packages extend, the config their\n# build reads — which turbo prune leaves out. What the install itself reads\n# (registry config, local tarballs) goes beside the manifests too.\nRUN find . -maxdepth 1 -type f ! -name '${pm.lockfile}' ! -name package.json \\\\\n -exec cp -n {} out/full/ \\\\; && \\\\\n for file in .npmrc .yarnrc.yml .pnpmfile.cjs bunfig.toml *.tgz; do \\\\\n if [ -f \"$file\" ]; then cp \"$file\" out/json/; fi; \\\\\n done${copyGkm}`;\n}\n\n/** The deps stage: the slice's dependencies, installed from its lockfile. */\nfunction depsStage(options: ImageTemplateOptions): string {\n\tconst { pm, installPm } = layout(options);\n\treturn `# Stage 2: Install dependencies\nFROM \\${NODE_IMAGE} AS deps\nWORKDIR /app\n${installPm}\nCOPY --from=pruner /app/out/${pm.lockfile} ./\nCOPY --from=pruner /app/out/json/ ./\nRUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\\\\n ${pm.installCmd}`;\n}\n\n/**\n * The start of the builder stage: the slice's source over its dependencies,\n * and every workspace package the app depends on built from it.\n *\n * Nothing built on the host reaches the image — `.dockerignore` keeps every\n * `dist` out — so a workspace package (a CLI that is a sibling package) is\n * built here: turbo's build of the app's dependencies (`^build`) and nothing\n * else. The root's own `build` script is never run: the slice holds one app,\n * and a root `build` that is `gkm build` (what `gkm init` scaffolds) builds\n * every app the workspace declares, most of which are not in it. The app\n * itself is built after this, by `gkm build` or its framework.\n */\nfunction builderStage(\n\toptions: ImageTemplateOptions,\n\textra: { args?: string[] } = {},\n): string {\n\tconst { turbo, monorepo } = layout(options);\n\tconst args = extra.args ?? [];\n\tconst argLines = args.length\n\t\t? `\\n# Build-time args: public values the bundler inlines\\n${args.map((a) => `ARG ${a}=\"\"`).join('\\n')}\\n${args.map((a) => `ENV ${a}=$${a}`).join('\\n')}\\n`\n\t\t: '';\n\tconst scopes = [options.turboPackage, ...(options.prunePackages ?? [])];\n\tconst dependencies = monorepo\n\t\t? `\\n# The workspace packages the app depends on, built from source.\\nRUN ${turbo} run build ${scopes.map((s) => `--filter='${s}^...'`).join(' ')}`\n\t\t: '';\n\n\treturn `# Stage 3: Build\nFROM deps AS builder\nWORKDIR /app\n${argLines}\nCOPY --from=pruner /app/out/full/ ./${dependencies}`;\n}\n\n/**\n * The PATH a command in the app's directory runs with: the app's binaries,\n * then the gkm workspace's, then the root's — a nested workspace's apps\n * declare nothing, and its CLI is installed where its config is.\n */\nfunction binPath(options: ImageTemplateOptions): string {\n\tconst { app, gkmRoot } = layout(options);\n\tconst dirs = [\n\t\t`${app}/node_modules/.bin`,\n\t\tgkmRoot === '.' ? '' : `/app/${gkmRoot}/node_modules/.bin`,\n\t\t'/app/node_modules/.bin',\n\t].filter(Boolean);\n\treturn `PATH=\"${[...new Set(dirs)].join(':')}:$PATH\"`;\n}\n\n/**\n * Run the gkm CLI the app resolves, from the app's directory: node on its\n * `bin/gkm.mjs`, found the way Node resolves a package — up from the app.\n *\n * Not through `node_modules/.bin`: a CLI that is a workspace package has no\n * bin linked, since its files were not there when the slice's dependencies\n * were installed.\n */\nfunction gkmCommand(args: string): string {\n\treturn `GKM_BIN=\"$(node -e '${FIND_GKM_BIN}')\" && node \"$GKM_BIN\" ${args}`;\n}\n\n/** Prints the `bin/gkm.mjs` Node resolves from the cwd, or fails saying so. */\nconst FIND_GKM_BIN = `let d=process.cwd();const{existsSync:e}=require(\"fs\"),{dirname:u,join:j}=require(\"path\");for(;;){const p=j(d,\"node_modules/@geekmidas/cli/bin/gkm.mjs\");if(e(p)){console.log(p);break}if(u(d)===d){console.error(\"@geekmidas/cli is not installed where the app can resolve it\");process.exit(1)}d=u(d)}`;\n\n/**\n * What a site's builder does with the gkm workspace it carries, before its\n * framework builds it — all of it inside the image, nothing from the host:\n *\n * - `gkm` on the PATH: the CLI the workspace installs, so a build script that\n * is `gkm exec -- next build` runs. Resolved from the gkm root rather than\n * through `node_modules/.bin`, where a CLI that is a workspace package has\n * no bin linked.\n * - `GKM_IMAGE_BUILD`, which has `gkm exec` inject the build args above — the\n * stage's public URLs — and never load a secret or resolve a local address.\n * - each backend's typed client, generated from its endpoints at the\n * workspace root's `.gkm/client/`, where the site's tsconfig paths point.\n */\nfunction siteWorkspaceSteps(options: ImageTemplateOptions): string {\n\tconst { gkmRoot } = layout(options);\n\tconst root = `/app/${gkmRoot}`.replace(/\\/\\.$/, '');\n\tconst clients = options.clients ?? [];\n\tconst generate = clients.length\n\t\t? `\n\n# The typed client of each API this site calls, generated from its endpoints\n# into ${gkmRoot === '.' ? '' : `${gkmRoot}/`}.gkm/client/ — offline, with no secret and no container.\nRUN ${clients.map(({ app, path, telemetry }) => ['cd', `/app/${path}`, '&&', 'gkm', 'openapi', '--app', app, ...telemetryArgs(telemetry)].join(' ')).join(' && \\\\\\n ')}`\n\t\t: '';\n\n\treturn `# The gkm CLI the workspace installs, as \\`gkm\\`\nRUN cd ${root} && GKM_BIN=\"$(node -e '${FIND_GKM_BIN}')\" && \\\\\n { echo '#!/bin/sh'; echo \"exec node \\\\\"$GKM_BIN\\\\\" \\\\\"\\\\$@\\\\\"\"; } > /usr/local/bin/gkm && \\\\\n chmod +x /usr/local/bin/gkm\n\n# \\`gkm exec\\` in this build injects the build args, never a stage's secrets\nENV ${IMAGE_BUILD_ENV}=1${generate}`;\n}\n\n/**\n * Build the site with turbo. Loose env mode, so the task sees what the\n * Dockerfile set — the build args and `GKM_IMAGE_BUILD` — whatever the\n * project's turbo.json declares: the image's environment holds nothing else.\n */\nfunction siteBuild(options: ImageTemplateOptions): string {\n\tconst { turbo } = layout(options);\n\treturn `RUN ${turbo} run build --filter='${options.turboPackage}' --env-mode=loose`;\n}\n\n/**\n * The encrypted credentials, from a build secret — never an ARG, which is\n * recorded in the image history — written where the build embeds them from.\n * Two lines, ciphertext then IV; absent when the app has no secrets.\n *\n * A BuildKit secret is not part of the cache key, so `GKM_CIPHERTEXT_HASH`\n * (a hash of the ciphertext, not a secret) is: credentials encrypted under a\n * new key rebuild the layer that embeds them.\n */\nfunction credentialsStep(appDir: string, then: string): string {\n\treturn `ARG GKM_CIPHERTEXT_HASH=\"\"\nRUN --mount=type=secret,id=gkm_credentials,required=false \\\\\n echo \"credentials: \\${GKM_CIPHERTEXT_HASH:-none}\" && \\\\\n if [ -s /run/secrets/gkm_credentials ]; then \\\\\n mkdir -p ${appDir}/.gkm && \\\\\n sed -n 1p /run/secrets/gkm_credentials > ${appDir}/.gkm/credentials.enc && \\\\\n sed -n 2p /run/secrets/gkm_credentials > ${appDir}/.gkm/credentials.iv; \\\\\n fi && \\\\\n ${then} && \\\\\n rm -f ${appDir}/.gkm/credentials.enc ${appDir}/.gkm/credentials.iv`;\n}\n\n/**\n * The packages a bundle left out — its native ones, which load a binary built\n * for the platform they were installed on — installed for Linux beside it.\n * `gkm build` records them, at the versions it resolved, in a `package.json`\n * beside the bundle (`externalsManifestName`), so the image installs exactly\n * what the build left out: nothing, for most apps.\n */\nfunction externalsStages(\n\tappDir: string,\n\tbundle: string,\n): { stage: string; copy: string } {\n\treturn {\n\t\tstage: `\n# The packages the bundle leaves out, installed for Linux at the versions the\n# build resolved — and nothing else.\nFROM \\${NODE_IMAGE} AS externals\nWORKDIR /externals\nCOPY --from=builder ${appDir}/.gkm/server/dist/${externalsManifestName(bundle)} ./package.json\nRUN --mount=type=cache,id=npm,target=/root/.npm \\\\\n npm install --omit=dev --no-package-lock --no-audit --no-fund && \\\\\n mkdir -p node_modules\n`,\n\t\tcopy: `\\nCOPY --from=externals --chown=hono:nodejs /externals/node_modules ./node_modules`,\n\t};\n}\n\n/**\n * Generate .dockerignore file\n *\n * Written at the build root. Nothing built on the host may reach an image —\n * every image builds its packages from source — and nothing secret may reach\n * a build context.\n */\nexport function generateDockerignore(): string {\n\treturn `# Dependencies: installed in the image, for Linux\n**/node_modules\n.pnpm-store\n\n# Build output: every image builds from source, never from the host's\n**/dist\n**/.next\n**/.turbo\n**/.gkm\n\n# The key gkm build --stage encrypted secrets with: runtime env only, never\n# the build context\n**/master.key\n\n# gkm compose's stacks: each app's env file holds its stage's secrets\n**/.gkm/compose\n\n# IDE and editor\n.idea\n.vscode\n*.swp\n*.swo\n\n# Git\n.git\n\n# Logs\n*.log\nnpm-debug.log*\npnpm-debug.log*\n\n# Test files\ncoverage\n\n# Environment files (handle secrets separately)\n**/.env\n**/.env.*\n!**/.env.example\n\n# Docker files (don't copy recursively)\nDockerfile*\ndocker-compose*\n.dockerignore\n`;\n}\n\n/**\n * Generate docker-entrypoint.sh for custom startup logic\n */\nexport function generateDockerEntrypoint(): string {\n\treturn `#!/bin/sh\nset -e\n\n# Run any custom startup scripts here\n# Example: wait for database\n# until nc -z $DB_HOST $DB_PORT; do\n# echo \"Waiting for database...\"\n# sleep 1\n# done\n\n# Execute the main command\nexec \"$@\"\n`;\n}\n\n/**\n * Resolve Docker configuration from GkmConfig with defaults\n */\nexport function resolveDockerConfig(config: GkmConfig): Required<DockerConfig> {\n\tconst docker = config.docker ?? {};\n\n\treturn {\n\t\tregistry: docker.registry ?? '',\n\t\t// The project's name, from the config — what somebody types after\n\t\t// `docker pull` — never whatever the directory's package.json is called.\n\t\timageName: docker.imageName ?? config.name ?? 'api',\n\t\tbaseImage: docker.baseImage ?? DEFAULT_BASE_IMAGE,\n\t\tport: docker.port ?? 3000,\n\t};\n}\n\n/** A site's root answers its health check. */\nfunction siteHealthcheck(port: number): string {\n\treturn `# A site answers at its root; Docker, and Dokploy, read the container's\n# health from it rather than from the process merely running. 127.0.0.1, not\n# localhost: the server listens on IPv4, and localhost can resolve to ::1.\nHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\\\\n CMD wget -qO- http://127.0.0.1:${port}/ > /dev/null 2>&1 || exit 1`;\n}\n\n/**\n * Generate a Dockerfile for Next.js frontend apps using standalone output.\n *\n * Pruned at the build root, Next traces from there, so the standalone\n * server lands at `<appPath>/server.js` under `.next/standalone`.\n * @internal Exported for testing\n */\nexport function generateNextjsDockerfile(\n\toptions: FrontendDockerfileOptions,\n): string {\n\tconst {\n\t\tport,\n\t\tappPath,\n\t\tpublicUrlArgs = ['NEXT_PUBLIC_API_URL', 'NEXT_PUBLIC_AUTH_URL'],\n\t} = options;\n\n\treturn `# syntax=docker/dockerfile:1\n# Next.js standalone Dockerfile, built from a turbo-pruned slice\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options, { args: publicUrlArgs })}\n\n${siteWorkspaceSteps(options)}\n\n# Ensure public directory exists (may be empty for scaffolded projects)\nRUN mkdir -p ${appPath}/public\n\nENV NEXT_TELEMETRY_DISABLED=1\n\n# Build the application\n${siteBuild(options)}\n\n# The runner needs the standalone server; without it there is nothing to run.\nRUN if [ ! -d ${appPath}/.next/standalone ]; then \\\\\n echo \"${appPath}/.next/standalone was not built: set output: 'standalone' in next.config so the image can run the app without node_modules.\" >&2; \\\\\n exit 1; \\\\\n fi\n\n# Stage 4: Production\nFROM \\${NODE_IMAGE} AS runner\n\nWORKDIR /app\n\n# Install tini for proper signal handling\nRUN apk add --no-cache tini\n\n# Create non-root user\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 nextjs\n\n# Set environment\nENV NODE_ENV=production\nENV NEXT_TELEMETRY_DISABLED=1\nENV PORT=${port}\nENV HOSTNAME=\"0.0.0.0\"\n\n# The standalone server, with its static files and public directory beside it\nCOPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/standalone ./\nCOPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/static ./${appPath}/.next/static\nCOPY --from=builder --chown=nextjs:nodejs /app/${appPath}/public ./${appPath}/public\n\nUSER nextjs\n\nEXPOSE ${port}\n\n${siteHealthcheck(port)}\n\nENTRYPOINT [\"/sbin/tini\", \"--\"]\nCMD [\"node\", \"${appPath}/server.js\"]\n`;\n}\n\n/**\n * Generate a Dockerfile for a gkm backend: pruned, installed, and bundled by\n * `gkm build --provider server --production` inside the image. The runner is\n * `server.mjs` — plus the packages the bundle leaves out, which is none\n * unless it uses one with native code.\n * @internal Exported for testing\n */\nexport function generateBackendDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\thealthCheckPath?: string;\n\t\t/** The cache backend the entry registers, where not the target's. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\treturn gkmBundleDockerfile(options, {\n\t\ttitle: 'Backend Dockerfile',\n\t\tbundle: 'server.mjs',\n\t\tas: 'server.mjs',\n\t\texpose: true,\n\t});\n}\n\n/** The port a worker answers its health check on, inside its container. */\nexport const WORKER_PORT = 3000;\n\n/** The port a processor unit answers on, inside its container. */\nexport const PROCESSOR_PORT = 3000;\n\n/**\n * A Worker's image: the same build as its host app's backend — a pruned\n * slice, `gkm build --provider server --production` in the image, with the\n * encrypted credentials from the `gkm_credentials` secret — and a runner that\n * is the worker's bundle alone. It publishes nothing: its one route is the\n * health check the HEALTHCHECK asks.\n * @internal Exported for testing\n */\nexport function generateWorkerDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\t/** The worker's construct id, for the comment. */\n\t\tworker: string;\n\t\t/** Its bundle under the host app's `.gkm/server/dist`. */\n\t\tbundle: string;\n\t\thealthCheckPath?: string;\n\t\t/** The cache backend the entry registers, where not the target's. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\treturn gkmBundleDockerfile(options, {\n\t\ttitle: `Worker Dockerfile (${options.worker})`,\n\t\tbundle: options.bundle,\n\t\tas: 'worker.mjs',\n\t\texpose: false,\n\t});\n}\n\n/**\n * A file server's processor unit: its host app's build, and the unit's bundle\n * as the runner. Its native packages — `sharp` — are installed for the image's\n * platform beside the bundle, at the versions the build resolved, as for\n * every bundle.\n */\nexport function generateProcessorDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\t/** The file server's surface id, for the comment. */\n\t\tfileServer: string;\n\t\t/** Its bundle under the host app's `.gkm/server/dist`. */\n\t\tbundle: string;\n\t\thealthCheckPath?: string;\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\treturn gkmBundleDockerfile(options, {\n\t\ttitle: `Processors Dockerfile (${options.fileServer})`,\n\t\tbundle: options.bundle,\n\t\tas: 'processors.mjs',\n\t\texpose: true,\n\t});\n}\n\nfunction gkmBundleDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\thealthCheckPath?: string;\n\t\tcache?: CacheBackend;\n\t},\n\trunner: { title: string; bundle: string; as: string; expose: boolean },\n): string {\n\tconst { port, healthCheckPath = '/health' } = options;\n\tconst { app } = layout(options);\n\tconst externals = externalsStages(app, runner.bundle);\n\n\treturn `# syntax=docker/dockerfile:1\n# ${runner.title}: a turbo-pruned slice, bundled by gkm build in the image\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options)}\n\n# Bundle the production server, with the encrypted credentials embedded\n${credentialsStep(app, `cd ${app} && ${gkmCommand(`build --provider server --production${options.cache ? ` --cache ${options.cache}` : ''}`)}`)}\n${externals.stage}\n# Production\nFROM \\${NODE_IMAGE} AS runner\n\nWORKDIR /app\n\nRUN apk add --no-cache tini\n\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 hono\n\n# The bundled ${runner.as.replace(/\\.mjs$/, '')}\nCOPY --from=builder --chown=hono:nodejs ${app}/.gkm/server/dist/${runner.bundle} ./${runner.as === runner.bundle ? '' : runner.as}${externals.copy}\n\nENV NODE_ENV=production\nENV PORT=${port}\n\nHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\\\\n CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1\n\nUSER hono\n${runner.expose ? `\\nEXPOSE ${port}\\n` : ''}\nENTRYPOINT [\"/sbin/tini\", \"--\"]\nCMD [\"node\", \"${runner.as}\"]\n`;\n}\n\n/**\n * Options for entry-based Dockerfile generation.\n */\nexport interface EntryDockerfileOptions extends ImageTemplateOptions {\n\t/** Entry file path relative to app path (e.g., './src/index.ts') */\n\tentry: string;\n\t/** Health check path (default: '/health') */\n\thealthCheckPath?: string;\n}\n\n/**\n * Generate a Dockerfile for apps with a custom entry point.\n * Uses esbuild to bundle the entry point into dist/index.mjs with all dependencies.\n * This is used for apps that don't use gkm routes (e.g., Better Auth servers).\n * @internal Exported for testing\n */\nexport function generateEntryDockerfile(\n\toptions: EntryDockerfileOptions,\n): string {\n\tconst { port, entry, healthCheckPath = '/health' } = options;\n\tconst { app } = layout(options);\n\n\tconst esbuild = (defines: string) =>\n\t\t`esbuild ${entry} --bundle --platform=node --target=node22 --format=esm \\\\\n --outfile=dist/index.mjs --packages=bundle \\\\\n --banner:js='import { createRequire } from \"module\"; const require = createRequire(import.meta.url);'${defines}`;\n\n\treturn `# syntax=docker/dockerfile:1\n# Entry-based Dockerfile: a turbo-pruned slice, bundled by esbuild in the image\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options)}\n\n# Bundle the entry point with every dependency (dist/index.mjs), embedding the\n# encrypted credentials when there are any.\nARG GKM_CIPHERTEXT_HASH=\"\"\nRUN --mount=type=secret,id=gkm_credentials,required=false \\\\\n echo \"credentials: \\${GKM_CIPHERTEXT_HASH:-none}\" && \\\\\n cd ${app} && export ${binPath(options)} && \\\\\n if [ -s /run/secrets/gkm_credentials ]; then \\\\\n CREDS=$(sed -n 1p /run/secrets/gkm_credentials) && \\\\\n IV=$(sed -n 2p /run/secrets/gkm_credentials) && \\\\\n ${esbuild(` \\\\\n --define:__GKM_ENCRYPTED_CREDENTIALS__=\"\\\\\"$CREDS\\\\\"\" \\\\\n --define:__GKM_CREDENTIALS_IV__=\"\\\\\"$IV\\\\\"\"`)}; \\\\\n else \\\\\n ${esbuild('')}; \\\\\n fi\n\n# Production\nFROM \\${NODE_IMAGE} AS runner\n\nWORKDIR /app\n\nRUN apk add --no-cache tini\n\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 app\n\n# Copy bundled output only (no node_modules needed - fully bundled)\nCOPY --from=builder --chown=app:nodejs ${app}/dist/index.mjs ./\n\nENV NODE_ENV=production\nENV PORT=${port}\n\nHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\\\\n CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1\n\nUSER app\n\nEXPOSE ${port}\n\nENTRYPOINT [\"/sbin/tini\", \"--\"]\nCMD [\"node\", \"index.mjs\"]\n`;\n}\n\n/**\n * Generate a Dockerfile for Node-based SSR web frameworks (TanStack Start,\n * Remix). Builds with turbo, then runs the framework's production start\n * script.\n *\n * Public URL build args are declared so framework bundlers (Vite, Vinxi)\n * can inline them at build time. Per-framework prefix is the caller's job.\n * @internal Exported for testing\n */\nexport function generateNodeWebDockerfile(\n\toptions: FrontendDockerfileOptions,\n): string {\n\tconst { port, appPath } = options;\n\n\treturn `# syntax=docker/dockerfile:1\n# Node SSR web Dockerfile (TanStack Start / Remix), from a turbo-pruned slice\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options, { args: options.publicUrlArgs ?? [] })}\n\n${siteWorkspaceSteps(options)}\n\n${siteBuild(options)}\n\nFROM \\${NODE_IMAGE} AS runner\nWORKDIR /app\nRUN apk add --no-cache tini\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 app\n\n# Copy the whole built workspace — frameworks differ on output paths\nCOPY --from=builder --chown=app:nodejs /app/ ./\n\nENV NODE_ENV=production\nENV PORT=${port}\nENV HOSTNAME=\"0.0.0.0\"\n\nUSER app\nEXPOSE ${port}\n\n${siteHealthcheck(port)}\n\nENTRYPOINT [\"/sbin/tini\", \"--\"]\n# npm ships with node, and runs the start script whichever package manager\n# installed it: the runner needs no other.\nCMD [\"sh\", \"-c\", \"cd ${appPath} && npm start\"]\n`;\n}\n\n/**\n * Generate a Dockerfile for Vite SPA apps. Builds the static bundle with\n * turbo, then serves it with Caddy: Vite's hashed `/assets/*` cached for a\n * year, everything else — `index.html`, and every deep link that falls back\n * to it — revalidated on each request.\n * @internal Exported for testing\n */\nexport function generateViteStaticDockerfile(\n\toptions: FrontendDockerfileOptions,\n): string {\n\tconst { port, appPath } = options;\n\n\treturn `# syntax=docker/dockerfile:1\n# Vite SPA Dockerfile — a turbo-pruned slice built to static files, served by Caddy\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options, { args: options.publicUrlArgs ?? [] })}\n\n${siteWorkspaceSteps(options)}\n\n${siteBuild(options)}\n\nFROM ${STATIC_SITE_IMAGE} AS runner\n\nCOPY <<'EOF' /etc/caddy/Caddyfile\n{\n\tadmin off\n\tauto_https off\n\tpersist_config off\n}\n\n:${port} {\n\troot * /srv\n\tencode zstd gzip\n\n\t# Vite names every built asset by its content hash: a changed file is a\n\t# new URL, so the old one can be cached for good.\n\thandle /assets/* {\n\t\theader Cache-Control \"public, max-age=31536000, immutable\"\n\t\tfile_server\n\t}\n\n\t# index.html, and every client-side route that falls back to it, is\n\t# asked for again each time so a deploy is seen at once.\n\thandle {\n\t\theader Cache-Control \"no-cache\"\n\t\ttry_files {path} /index.html\n\t\tfile_server\n\t}\n}\nEOF\n\nCOPY --from=builder /app/${appPath}/dist /srv\n\nRUN addgroup -S -g 1001 site && adduser -S -u 1001 -G site site && \\\\\n chown -R site:site /data /config\n\nUSER site\n\nEXPOSE ${port}\n\n${siteHealthcheck(port)}\n\nCMD [\"caddy\", \"run\", \"--config\", \"/etc/caddy/Caddyfile\", \"--adapter\", \"caddyfile\"]\n`;\n}\n","/**\n * Where a workspace's images are built from, and what each is built with.\n *\n * Every builder of images — `gkm docker`, `gkm compose`, a Dokploy deploy —\n * builds from the same place with the same templates: the build root (the\n * package manager's root, at or above the gkm workspace), cut by `turbo\n * prune` to one app's slice. Nothing is built on the host.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { isAbsolute, join, relative, sep } from 'node:path';\nimport { GkmError } from '../errors';\nimport type { ClientTelemetryDefault } from '../generators/clientTelemetry.js';\nimport { allConstructGlobs } from '../workspace/index.js';\nimport type {\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport {\n\ttype BuildTools,\n\tDEFAULT_BASE_IMAGE,\n\tfindBuildRoot,\n\thasTurboConfig,\n\ttype ImageTemplateOptions,\n\tresolveBuildTools,\n} from './templates.js';\n\n/** A workspace of packages with no turbo.json, which every image prunes with. */\nexport class MonorepoNeedsTurbo extends GkmError {\n\tconstructor(readonly buildRoot: string) {\n\t\tsuper(\n\t\t\t`${buildRoot} is a workspace of packages, and its images are built from a turbo-pruned slice of it — but it has no turbo.json.\\n\\n` +\n\t\t\t\t'To fix this:\\n' +\n\t\t\t\t' 1. Install turbo: pnpm add -Dw turbo\\n' +\n\t\t\t\t` 2. Create turbo.json in ${buildRoot}\\n` +\n\t\t\t\t' 3. Run this command again\\n\\n' +\n\t\t\t\t'See: https://turbo.build/repo/docs/guides/tools/docker',\n\t\t);\n\t\tthis.name = 'MonorepoNeedsTurbo';\n\t}\n}\n\nexport interface ImageLayout {\n\t/** The build context of every image, absolute. */\n\tbuildRoot: string;\n\t/** The gkm workspace's root, relative to the build root (`.` when equal). */\n\tgkmRoot: string;\n\ttools: BuildTools;\n\t/**\n\t * The gkm workspace's own package, when it is nested in a monorepo as one:\n\t * kept in every backend's slice, since it holds the config, the constructs\n\t * and the dependencies they import.\n\t */\n\tworkspacePackage?: string;\n\t/** What under the gkm root a build reads besides the app's own directory. */\n\tgkmPaths: string[];\n}\n\n/**\n * Where a workspace's images are built from.\n *\n * Refuses a workspace of packages with no turbo.json — every image prunes\n * with turbo — so only a caller about to generate or build images asks.\n */\nexport function imageLayout(workspace: NormalizedWorkspace): ImageLayout {\n\tconst buildRoot = findBuildRoot(workspace.root);\n\tconst tools = resolveBuildTools(buildRoot);\n\tif (tools.monorepo && !hasTurboConfig(buildRoot)) {\n\t\tthrow new MonorepoNeedsTurbo(buildRoot);\n\t}\n\n\tconst gkmRoot = toPosix(relative(buildRoot, workspace.root)) || '.';\n\tconst workspacePackage =\n\t\tgkmRoot !== '.' ? packageName(workspace.root) : undefined;\n\n\treturn {\n\t\tbuildRoot,\n\t\tgkmRoot,\n\t\ttools,\n\t\t...(workspacePackage ? { workspacePackage } : {}),\n\t\tgkmPaths: ['gkm.config.*', ...constructRoots(workspace)],\n\t};\n}\n\n/**\n * How a compose file builds an app: the build root as the context, relative\n * to the directory the compose file is in, and the Dockerfile — written under\n * the gkm root — relative to that context, which is what compose resolves\n * `dockerfile` against.\n */\nexport function composeBuildPaths(options: {\n\t/** The directory the compose file is in, absolute. */\n\tcomposeDir: string;\n\tbuildRoot: string;\n\tworkspaceRoot: string;\n\t/** The Dockerfile, relative to the gkm workspace's root. */\n\tdockerfile: string;\n}): { context: string; dockerfile: string } {\n\tconst { composeDir, buildRoot, workspaceRoot, dockerfile } = options;\n\treturn {\n\t\tcontext: toPosix(relative(composeDir, buildRoot)) || '.',\n\t\tdockerfile: toPosix(join(relative(buildRoot, workspaceRoot), dockerfile)),\n\t};\n}\n\n/** A path under the gkm root, as the build root sees it. */\nexport function fromBuildRoot(layout: ImageLayout, path: string): string {\n\tif (layout.gkmRoot === '.') return toPosix(path);\n\tconst joined = toPosix(join(layout.gkmRoot, path));\n\treturn joined === '' ? '.' : joined;\n}\n\n/** Everything a template needs about one app, relative to the build root. */\nexport function appImageOptions(\n\tlayout: ImageLayout,\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\tworkspaceRoot: string,\n\t/**\n\t * Every app in the workspace: a site's image generates the client of each\n\t * backend it depends on, so it has to know where they are.\n\t */\n\tapps: Readonly<Record<string, NormalizedAppConfig>> = {},\n\t/**\n\t * Whether a site's clients propagate trace context, at what rate — set\n\t * from its edge to a `Telemetry` construct and the stage's sample rate.\n\t */\n\tclientTelemetry?: ClientTelemetryDefault,\n): ImageTemplateOptions {\n\tconst turboPackage =\n\t\tpackageName(\n\t\t\tisAbsolute(app.path) ? app.path : join(workspaceRoot, app.path),\n\t\t) ?? appName;\n\treturn {\n\t\timageName: appName,\n\t\tbaseImage: DEFAULT_BASE_IMAGE,\n\t\tport: app.port,\n\t\tappPath: fromBuildRoot(layout, app.path),\n\t\tturboPackage,\n\t\tpackageManager: layout.tools.packageManager,\n\t\t...(layout.tools.packageManagerVersion\n\t\t\t? { packageManagerVersion: layout.tools.packageManagerVersion }\n\t\t\t: {}),\n\t\tturboVersion: layout.tools.turboVersion,\n\t\tmonorepo: layout.tools.monorepo,\n\t\tgkmRoot: layout.gkmRoot,\n\t\t// A backend is built by gkm, from the workspace's config and constructs.\n\t\t// So is half of a site: the typed client it imports is generated from\n\t\t// the endpoints of the backends it depends on, in its image, before its\n\t\t// bundler runs — so it carries the same workspace, and those backends'\n\t\t// packages for what their endpoints import.\n\t\t...(app.type === 'backend'\n\t\t\t? {\n\t\t\t\t\tgkmPaths: layout.gkmPaths,\n\t\t\t\t\t...(layout.workspacePackage &&\n\t\t\t\t\tlayout.workspacePackage !== turboPackage\n\t\t\t\t\t\t? { prunePackages: [layout.workspacePackage] }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}\n\t\t\t: app.type === 'web'\n\t\t\t\t? siteWorkspace(\n\t\t\t\t\t\tlayout,\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\tapps,\n\t\t\t\t\t\tworkspaceRoot,\n\t\t\t\t\t\tturboPackage,\n\t\t\t\t\t\tclientTelemetry,\n\t\t\t\t\t)\n\t\t\t\t: {}),\n\t};\n}\n\n/**\n * What a site's image carries of the gkm workspace: its config and construct\n * directories, the workspace's own package where it is nested in a monorepo\n * (it holds the CLI), and each backend the site calls — whose endpoints its\n * client is generated from, and whose package their imports resolve in.\n */\nfunction siteWorkspace(\n\tlayout: ImageLayout,\n\tsite: NormalizedAppConfig,\n\tapps: Readonly<Record<string, NormalizedAppConfig>>,\n\tworkspaceRoot: string,\n\tturboPackage: string,\n\tclientTelemetry?: ClientTelemetryDefault,\n): Pick<ImageTemplateOptions, 'gkmPaths' | 'prunePackages' | 'clients'> {\n\tconst clients = siteClients(site, apps);\n\tconst packages = new Set<string>();\n\tif (layout.workspacePackage) packages.add(layout.workspacePackage);\n\tfor (const { app } of clients) {\n\t\tconst backend = apps[app]!;\n\t\tconst name = packageName(\n\t\t\tisAbsolute(backend.path)\n\t\t\t\t? backend.path\n\t\t\t\t: join(workspaceRoot, backend.path),\n\t\t);\n\t\tif (name) packages.add(name);\n\t}\n\tpackages.delete(turboPackage);\n\n\treturn {\n\t\tgkmPaths: layout.gkmPaths,\n\t\t...(packages.size > 0 ? { prunePackages: [...packages].sort() } : {}),\n\t\t...(clients.length > 0\n\t\t\t? {\n\t\t\t\t\tclients: clients.map(({ app }) => ({\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\tpath: fromBuildRoot(layout, apps[app]!.path),\n\t\t\t\t\t\t...(clientTelemetry ? { telemetry: clientTelemetry } : {}),\n\t\t\t\t\t})),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * The backends whose clients a site imports: each it depends on that gkm\n * builds from endpoints — not one with an entry of its own, and not one that\n * turned OpenAPI off.\n */\nexport function siteClients(\n\tsite: NormalizedAppConfig,\n\tapps: Readonly<Record<string, NormalizedAppConfig>>,\n): { app: string }[] {\n\treturn site.dependencies\n\t\t.filter((name) => {\n\t\t\tconst app = apps[name];\n\t\t\tif (!app || app.type !== 'backend' || app.entry) return false;\n\t\t\tif (app.openapi === false) return false;\n\t\t\tif (typeof app.openapi === 'object' && app.openapi.enabled === false)\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t})\n\t\t.sort()\n\t\t.map((app) => ({ app }));\n}\n\n/**\n * The directories the workspace's construct globs start in, relative to its\n * root: `./constructs/**\\/*.ts` reads from `constructs`.\n */\nexport function constructRoots(workspace: NormalizedWorkspace): string[] {\n\tconst roots = new Set<string>();\n\tfor (const glob of allConstructGlobs(workspace)) {\n\t\tconst rel = toPosix(relative(workspace.root, glob));\n\t\tif (!rel || rel.startsWith('..')) continue;\n\t\tconst first = rel.split('/')[0]!;\n\t\tif (/[*?{}[\\]!]/.test(first)) continue;\n\t\troots.add(first);\n\t}\n\treturn [...roots].sort();\n}\n\nfunction packageName(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n\t\treturn typeof pkg.name === 'string' ? pkg.name : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction toPosix(path: string): string {\n\treturn path.split(sep).join('/');\n}\n","/**\n * The real Postgres and MinIO clients the applier runs against.\n *\n * Kept apart from `provision.ts` so the rules there — what gets created, in what\n * order, and never dropping anything — are asserted against fakes, while the\n * drivers live here where there is nothing to assert but wiring.\n *\n * Both are constructed from the same local addresses the env writer composes,\n * so the applier cannot end up talking to a different container than the app.\n */\n\nimport {\n\tCreateBucketCommand,\n\tDeleteBucketLifecycleCommand,\n\tGetBucketLifecycleConfigurationCommand,\n\tGetBucketNotificationConfigurationCommand,\n\tGetBucketPolicyCommand,\n\tHeadBucketCommand,\n\tPutBucketLifecycleConfigurationCommand,\n\tPutBucketNotificationConfigurationCommand,\n\tPutBucketPolicyCommand,\n\tS3Client,\n} from '@aws-sdk/client-s3';\nimport {\n\tCreateTopicCommand,\n\tGetTopicAttributesCommand,\n\tSNSClient,\n} from '@aws-sdk/client-sns';\nimport {\n\tCreateQueueCommand,\n\tGetQueueUrlCommand,\n\tSQSClient,\n} from '@aws-sdk/client-sqs';\nimport { Client } from 'pg';\nimport { CLUSTER_DATABASE } from './compose';\nimport {\n\tEMULATOR_REGION,\n\temulatorEndpoint,\n\temulatorTopicArn,\n} from './emulator';\nimport type { ContainerCredentials, Login } from './localCredentials';\nimport type {\n\tBucketClient,\n\tBucketNotification,\n\tCarrierClient,\n\tSqlClient,\n} from './provision';\n\n/**\n * A Postgres client that opens one connection per database it is asked about.\n *\n * `CREATE DATABASE` cannot run from a connection to the database being created,\n * and a schema must be created from inside its own database — so the database is\n * part of each query rather than fixed when the client is built.\n */\nexport function pgClient(\n\tport: number,\n\t/**\n\t * The cluster's superuser: the workspace's local login, or the one a\n\t * `gkm compose` stack serving a deployed stage derives.\n\t */\n\tlogin: Login,\n): SqlClient {\n\treturn {\n\t\tasync query(database, sql, values) {\n\t\t\tconst client = new Client({\n\t\t\t\thost: 'localhost',\n\t\t\t\tport,\n\t\t\t\tuser: login.user,\n\t\t\t\tpassword: login.password,\n\t\t\t\t// The cluster's own database, which every cluster has. Connecting\n\t\t\t\t// to it is what makes `CREATE DATABASE` possible at all.\n\t\t\t\tdatabase: database ?? CLUSTER_DATABASE,\n\t\t\t});\n\n\t\t\tawait client.connect();\n\t\t\ttry {\n\t\t\t\tconst result = await client.query(sql, values as never[]);\n\t\t\t\treturn result.rows;\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** A bucket client pointed at a MinIO on this machine. */\nexport function bucketClient(\n\tport: number,\n\t/**\n\t * Its root login: the workspace's local one, or the one a `gkm compose`\n\t * stack serving a deployed stage derives.\n\t */\n\tcredentials: Login,\n): BucketClient {\n\tconst s3 = new S3Client({\n\t\tregion: 'us-east-1',\n\t\tendpoint: `http://localhost:${port}`,\n\t\t// MinIO serves buckets as paths, not as subdomains of the endpoint.\n\t\tforcePathStyle: true,\n\t\tcredentials: {\n\t\t\taccessKeyId: credentials.user,\n\t\t\tsecretAccessKey: credentials.password,\n\t\t},\n\t});\n\n\treturn {\n\t\tasync exists(bucket) {\n\t\t\ttry {\n\t\t\t\tawait s3.send(new HeadBucketCommand({ Bucket: bucket }));\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\t// Missing, or not reachable. Creating is idempotent enough that\n\t\t\t\t// treating both as \"missing\" is safe.\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync create(bucket) {\n\t\t\tawait s3.send(new CreateBucketCommand({ Bucket: bucket }));\n\t\t},\n\n\t\tasync policy(bucket) {\n\t\t\ttry {\n\t\t\t\tconst result = await s3.send(\n\t\t\t\t\tnew GetBucketPolicyCommand({ Bucket: bucket }),\n\t\t\t\t);\n\t\t\t\treturn result.Policy;\n\t\t\t} catch {\n\t\t\t\t// No policy, or the bucket is not reachable. Both mean there is\n\t\t\t\t// nothing to compare against, and writing one is idempotent.\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\tasync setPolicy(bucket, policy) {\n\t\t\tawait s3.send(\n\t\t\t\tnew PutBucketPolicyCommand({ Bucket: bucket, Policy: policy }),\n\t\t\t);\n\t\t},\n\n\t\tasync lifecycle(bucket) {\n\t\t\ttry {\n\t\t\t\tconst result = await s3.send(\n\t\t\t\t\tnew GetBucketLifecycleConfigurationCommand({ Bucket: bucket }),\n\t\t\t\t);\n\t\t\t\treturn result.Rules;\n\t\t\t} catch (error) {\n\t\t\t\t// No lifecycle is MinIO's ordinary answer for a bucket with none;\n\t\t\t\t// anything else — unreachable, refused — is not \"none\".\n\t\t\t\tif (\n\t\t\t\t\t(error as { name?: string }).name === 'NoSuchLifecycleConfiguration'\n\t\t\t\t) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\tasync setLifecycle(bucket, rules) {\n\t\t\tif (rules.length === 0) {\n\t\t\t\tawait s3.send(new DeleteBucketLifecycleCommand({ Bucket: bucket }));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait s3.send(\n\t\t\t\tnew PutBucketLifecycleConfigurationCommand({\n\t\t\t\t\tBucket: bucket,\n\t\t\t\t\tLifecycleConfiguration: { Rules: rules },\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\tasync notification(bucket) {\n\t\t\tconst { $metadata: _, ...notification } = await s3.send(\n\t\t\t\tnew GetBucketNotificationConfigurationCommand({ Bucket: bucket }),\n\t\t\t);\n\t\t\treturn notification as BucketNotification;\n\t\t},\n\n\t\tasync setNotification(bucket, notification) {\n\t\t\tawait s3.send(\n\t\t\t\tnew PutBucketNotificationConfigurationCommand({\n\t\t\t\t\tBucket: bucket,\n\t\t\t\t\tNotificationConfiguration: notification as never,\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/** A topic and queue client pointed at the local AWS emulator. */\nexport function carrierClient(\n\tport: number,\n\tcredentials: ContainerCredentials['emulator'],\n): CarrierClient {\n\tconst config = {\n\t\tregion: EMULATOR_REGION,\n\t\tendpoint: emulatorEndpoint(port),\n\t\tcredentials,\n\t};\n\tconst sns = new SNSClient(config);\n\tconst sqs = new SQSClient(config);\n\n\treturn {\n\t\tasync topicExists(name) {\n\t\t\ttry {\n\t\t\t\tawait sns.send(\n\t\t\t\t\tnew GetTopicAttributesCommand({ TopicArn: emulatorTopicArn(name) }),\n\t\t\t\t);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\t// Missing, or not reachable; creating is idempotent either way.\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync createTopic(name) {\n\t\t\tawait sns.send(new CreateTopicCommand({ Name: name }));\n\t\t},\n\n\t\tasync queueExists(name) {\n\t\t\ttry {\n\t\t\t\tawait sqs.send(new GetQueueUrlCommand({ QueueName: name }));\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync createQueue(name) {\n\t\t\tawait sqs.send(new CreateQueueCommand({ QueueName: name }));\n\t\t},\n\t};\n}\n","/**\n * The real Docker, behind the small interface reconcile needs.\n *\n * Shells out to `docker compose` rather than talking to the daemon socket: it is\n * what a developer runs by hand when something is wrong, so the two cannot\n * disagree, and it keeps Docker out of this package's dependencies.\n *\n * Every call that acts is scoped to the generated compose file. Nothing here\n * can touch a container this project did not generate; `publisher` only reads\n * who holds a port.\n */\n\nimport { execFile, spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { Docker } from './index';\n\nconst run = promisify(execFile);\n\n/**\n * The generated file, then the project's own if it has one.\n *\n * Merged in that order so the project's wins — an `image:` there pins a\n * container this file derived, and a service there is added beside them.\n */\nexport function composeFiles(composePath: string): string[] {\n\tconst project = join(dirname(composePath), 'docker-compose.yml');\n\treturn ['-f', composePath, ...(existsSync(project) ? ['-f', project] : [])];\n}\n\n/** How long to wait for containers to pass their health checks. */\nconst HEALTH_TIMEOUT_MS = 120_000;\n\n/** `docker compose up` exited unsuccessfully; its own output said why. */\nexport class ComposeUpFailed extends Error {\n\tconstructor(\n\t\treadonly services: readonly string[],\n\t\treadonly code: number | null,\n\t) {\n\t\tsuper(\n\t\t\t`docker compose could not start ${services.join(', ')} (exit ${code ?? 'signal'}). Its output above names the container; \\`docker compose logs <service>\\` shows why it stopped.`,\n\t\t);\n\t\tthis.name = 'ComposeUpFailed';\n\t}\n}\n\n/** Run compose with its output on this terminal rather than captured. */\nfunction shown(args: readonly string[], services: readonly string[]) {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn('docker', args, {\n\t\t\tstdio: ['ignore', 'inherit', 'inherit'],\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) =>\n\t\t\tcode === 0 ? resolve() : reject(new ComposeUpFailed(services, code)),\n\t\t);\n\t});\n}\n\nexport const dockerCli: Docker = {\n\tasync publishedPort(composePath, service, inside) {\n\t\ttry {\n\t\t\tconst { stdout } = await run('docker', [\n\t\t\t\t'compose',\n\t\t\t\t...composeFiles(composePath),\n\t\t\t\t'port',\n\t\t\t\tservice,\n\t\t\t\tString(inside),\n\t\t\t]);\n\n\t\t\t// `0.0.0.0:54321` — the part after the last colon is the host port.\n\t\t\tconst port = Number(stdout.trim().split(':').pop());\n\n\t\t\treturn Number.isFinite(port) && port > 0 ? port : undefined;\n\t\t} catch {\n\t\t\t// Not running, or no such service. Both mean \"nothing to reuse\".\n\t\t\treturn undefined;\n\t\t}\n\t},\n\n\tasync publisher(port) {\n\t\ttry {\n\t\t\t// Not scoped to the compose file: the point is to name whoever holds\n\t\t\t// the port, which is usually another project.\n\t\t\tconst { stdout } = await run('docker', [\n\t\t\t\t'ps',\n\t\t\t\t'--filter',\n\t\t\t\t`publish=${port}`,\n\t\t\t\t'--format',\n\t\t\t\t'{{.Label \"com.docker.compose.project\"}}',\n\t\t\t]);\n\n\t\t\treturn stdout.trim().split('\\n')[0] || undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t},\n\n\tasync up(composePath, services, options = {}) {\n\t\tconst args = [\n\t\t\t'compose',\n\t\t\t...composeFiles(composePath),\n\t\t\t'up',\n\t\t\t'-d',\n\t\t\t// Recreate anything whose definition moved — a changed image pin is\n\t\t\t// exactly the case the hash detects, and leaving the old container\n\t\t\t// running would make the reconcile a lie.\n\t\t\t'--remove-orphans',\n\t\t\t'--wait',\n\t\t\t`--wait-timeout=${Math.floor(HEALTH_TIMEOUT_MS / 1000)}`,\n\t\t\t...services,\n\t\t];\n\n\t\tif (options.show) return shown(args, services);\n\t\tawait run('docker', args);\n\t},\n\n\tasync copyOut(composePath, service, from, to) {\n\t\tawait mkdir(dirname(to), { recursive: true });\n\t\tawait run('docker', [\n\t\t\t'compose',\n\t\t\t...composeFiles(composePath),\n\t\t\t'cp',\n\t\t\t`${service}:${from}`,\n\t\t\tto,\n\t\t]);\n\t},\n\n\tasync reload(composePath, service) {\n\t\t// Caddy's own reload is graceful and validates first, so a config it\n\t\t// refuses leaves the previous one serving rather than dropping the edge.\n\t\tawait run('docker', [\n\t\t\t'compose',\n\t\t\t...composeFiles(composePath),\n\t\t\t'exec',\n\t\t\t'-T',\n\t\t\tservice,\n\t\t\t'caddy',\n\t\t\t'reload',\n\t\t\t'--config',\n\t\t\t'/etc/caddy/Caddyfile',\n\t\t]);\n\t},\n\n\tasync exec(composePath, service, argv) {\n\t\ttry {\n\t\t\tconst { stdout, stderr } = await run('docker', [\n\t\t\t\t'compose',\n\t\t\t\t...composeFiles(composePath),\n\t\t\t\t'exec',\n\t\t\t\t'-T',\n\t\t\t\tservice,\n\t\t\t\t...argv,\n\t\t\t]);\n\t\t\treturn { ok: true, output: `${stdout}${stderr}` };\n\t\t} catch (error) {\n\t\t\tconst { stdout = '', stderr = '' } = error as {\n\t\t\t\tstdout?: string;\n\t\t\t\tstderr?: string;\n\t\t\t};\n\t\t\treturn { ok: false, output: `${stdout}${stderr}` };\n\t\t}\n\t},\n\n\tasync healthy(composePath, services, { mounted = [] } = {}) {\n\t\tif (services.length === 0) return true;\n\t\tconst checkout = dirname(composePath);\n\n\t\ttry {\n\t\t\tconst { stdout } = await run('docker', [\n\t\t\t\t'compose',\n\t\t\t\t...composeFiles(composePath),\n\t\t\t\t'ps',\n\t\t\t\t'--format',\n\t\t\t\t'json',\n\t\t\t\t...services,\n\t\t\t]);\n\n\t\t\tconst running = new Set<string>();\n\t\t\tfor (const line of stdout.trim().split('\\n').filter(Boolean)) {\n\t\t\t\tconst entry = JSON.parse(line) as {\n\t\t\t\t\tService?: string;\n\t\t\t\t\tState?: string;\n\t\t\t\t\tHealth?: string;\n\t\t\t\t\tLabels?: string;\n\t\t\t\t};\n\n\t\t\t\t// A container with a health check must be passing it; one without\n\t\t\t\t// only has to be running, since there is nothing better to ask.\n\t\t\t\tconst ok =\n\t\t\t\t\tentry.State === 'running' &&\n\t\t\t\t\t(entry.Health === undefined ||\n\t\t\t\t\t\tentry.Health === '' ||\n\t\t\t\t\t\tentry.Health === 'healthy');\n\n\t\t\t\t// Every checkout of a project shares its compose project name, so a\n\t\t\t\t// worktree's container answers here too. One that mounts the\n\t\t\t\t// checkout's files reads that worktree's — Caddy routing to the\n\t\t\t\t// ports another checkout's apps had — so it counts only when it was\n\t\t\t\t// created from this one.\n\t\t\t\tconst fromHere =\n\t\t\t\t\t!entry.Service ||\n\t\t\t\t\t!mounted.includes(entry.Service) ||\n\t\t\t\t\tlabel(entry.Labels, 'com.docker.compose.project.working_dir') ===\n\t\t\t\t\t\tcheckout;\n\n\t\t\t\tif (ok && fromHere && entry.Service) running.add(entry.Service);\n\t\t\t}\n\n\t\t\treturn services.every((service) => running.has(service));\n\t\t} catch {\n\t\t\t// No compose file yet, or no daemon. Either way, not healthy.\n\t\t\treturn false;\n\t\t}\n\t},\n};\n\n/** One label's value out of `docker compose ps`'s comma-joined `Labels`. */\nfunction label(labels: string | undefined, name: string): string | undefined {\n\tconst prefix = `${name}=`;\n\treturn labels\n\t\t?.split(',')\n\t\t.find((pair) => pair.startsWith(prefix))\n\t\t?.slice(prefix.length);\n}\n\nexport { HEALTH_TIMEOUT_MS };\n","/**\n * This machine's address on the local network — what a phone running the app\n * reaches it on.\n */\n\nimport { type NetworkInterfaceInfo, networkInterfaces } from 'node:os';\n\n/**\n * The first private IPv4 address of an interface that is up and not loopback.\n *\n * Private ranges only (`10/8`, `172.16/12`, `192.168/16`): a public address\n * would mean listening for a phone on the open internet, and a link-local one\n * (`169.254/16`) is what an interface has when it found no network at all.\n * Undefined when there is none — a laptop on no network still runs, its mobile\n * app reaching only a simulator.\n */\nexport function lanAddress(\n\tinterfaces: Record<\n\t\tstring,\n\t\tNetworkInterfaceInfo[] | undefined\n\t> = networkInterfaces(),\n): string | undefined {\n\tfor (const entries of Object.values(interfaces)) {\n\t\tfor (const entry of entries ?? []) {\n\t\t\tif (entry.family !== 'IPv4' || entry.internal) continue;\n\t\t\tif (isPrivate(entry.address)) return entry.address;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isPrivate(address: string): boolean {\n\treturn (\n\t\t/^10\\./.test(address) ||\n\t\t/^192\\.168\\./.test(address) ||\n\t\t/^172\\.(1[6-9]|2\\d|3[01])\\./.test(address)\n\t);\n}\n","/**\n * Bringing a container that already has data in line with the workspace's\n * generated logins.\n *\n * Postgres and RabbitMQ read their login from the environment once, when the\n * volume is first initialised; a volume an older gkm made was initialised\n * with the old fixed one, and a changed environment alone would lock the\n * developer out of their own data. So after the containers are up, each one\n * is asked whether the generated login opens it, and if not:\n *\n * - **Postgres**: signed in to with the old login, the generated superuser is\n * created (or given its password), and the old one stops logging in. Where\n * no login is accepted — another checkout of the same project rotated it —\n * the password is set from inside the container, which trusts its own\n * socket.\n * - **MinIO** reads its root login on every start, so recreating the\n * container rotated it already. If the old login is still the one it takes —\n * a project's own `docker-compose.yml` pins it — that is kept, with a note.\n * - **RabbitMQ**: the user is added, or given its password, with `rabbitmqctl`\n * inside the container.\n *\n * Nothing is deleted: no volume, no database, no bucket.\n */\n\nimport { ListBucketsCommand, S3Client } from '@aws-sdk/client-s3';\nimport { Client } from 'pg';\nimport { GkmError } from '../errors';\nimport { CLUSTER_DATABASE } from './compose';\nimport type { LocalCredentials, Login } from './localCredentials';\n\n/**\n * The login every local container was brought up with before logins were\n * generated. Kept only to recognise — and rotate away from — a volume made\n * then.\n */\nexport const LEGACY_LOCAL_LOGIN: Login = Object.freeze({\n\tuser: 'geekmidas',\n\tpassword: 'geekmidas',\n});\n\n/** Runs a command inside a running compose service. */\nexport type ServiceExec = (\n\tservice: string,\n\targv: readonly string[],\n) => Promise<{ ok: boolean; output: string }>;\n\n/** What checking one service's login found and did. */\nexport interface LoginOutcome {\n\tservice: 'postgres' | 'minio' | 'rabbitmq';\n\t/**\n\t * `current` — the generated login opened it; `rotated` — an older login\n\t * did, and the service now takes the generated one; `kept` — an older\n\t * login did and could not be rotated, so it is what is used.\n\t */\n\tstatus: 'current' | 'rotated' | 'kept';\n\t/** The login the service takes now. */\n\tlogin: Login;\n\t/** A line for the developer, where anything changed. */\n\tnotice?: string;\n}\n\n/** No login this workspace knows opens its Postgres. */\nexport class PostgresLoginRefused extends GkmError {\n\tconstructor(\n\t\treadonly port: number,\n\t\treadonly user: string,\n\t) {\n\t\tsuper(\n\t\t\t`The Postgres on port ${port} accepts neither '${user}' with this workspace's generated password nor the login older gkm versions used, and could not be reset from inside its container. ` +\n\t\t\t\t\"If it is not this project's container, stop whatever holds the port. If it is, removing its volume starts it over with the generated login — and deletes its data: docker compose -f docker-compose.constructs.yml down -v\",\n\t\t);\n\t\tthis.name = 'PostgresLoginRefused';\n\t}\n}\n\n/** No login this workspace knows opens its MinIO. */\nexport class MinioLoginRefused extends GkmError {\n\tconstructor(\n\t\treadonly port: number,\n\t\treadonly user: string,\n\t) {\n\t\tsuper(\n\t\t\t`The MinIO on port ${port} accepts neither '${user}' with this workspace's generated password nor the login older gkm versions used. ` +\n\t\t\t\t'If your docker-compose.yml sets MINIO_ROOT_USER or MINIO_ROOT_PASSWORD, remove them so the generated login applies.',\n\t\t);\n\t\tthis.name = 'MinioLoginRefused';\n\t}\n}\n\n/** Whether `login` opens the Postgres on `port`, as a connected client. */\nasync function connect(port: number, login: Login): Promise<Client | null> {\n\tconst client = new Client({\n\t\thost: 'localhost',\n\t\tport,\n\t\tuser: login.user,\n\t\tpassword: login.password,\n\t\tdatabase: CLUSTER_DATABASE,\n\t});\n\ttry {\n\t\tawait client.connect();\n\t\treturn client;\n\t} catch (error) {\n\t\tawait client.end().catch(() => {});\n\t\t// 28P01: wrong password. 28000: no such role, or no pg_hba entry.\n\t\t// 3D000: no such database — a cluster whose default database was\n\t\t// named after an older superuser still answers for `postgres`, so\n\t\t// this is only a login that is not ours.\n\t\tconst code = (error as { code?: string }).code;\n\t\tif (code === '28P01' || code === '28000' || code === '3D000') return null;\n\t\tthrow error;\n\t}\n}\n\n/** Quote a string literal for DDL that cannot take parameters. */\nfunction literal(value: string): string {\n\treturn `'${value.replace(/'/g, \"''\")}'`;\n}\n\nfunction ident(name: string): string {\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** The SQL that makes `login` a superuser with its password, new or not. */\nfunction superuserSql(login: Login): string {\n\treturn (\n\t\t`DO $$ BEGIN IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(login.user)}) ` +\n\t\t`THEN ALTER ROLE ${ident(login.user)} WITH SUPERUSER LOGIN PASSWORD ${literal(login.password)}; ` +\n\t\t`ELSE CREATE ROLE ${ident(login.user)} WITH SUPERUSER LOGIN PASSWORD ${literal(login.password)}; ` +\n\t\t'END IF; END $$'\n\t);\n}\n\n/**\n * Make the Postgres on `port` take `login`, rotating it from an older one\n * where that is what it takes.\n */\nexport async function ensurePostgresLogin(options: {\n\tport: number;\n\tlogin: Login;\n\t/** Older logins it may still take, most likely first. */\n\tlegacy: readonly Login[];\n\t/** Inside the container, where its socket trusts any role. */\n\texec?: ServiceExec;\n}): Promise<LoginOutcome> {\n\tconst { port, login, legacy } = options;\n\n\tconst current = await connect(port, login);\n\tif (current) {\n\t\tawait current.end();\n\t\treturn { service: 'postgres', status: 'current', login };\n\t}\n\n\tfor (const old of legacy) {\n\t\tconst client = await connect(port, old);\n\t\tif (!client) continue;\n\t\ttry {\n\t\t\tawait client.query(superuserSql(login));\n\t\t} catch {\n\t\t\t// The old login is not allowed to make a superuser: keep using it.\n\t\t\tawait client.end();\n\t\t\treturn {\n\t\t\t\tservice: 'postgres',\n\t\t\t\tstatus: 'kept',\n\t\t\t\tlogin: old,\n\t\t\t\tnotice: `⚠️ Postgres still signs in as '${old.user}' with the old fixed password: it could not be rotated. To start over with a generated one, remove its volume (this deletes its data): docker compose -f docker-compose.constructs.yml down -v`,\n\t\t\t};\n\t\t}\n\t\tawait client.end();\n\t\tawait retire(port, login, old);\n\t\treturn {\n\t\t\tservice: 'postgres',\n\t\t\tstatus: 'rotated',\n\t\t\tlogin,\n\t\t\tnotice: `🔑 Postgres moved from the old fixed login to a generated one ('${login.user}'); its data is unchanged. See it with: gkm dev:credentials`,\n\t\t};\n\t}\n\n\t// Nothing we know opens it over TCP. Its socket inside the container\n\t// trusts any role that exists, which one of these is.\n\tif (options.exec) {\n\t\tfor (const user of [login.user, ...legacy.map((l) => l.user)]) {\n\t\t\tconst result = await options.exec('postgres', [\n\t\t\t\t'psql',\n\t\t\t\t'-v',\n\t\t\t\t'ON_ERROR_STOP=1',\n\t\t\t\t'-U',\n\t\t\t\tuser,\n\t\t\t\t'-d',\n\t\t\t\tCLUSTER_DATABASE,\n\t\t\t\t'-c',\n\t\t\t\tsuperuserSql(login),\n\t\t\t]);\n\t\t\tif (!result.ok) continue;\n\t\t\tconst client = await connect(port, login);\n\t\t\tif (!client) continue;\n\t\t\tawait client.end();\n\t\t\tfor (const old of legacy) await retire(port, login, old);\n\t\t\treturn {\n\t\t\t\tservice: 'postgres',\n\t\t\t\tstatus: 'rotated',\n\t\t\t\tlogin,\n\t\t\t\tnotice: `🔑 Postgres's login was reset to this workspace's generated one ('${login.user}'); its data is unchanged.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tthrow new PostgresLoginRefused(port, login.user);\n}\n\n/** Stop an older login from opening the cluster, now another does. */\nasync function retire(port: number, login: Login, old: Login): Promise<void> {\n\tif (old.user === login.user) return;\n\tconst client = await connect(port, login);\n\tif (!client) return;\n\ttry {\n\t\tconst exists = await client.query(\n\t\t\t'SELECT 1 FROM pg_roles WHERE rolname = $1',\n\t\t\t[old.user],\n\t\t);\n\t\tif (exists.rowCount) {\n\t\t\tawait client.query(\n\t\t\t\t`ALTER ROLE ${ident(old.user)} WITH NOLOGIN PASSWORD NULL`,\n\t\t\t);\n\t\t}\n\t} finally {\n\t\tawait client.end();\n\t}\n}\n\n/** Whether `login` signs in to the MinIO on `port`. */\nexport async function minioAccepts(\n\tport: number,\n\tlogin: Login,\n): Promise<boolean> {\n\tconst s3 = new S3Client({\n\t\tregion: 'us-east-1',\n\t\tendpoint: `http://localhost:${port}`,\n\t\tforcePathStyle: true,\n\t\tcredentials: { accessKeyId: login.user, secretAccessKey: login.password },\n\t\tmaxAttempts: 1,\n\t});\n\ttry {\n\t\tawait s3.send(new ListBucketsCommand({}));\n\t\treturn true;\n\t} catch (error) {\n\t\tconst name = (error as { name?: string }).name ?? '';\n\t\tif (\n\t\t\tname === 'InvalidAccessKeyId' ||\n\t\t\tname === 'SignatureDoesNotMatch' ||\n\t\t\tname === 'AccessDenied'\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\ts3.destroy();\n\t}\n}\n\n/**\n * Check the MinIO on `port` takes `login`. It reads its root login on every\n * start, so a recreated container already does — unless something pins an\n * older one, which is then kept.\n */\nexport async function ensureMinioLogin(options: {\n\tport: number;\n\tlogin: Login;\n\tlegacy: readonly Login[];\n}): Promise<LoginOutcome> {\n\tconst { port, login, legacy } = options;\n\tif (await minioAccepts(port, login)) {\n\t\treturn { service: 'minio', status: 'current', login };\n\t}\n\tfor (const old of legacy) {\n\t\tif (await minioAccepts(port, old)) {\n\t\t\treturn {\n\t\t\t\tservice: 'minio',\n\t\t\t\tstatus: 'kept',\n\t\t\t\tlogin: old,\n\t\t\t\tnotice: `⚠️ MinIO still signs in as '${old.user}' with the old fixed password: something — usually your docker-compose.yml's MINIO_ROOT_USER/MINIO_ROOT_PASSWORD — pins it. Remove that to use the generated login.`,\n\t\t\t};\n\t\t}\n\t}\n\tthrow new MinioLoginRefused(port, login.user);\n}\n\n/**\n * Make the RabbitMQ in the project's container take `login`, with\n * `rabbitmqctl` inside it — which needs no password.\n */\nexport async function ensureRabbitmqLogin(options: {\n\tlogin: Login;\n\tlegacy: readonly Login[];\n\texec: ServiceExec;\n}): Promise<LoginOutcome> {\n\tconst { login, legacy, exec } = options;\n\tconst ctl = (...args: string[]) => exec('rabbitmq', ['rabbitmqctl', ...args]);\n\n\tif ((await ctl('authenticate_user', login.user, login.password)).ok) {\n\t\treturn { service: 'rabbitmq', status: 'current', login };\n\t}\n\n\tif (!(await ctl('add_user', login.user, login.password)).ok) {\n\t\tawait ctl('change_password', login.user, login.password);\n\t}\n\tawait ctl('set_user_tags', login.user, 'administrator');\n\tawait ctl('set_permissions', '-p', '/', login.user, '.*', '.*', '.*');\n\tfor (const old of legacy) {\n\t\tif (old.user !== login.user) await ctl('delete_user', old.user);\n\t}\n\treturn {\n\t\tservice: 'rabbitmq',\n\t\tstatus: 'rotated',\n\t\tlogin,\n\t\tnotice: `🔑 RabbitMQ moved from the old fixed login to a generated one ('${login.user}'); its queues are unchanged.`,\n\t};\n}\n\n/** Every container's login, checked — and what is used from now on. */\nexport interface LoginsResult {\n\tcredentials: LocalCredentials;\n\toutcomes: LoginOutcome[];\n}\n\n/**\n * Check the login of each running container that keeps one, and the\n * credentials to use from here: the generated ones, or an older login a\n * service could not be moved off.\n */\nexport async function ensureLogins(options: {\n\tcredentials: LocalCredentials;\n\tcontainers: readonly string[];\n\tports: { postgres?: number; minio?: number };\n\texec?: ServiceExec;\n}): Promise<LoginsResult> {\n\tconst { containers, ports, exec } = options;\n\tlet credentials = options.credentials;\n\tconst outcomes: LoginOutcome[] = [];\n\tconst legacy = [LEGACY_LOCAL_LOGIN];\n\n\tif (containers.includes('postgres') && ports.postgres !== undefined) {\n\t\tconst outcome = await ensurePostgresLogin({\n\t\t\tport: ports.postgres,\n\t\t\tlogin: credentials.postgres,\n\t\t\tlegacy,\n\t\t\t...(exec ? { exec } : {}),\n\t\t});\n\t\toutcomes.push(outcome);\n\t\tcredentials = { ...credentials, postgres: outcome.login };\n\t}\n\n\tif (containers.includes('minio') && ports.minio !== undefined) {\n\t\tconst outcome = await ensureMinioLogin({\n\t\t\tport: ports.minio,\n\t\t\tlogin: credentials.minio,\n\t\t\tlegacy,\n\t\t});\n\t\toutcomes.push(outcome);\n\t\tcredentials = { ...credentials, minio: outcome.login };\n\t}\n\n\tif (containers.includes('rabbitmq') && exec) {\n\t\toutcomes.push(\n\t\t\tawait ensureRabbitmqLogin({\n\t\t\t\tlogin: credentials.rabbitmq,\n\t\t\t\tlegacy,\n\t\t\t\texec,\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn { credentials, outcomes };\n}\n","/**\n * Port allocation — why two projects can run at once.\n *\n * Publishing `5432:5432` means the second project on your machine cannot start.\n * Nothing solves that except giving each project its own ports, and what makes\n * it *possible* is the single-`<NAME>_URL` rule: an app reads `ORDERS_URL` and\n * never sees a host or a port, so reconcile is free to bind whatever is\n * available and compose the URL from what it bound. An app reading `DB_HOST` and\n * `DB_PORT` separately could not be moved this way.\n *\n * Assignments are **persisted, not recomputed**. Recomputing means adding a\n * construct renumbers its neighbours, and every running container, saved\n * connection string, and `psql` history goes stale at once.\n *\n * Pure, with the liveness probe injected — a collision with another project's\n * stack is a fact about the machine, and keeping it a parameter is what lets the\n * rules be asserted without binding a socket.\n */\n\nimport { createHash } from 'node:crypto';\nimport { createServer } from 'node:net';\nimport { GkmError } from '../errors';\n\n/** What was assigned, by container name. Persisted between runs. */\nexport type PortAssignments = Readonly<Record<string, number>>;\n\n/**\n * The window ports are drawn from.\n *\n * Above the registered range so nothing here needs privileges, and below the\n * ephemeral range both Linux (32768+) and macOS (49152+) allocate from — a port\n * the kernel might hand to an outgoing connection is one that is free when\n * checked and taken by the time it is bound.\n */\nconst WINDOW = { min: 20000, max: 32000 } as const;\n\n/**\n * How far apart two projects start.\n *\n * Wide enough that a project can add containers without walking into its\n * neighbour's block, narrow enough that the window holds many projects.\n */\nconst BLOCK = 50;\n\n/**\n * Where a project's ports start.\n *\n * Derived from the name rather than assigned sequentially so that a fresh clone\n * of the same project on the same machine lands on the same block — the first\n * run has nothing persisted to read, and hashing is what keeps that first run\n * from colliding with whatever else is already allocated.\n *\n * @example startingPort('toolbox') // stable for a given name\n */\nexport function startingPort(project: string): number {\n\tconst digest = createHash('sha256').update(project).digest();\n\tconst blocks = Math.floor((WINDOW.max - WINDOW.min) / BLOCK);\n\n\treturn WINDOW.min + (digest.readUInt32BE(0) % blocks) * BLOCK;\n}\n\n/**\n * Whether a port can be bound right now.\n *\n * Async because the only way to answer it is to try binding, and\n * `server.listen` is asynchronous — there is no synchronous form to wrap. A\n * probe that pretended otherwise would have to lie.\n */\nexport type PortProbe = (port: number) => Promise<boolean>;\n\n/**\n * Assign a port to every container that has none, keeping the ones that do.\n *\n * Existing assignments are returned untouched even when the container is no\n * longer in the plan: removing a construct must not renumber what is left, and\n * keeping the entry means re-adding it later restores the same port rather than\n * inventing a new one.\n *\n * @param probe - reports what is actually listening. A port assigned to this\n * project is skipped without probing, because on a converged reconcile our own\n * container is the thing listening on it.\n * @throws {NoPortAvailable} when the window is exhausted.\n */\nexport async function allocate(\n\tproject: string,\n\tcontainers: readonly string[],\n\texisting: PortAssignments = {},\n\tprobe: PortProbe = isPortFree,\n): Promise<PortAssignments> {\n\tconst assignments: Record<string, number> = { ...existing };\n\tconst taken = new Set(Object.values(assignments));\n\n\t// Sorted so the order containers happen to appear in the plan cannot change\n\t// which port each one gets.\n\tfor (const container of [...containers].sort()) {\n\t\tif (assignments[container] !== undefined) continue;\n\n\t\tconst port = await nextFree(startingPort(project), taken, probe);\n\t\tassignments[container] = port;\n\t\ttaken.add(port);\n\t}\n\n\treturn assignments;\n}\n\n/**\n * The ports to keep: what running containers are observed on, then what was\n * saved — minus any saved entry whose port something else already holds.\n *\n * Spreading one over the other let an observed port override its own key and\n * leave a *different* key still saved on the same number: two services on one\n * port, and whichever answered first won. Saved keys for containers the plan no\n * longer has — a backend switched and back — were the usual source. Observed\n * wins because it is what is actually bound; a dropped entry is simply\n * allocated again.\n */\nexport function keptPorts(\n\tsaved: PortAssignments = {},\n\tobserved: PortAssignments = {},\n): PortAssignments {\n\tconst kept: Record<string, number> = { ...observed };\n\tconst taken = new Set(Object.values(observed));\n\n\t// Sorted, so which of two colliding saved entries survives is stable.\n\tfor (const [key, port] of Object.entries(saved).sort(([a], [b]) =>\n\t\ta < b ? -1 : 1,\n\t)) {\n\t\tif (key in kept || taken.has(port)) continue;\n\t\tkept[key] = port;\n\t\ttaken.add(port);\n\t}\n\n\treturn kept;\n}\n\n/**\n * Whether a port is published by one of this project's own containers.\n *\n * Asked only of a port the probe found taken: our own container on it is the\n * normal re-run, anything else is a stack that took the port since it was\n * saved.\n */\nexport type PortOwner = (port: number) => Promise<boolean>;\n\n/** A kept port something else now holds, and where its container moved. */\nexport interface PortMove {\n\tkey: string;\n\tfrom: number;\n\tto: number;\n}\n\n/**\n * The kept ports, among those the plan publishes, that something other than\n * this project now holds.\n *\n * A saved port is only a memory of a free one. Another checkout's stack — the\n * same project name hashes to the same block — can bind it in the meantime,\n * and keeping it unchecked fails `docker compose up` with \"port is already\n * allocated\". An observed port is ours by definition and is never asked\n * about; neither is a saved one the plan no longer publishes, which is only\n * kept for when it returns.\n */\nexport async function heldElsewhere(\n\tkept: PortAssignments,\n\tkeys: readonly string[],\n\tobserved: PortAssignments,\n\tprobe: PortProbe,\n\tours: PortOwner,\n): Promise<string[]> {\n\tconst held: string[] = [];\n\n\tfor (const key of [...keys].sort()) {\n\t\tconst port = kept[key];\n\t\tif (port === undefined || key in observed) continue;\n\t\tif (await probe(port)) continue;\n\t\tif (await ours(port)) continue;\n\t\theld.push(key);\n\t}\n\n\treturn held;\n}\n\n/** The window was exhausted. */\nexport class NoPortAvailable extends GkmError {\n\t/** Where the search started. */\n\treadonly from: number;\n\t/** The window searched, so the caller can report what was full. */\n\treadonly window: { min: number; max: number } = WINDOW;\n\n\tconstructor(from: number) {\n\t\tsuper('No free port is available in the local port range');\n\t\tthis.name = 'NoPortAvailable';\n\t\tthis.from = from;\n\t}\n}\n\n/**\n * The first port at or after `from` that is neither ours nor in use.\n *\n * Wraps at the top of the window rather than stopping, so a project whose block\n * sits near the end is not the one that fails.\n */\nasync function nextFree(\n\tfrom: number,\n\ttaken: ReadonlySet<number>,\n\tprobe: PortProbe,\n): Promise<number> {\n\tconst span = WINDOW.max - WINDOW.min;\n\n\tfor (let offset = 0; offset < span; offset++) {\n\t\tconst port = WINDOW.min + ((from - WINDOW.min + offset) % span);\n\t\tif (taken.has(port)) continue;\n\t\tif (await probe(port)) return port;\n\t}\n\n\tthrow new NoPortAvailable(from);\n}\n\n/**\n * Whether nothing is listening on a port.\n *\n * Binds rather than connects: a refused connection says nothing about whether\n * the port can be *published*, which is the question Docker will ask. Binds on\n * `0.0.0.0` for the same reason — a port free on loopback can still be taken on\n * the address Docker publishes to — and then on `127.0.0.1`, because on macOS\n * a wildcard bind succeeds beside a listener on loopback alone.\n *\n * Inherently racy, and that is acceptable: Docker failing to bind stays the real\n * check. This exists so the common case surfaces as a message at reconcile\n * rather than as a connection failure ten minutes later.\n */\nexport async function isPortFree(port: number): Promise<boolean> {\n\treturn (await canBind(port, '0.0.0.0')) && (await canBind(port, '127.0.0.1'));\n}\n\nfunction canBind(port: number, host: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst server = createServer();\n\n\t\tserver.once('error', () => resolve(false));\n\t\tserver.once('listening', () => server.close(() => resolve(true)));\n\t\tserver.listen(port, host);\n\t});\n}\n","/**\n * What reconcile records, and the hash that lets it do nothing.\n *\n * Reconciling on every `gkm dev` is only acceptable if the converged case is\n * free, so the desired plan is hashed: matching hash plus healthy containers\n * means there is nothing to do. Without that, the automatic reconcile the design\n * asks for would tax every start.\n *\n * Almost nothing needs recording — roles are queried, migrations have their own\n * table, containers are remembered by Docker. Only ports and this hash have no\n * other owner.\n */\n\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { ComposeFile } from './compose';\nimport type { Plan } from './plan';\n\n/** What was true at the end of the last successful reconcile. */\nexport interface ReconcileState {\n\t/** The hash of the plan that was applied. */\n\thash: string;\n\t/** The stage it was applied for, so a mismatched file is ignored. */\n\tstage: string;\n}\n\nconst STATE_DIR = '.gkm/reconcile';\n\n/**\n * The hash of everything a reconcile would act on.\n *\n * Covers the compose document rather than the plan alone, because the plan is\n * unchanged when only an image pin moves — and a changed image is exactly a\n * container that must be recreated. `stringify` is stable here because\n * `composeFor` sorts its containers, which is what makes the hash meaningful.\n *\n * Deliberately a plain function over serialisable input: the deployed target\n * keys its provisioner invocation on the same idea, and the two must not be able\n * to disagree about what counts as a change.\n */\nexport function planHash(\n\tplan: Plan,\n\tcompose: ComposeFile,\n\t/**\n\t * Anything else generated from the plan that a container reads.\n\t *\n\t * The edge's Caddyfile is the case: a file server added or a bucket renamed\n\t * changes the routing without changing a single container, so a hash over\n\t * the compose document alone would report convergence and leave the old\n\t * routes serving.\n\t */\n\tgenerated: Readonly<Record<string, string>> = {},\n): string {\n\treturn createHash('sha256')\n\t\t.update(JSON.stringify({ stage: plan.stage, plan, compose, generated }))\n\t\t.digest('hex');\n}\n\n/** Read the recorded state, or nothing if this stage has never reconciled. */\nexport async function loadState(\n\troot: string,\n\tstage: string,\n): Promise<ReconcileState | undefined> {\n\ttry {\n\t\tconst raw = await readFile(statePath(root, stage), 'utf-8');\n\t\tconst state = JSON.parse(raw) as ReconcileState;\n\n\t\t// A file written for another stage is not this stage's state. Treating it\n\t\t// as one is how `gkm test` would skip work `gkm dev` did.\n\t\treturn state.stage === stage ? state : undefined;\n\t} catch {\n\t\t// Unreadable, absent, or corrupt all mean the same thing: reconcile. The\n\t\t// loop is convergent, so the cost of being wrong here is one slow start.\n\t\treturn undefined;\n\t}\n}\n\n/** Record what was applied, so the next run can skip it. */\nexport async function saveState(\n\troot: string,\n\tstate: ReconcileState,\n): Promise<void> {\n\tconst path = statePath(root, state.stage);\n\n\tawait mkdir(dirname(path), { recursive: true });\n\tawait writeFile(path, `${JSON.stringify(state, null, 2)}\\n`);\n}\n\n/**\n * Forget what was applied, so the next reconcile of this stage converges from\n * nothing — creating again whatever was dropped underneath the record.\n */\nexport async function forgetState(root: string, stage: string): Promise<void> {\n\tawait rm(statePath(root, stage), { force: true });\n}\n\nfunction statePath(root: string, stage: string): string {\n\treturn join(root, STATE_DIR, `${stage}.json`);\n}\n","/**\n * Reconcile — the one convergent function `gkm dev`, `gkm test`, and `gkm setup`\n * all call.\n *\n * Three phases, and only this one has side effects: declaring is pure (`gkm\n * build` and the dev watcher), running reads `<NAME>_URL` and provisions\n * nothing. Reconcile computes the desired state, compares, and applies the\n * difference — which is what makes \"when does it run\" answerable with\n * *whenever, repeatedly*.\n *\n * It is safe to run automatically because its blast radius is entirely local:\n * this project's containers, this project's `.gkm/`. Nothing it does can reach a\n * cloud. The line is drawn at data, not at side effects — it allocates ports,\n * writes compose, starts containers, and creates roles; it never seeds, resets,\n * or drops.\n *\n * Docker is injected rather than imported so the rules above can be asserted\n * without a daemon. The default implementation is the real one.\n */\n\nimport { existsSync } from 'node:fs';\nimport {\n\tchmod,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trm,\n\twriteFile,\n} from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { type ConstructManifest, provisionOrder } from '@geekmidas/manifest';\nimport { scopeTelemetryEnv } from '../telemetry/edges';\nimport type { CacheBackend, EventsBackend } from '../types';\nimport { TEST_STAGE } from '../workspace/stages';\nimport { caddyfileRoot, sitesFor, toCaddyfile } from './caddyfile';\nimport { bucketClient, carrierClient, pgClient } from './clients';\nimport {\n\ttype ComposeFile,\n\ttype ComposeService,\n\tcomposeFor,\n\ttoYaml,\n} from './compose';\nimport {\n\tportKeys,\n\tportsOf,\n\tprimaryPortKey,\n\ttype ServiceAddress,\n\tserviceAddresses,\n} from './containers';\nimport { dockerCli } from './docker';\nimport { envFor } from './env';\nimport type { LocalFake } from './fakes';\nimport { lanAddress } from './lan';\nimport type { LocalCredentials, Login } from './localCredentials';\nimport { ensureLogins, type LoginOutcome } from './logins';\nimport type { ObjectWebhook } from './objectEvents';\nimport {\n\ttype Plan,\n\ttype PlanOptions,\n\tplanFor,\n\tTELEMETRY_CONTAINER,\n} from './plan';\nimport {\n\tallocate,\n\theldElsewhere,\n\tisPortFree,\n\tkeptPorts,\n\ttype PortAssignments,\n\ttype PortMove,\n\ttype PortProbe,\n} from './ports';\nimport {\n\ttype Applied,\n\tapplyBuckets,\n\tapplyCarriers,\n\tapplyLifecycles,\n\tapplyNotifications,\n\tapplyPolicies,\n\tapplyPostgres,\n\ttype BucketClient,\n\tbucketLifecycles,\n\tbucketNames,\n\tbucketPolicies,\n\ttype CarrierClient,\n\tcarrierNames,\n\tdatabasesExist,\n\tpostgresDatabaseNames,\n\tpostgresStatements,\n\ttype SqlClient,\n} from './provision';\nimport { loadState, planHash, saveState } from './state';\n\nexport type { ComposeFile } from './compose';\nexport type { Plan, PlannedResource } from './plan';\nexport type { PortAssignments, PortMove } from './ports';\n\n/**\n * Where the generated compose file is written, relative to the project root.\n *\n * At the root, beside the project's own `docker-compose.yml`, because the two\n * are one stack: this file is everything the constructs imply and is never\n * edited, that one is anything they cannot express — an image pin, an extra\n * service — and is merged over it, so it wins.\n */\nexport const COMPOSE_PATH = 'docker-compose.constructs.yml';\n\n/** The project's own compose file, merged over the generated one if present. */\nexport const PROJECT_COMPOSE_PATH = 'docker-compose.yml';\n\n/**\n * The local edge's config, beside the compose file that mounts it.\n *\n * Relative in the compose volume, so it resolves against `.gkm/` wherever the\n * project lives.\n */\nexport const CADDYFILE_PATH = '.gkm/Caddyfile';\n\n/**\n * The containers that mount this checkout's files: Caddy reads its routes out\n * of `.gkm/`, so one started from a worktree serves that worktree's ports.\n */\nconst CHECKOUT_MOUNTS = ['caddy'];\n\n/**\n * Where one stage's routes live, imported by the file above.\n *\n * Per stage because one edge serves every stage, the same way one Postgres\n * holds `orders` and `orders_test`. A single file would mean `gkm test`\n * deleting the routes `gkm dev` is serving.\n */\nexport const caddySitesPath = (stage: string) =>\n\t`.gkm/caddy-sites/${stage}.caddy`;\n\n/**\n * Where the local edge's root certificate is copied to.\n *\n * Exported so a process can be pointed at it without installing anything:\n * `NODE_EXTRA_CA_CERTS` is the whole of the trust story for Node, and it needs\n * no sudo. A browser is the case that still wants the root in the system store,\n * which is a one-time `caddy trust` rather than something a reconcile should do\n * on a developer's behalf.\n */\nexport const LOCAL_CA_PATH = '.gkm/caddy-root.crt';\n\n/** Where Caddy keeps the root of the CA it generated. */\nconst CADDY_ROOT_IN_CONTAINER = '/data/caddy/pki/authorities/local/root.crt';\n\n/**\n * The Docker operations reconcile needs.\n *\n * Small on purpose: everything else about containers Docker already remembers,\n * so there is no state here to keep in step with it.\n */\nexport interface Docker {\n\t/**\n\t * The host port a running container publishes for one of its internal ports,\n\t * or `undefined` if it is not running.\n\t *\n\t * Consulted before the saved assignments so that reconcile converges against\n\t * what is actually running rather than only against its own file — a\n\t * container someone started by hand is still the container serving the app.\n\t */\n\tpublishedPort(\n\t\tcomposePath: string,\n\t\tservice: string,\n\t\tinside: number,\n\t): Promise<number | undefined>;\n\t/**\n\t * The compose project of the running container publishing a host port, or\n\t * `undefined` when no container does — the port is held by something\n\t * outside Docker, or by nothing. Absent, nothing is known to be ours.\n\t */\n\tpublisher?(port: number): Promise<string | undefined>;\n\t/**\n\t * Bring the named services up, detached, and wait for their health checks.\n\t *\n\t * `show` lets Compose draw its own progress — the pulls, the containers it\n\t * creates, each one turning healthy — rather than capturing it. A first\n\t * start pulls every image and can take minutes, and minutes of nothing\n\t * read as a hang.\n\t */\n\tup(\n\t\tcomposePath: string,\n\t\tservices: readonly string[],\n\t\toptions?: { show?: boolean },\n\t): Promise<void>;\n\t/**\n\t * Whether every named service is running and passing its health check.\n\t *\n\t * `mounted` names the services that mount this checkout's files; one of\n\t * those counts only when it was created from the compose file's directory,\n\t * not from another checkout of the same project.\n\t */\n\thealthy(\n\t\tcomposePath: string,\n\t\tservices: readonly string[],\n\t\toptions?: { mounted?: readonly string[] },\n\t): Promise<boolean>;\n\t/**\n\t * Copy a file out of a running container.\n\t *\n\t * One case: the certificate authority the local edge generates. It lives in\n\t * the container's volume, and everything that has to *trust* it — Node, the\n\t * test suite, curl — lives outside.\n\t */\n\tcopyOut(\n\t\tcomposePath: string,\n\t\tservice: string,\n\t\tfrom: string,\n\t\tto: string,\n\t): Promise<void>;\n\t/**\n\t * Ask a running service to re-read its configuration.\n\t *\n\t * The local edge is the case: its routes are a mounted file, and a container\n\t * that is already up will not notice one changing.\n\t */\n\treload(composePath: string, service: string): Promise<void>;\n\t/**\n\t * Run a command inside a running service, reporting whether it exited\n\t * cleanly. Bringing an older volume's login in line uses it: Postgres's\n\t * socket and `rabbitmqctl` need no password from inside. Absent, that\n\t * fallback is skipped.\n\t */\n\texec?(\n\t\tcomposePath: string,\n\t\tservice: string,\n\t\targv: readonly string[],\n\t): Promise<{ ok: boolean; output: string }>;\n}\n\nexport interface ReconcileOptions {\n\t/** The project root — where `.gkm/` lives. */\n\troot: string;\n\t/**\n\t * Told each slow step as it starts — starting the containers, creating what\n\t * the constructs declare — and, given one, Docker shows its own progress.\n\t * Absent, reconcile is silent: `gkm test` and the converged case say\n\t * nothing.\n\t */\n\tprogress?: (message: string) => void;\n\t/**\n\t * The project name, which seeds port allocation and names the compose\n\t * project. Two checkouts of the same repo share it deliberately.\n\t */\n\tproject: string;\n\t/** The construct manifest — what the app declared. */\n\tmanifest: ConstructManifest;\n\t/** The stage being reconciled: the project's local stage, or `test`. */\n\tstage: string;\n\t/**\n\t * This machine's LAN address, for a mobile app's `exp://` origins and the\n\t * address its sign-in links are built on. Read from the network interfaces\n\t * when absent; `null` for none.\n\t */\n\tlanAddress?: string | null;\n\t/** Each mobile app's Metro port, by construct id. */\n\tmetroPorts?: Readonly<Record<string, number>>;\n\t/** The project's local stage, whose resources carry no suffix. */\n\tlocalStage?: string;\n\t/** The events backend, until `topic` and `queue` are kinds. */\n\tevents?: EventsBackend;\n\t/** Where a declared cache lives — see {@link CacheBackend}. */\n\tcache?: CacheBackend;\n\t/** Containers no construct implies — the config exceptions. */\n\textraContainers?: readonly string[];\n\t/** Each external API's fake, by id — see `readFakes`. */\n\tfakes?: PlanOptions['fakes'];\n\t/** Each credential's fake value, by id — see `readCredentialFakes`. */\n\tcredentialFakes?: PlanOptions['credentialFakes'];\n\t/**\n\t * The workspace's generated local logins — what every container is\n\t * brought up with and every URL carries. See `localCredentials.ts`.\n\t */\n\tcredentials: LocalCredentials;\n\t/** Whether the local edge fronts surfaces, sites and file servers. */\n\tedge?: boolean;\n\t/** The workspace's `protectedSubdomains` — see `PlanOptions`. */\n\tprotectedSubdomains?: readonly string[];\n\t/**\n\t * Where MinIO posts each watched bucket's events — see `objectEvents.ts`.\n\t * The same for every stage, because one MinIO serves them all; only the\n\t * local stage's buckets are pointed at them, so `gkm test`'s uploads never\n\t * reach the process `gkm dev` runs.\n\t */\n\tobjectWebhooks?: readonly ObjectWebhook[];\n\t/** Mailpit's webhook, where an inbox has a subscriber — see `inboxRelay.ts`. */\n\tinboxRelay?: string;\n\t/**\n\t * The apps, as services beside the containers — see `reconcile/apps.ts`.\n\t * Handed the derived containers so an app can depend on them.\n\t */\n\tapps?: (containers: readonly string[]) => Record<string, ComposeService>;\n\t/** Ports assigned by previous runs, from `.gkm/ports.json`. */\n\tsaved?: PortAssignments;\n\t/** Start containers and wait for health. Off answers \"what would change\". */\n\tstart?: boolean;\n\t/**\n\t * Create the databases, schemas, and buckets the plan names.\n\t *\n\t * Requires the containers to be running, so it is skipped when `start` is\n\t * off. Never seeds, resets, or drops — the line is at data, not side effects.\n\t */\n\tprovision?: boolean;\n\t/** The address mail is sent from locally. */\n\tmailFrom?: string;\n\t/**\n\t * Where each address-owning construct answers, keyed by id.\n\t *\n\t * Surfaces and sites. Assigned by whatever starts them, which is why it\n\t * arrives here rather than being read off a published container port.\n\t */\n\taddresses?: Readonly<Record<string, string>>;\n\t/**\n\t * Where each file server's processors answer, keyed by the file server's\n\t * id: the dev server of the app holding them. Only the edge reads it — a\n\t * file server's own address is still the bucket's.\n\t */\n\tprocessorAddresses?: Readonly<Record<string, string>>;\n\tdocker?: Docker;\n\tprobe?: PortProbe;\n\t/** Injected for tests; the defaults talk to the containers just started. */\n\tsql?: (port: number, login: Login) => SqlClient;\n\tbuckets?: (port: number, login: Login) => BucketClient;\n\tcarriers?: (\n\t\tport: number,\n\t\tcredentials: LocalCredentials['emulator'],\n\t) => CarrierClient;\n\t/**\n\t * Bring each running container's login in line with `credentials` — see\n\t * `logins.ts`. Injected for tests that run no containers.\n\t */\n\tlogins?: typeof ensureLogins;\n}\n\nexport interface ReconcileResult {\n\tstage: string;\n\tplan: Plan;\n\tcompose: ComposeFile;\n\t/** Every assigned port, keyed by port key. Persist this. */\n\tports: PortAssignments;\n\t/**\n\t * Saved ports something outside this project had bound, each moved to a\n\t * free one. Say so: a connection string copied before now is stale.\n\t */\n\tmoved: readonly PortMove[];\n\t/** Every port the containers publish, labelled — consoles and inbox too. */\n\tservices: readonly ServiceAddress[];\n\t/** The `<NAME>_URL` values this stage resolves. */\n\tenv: Readonly<Record<string, string>>;\n\t/**\n\t * The logins in use: the ones passed in, or — where a container that\n\t * already had data could not be moved to one — the login it still takes.\n\t * Keep them when they differ.\n\t */\n\tcredentials: LocalCredentials;\n\t/** What checking each container's login did, when it was checked. */\n\tlogins: readonly LoginOutcome[];\n\t/** What the applier created, or found already there. */\n\tprovisioned: Applied[];\n\t/**\n\t * Each external API's fake, by id. An image fake is already running with\n\t * the containers; an app fake is the caller's to serve — `gkm dev` does —\n\t * on `ports[fakeKey(id)]`.\n\t */\n\tfakes: Readonly<Record<string, LocalFake>>;\n\t/** The hash recorded for this state. */\n\thash: string;\n\t/**\n\t * Whether anything was applied. False is the fast path — the recorded hash\n\t * matched and the containers were healthy, so nothing was written or started.\n\t */\n\tchanged: boolean;\n}\n\n/**\n * Converge the local target on what the manifest declares.\n *\n * Cheap when there is nothing to do: the hash is compared before the compose\n * file is written or a container is touched, and a converged project pays one\n * hash and one health check.\n */\nexport async function reconcile(\n\toptions: ReconcileOptions,\n): Promise<ReconcileResult> {\n\tconst {\n\t\troot,\n\t\tproject,\n\t\tmanifest,\n\t\tstage,\n\t\tstart = true,\n\t\tprovision = true,\n\t\tdocker = dockerCli,\n\t\tprobe = isPortFree,\n\t\tsql = pgClient,\n\t\tbuckets = bucketClient,\n\t\tcarriers = carrierClient,\n\t\tlogins = ensureLogins,\n\t} = options;\n\tconst { seed } = options.credentials;\n\n\tconst plan = planFor(manifest, stage, provisionOrder(manifest), {\n\t\tlocalStage: options.localStage,\n\t\tevents: options.events,\n\t\tcache: options.cache,\n\t\textraContainers: options.extraContainers,\n\t\t...(options.fakes ? { fakes: options.fakes } : {}),\n\t\t...(options.credentialFakes\n\t\t\t? { credentialFakes: options.credentialFakes }\n\t\t\t: {}),\n\t\t...(options.edge === undefined ? {} : { edge: options.edge }),\n\t\t...(options.protectedSubdomains\n\t\t\t? { protectedSubdomains: options.protectedSubdomains }\n\t\t\t: {}),\n\t});\n\n\t// `gkm test` exports nothing: its stage starts no collector and hands no\n\t// process a telemetry key. The container stays in the file — it is the\n\t// same file `gkm dev` runs from, and dropping it would have `up\n\t// --remove-orphans` stop the one a running `gkm dev` is exporting to.\n\tconst exports = stage !== TEST_STAGE;\n\tconst running = exports\n\t\t? plan.containers\n\t\t: plan.containers.filter((c) => c !== TELEMETRY_CONTAINER);\n\n\tconst composePath = join(root, COMPOSE_PATH);\n\n\t// What is already running wins over what was recorded: a container on a port\n\t// is the fact, and the file is only a memory of one.\n\tconst observed = await observedPorts(\n\t\tdocker,\n\t\tcomposePath,\n\t\tplan.containers,\n\t\tplan.fakes,\n\t);\n\tconst keys = portKeys(plan.containers, plan.fakes);\n\tconst kept = keptPorts(options.saved, observed);\n\t// A saved port another stack has bound since is given up rather than handed\n\t// to `docker compose up` to fail on. Compose's own project name decides\n\t// what is ours, and `COMPOSE_PROJECT_NAME` overrides the file's.\n\tconst composeProject = process.env.COMPOSE_PROJECT_NAME || project;\n\tconst held = await heldElsewhere(\n\t\tkept,\n\t\tkeys,\n\t\tobserved,\n\t\tprobe,\n\t\tasync (port) => (await docker.publisher?.(port)) === composeProject,\n\t);\n\tconst ports = await allocate(\n\t\tproject,\n\t\tkeys,\n\t\tObject.fromEntries(\n\t\t\tObject.entries(kept).filter(([key]) => !held.includes(key)),\n\t\t),\n\t\tprobe,\n\t);\n\tconst moved = held.map((key) => ({\n\t\tkey,\n\t\tfrom: kept[key] as number,\n\t\tto: ports[key] as number,\n\t}));\n\n\tconst compose = composeFor(plan, {\n\t\tproject,\n\t\tports,\n\t\tcredentials: options.credentials,\n\t\t...(options.apps ? { apps: options.apps(plan.containers) } : {}),\n\t\t...(options.objectWebhooks?.length\n\t\t\t? { objectWebhooks: options.objectWebhooks }\n\t\t\t: {}),\n\t\t...(options.inboxRelay ? { inboxRelay: options.inboxRelay } : {}),\n\t});\n\n\t// The edge's config is part of what \"converged\" means: a file server added or\n\t// a bucket renamed changes the routing without changing a container, and a\n\t// hash that ignored it would leave the old routes in place.\n\tconst caddyfile = toCaddyfile(\n\t\tsitesFor(plan, project, options.addresses, options.processorAddresses),\n\t);\n\t// And so is what provisioning runs. A toolbox upgrade that changes the role\n\t// DDL — a new grant — changes no container and no route, so a hash without\n\t// it reported convergence and the existing database never got the grant.\n\tconst postgres = postgresStatements(plan, project, seed)\n\t\t.map((statement) => statement.create)\n\t\t.join(';\\n');\n\tconst hash = planHash(plan, compose, { caddyfile, postgres });\n\tconst services = serviceAddresses(running, ports, plan.fakes);\n\t// Only a project with a mobile app reads it, so only one looks for it.\n\tconst lan = plan.resources.some((r) => r.kind === 'mobile-app')\n\t\t? options.lanAddress === undefined\n\t\t\t? lanAddress()\n\t\t\t: (options.lanAddress ?? undefined)\n\t\t: undefined;\n\tconst envWith = (credentials: LocalCredentials) => {\n\t\tconst resolved = envFor(plan, {\n\t\t\tports,\n\t\t\tproject,\n\t\t\tcredentials,\n\t\t\tseed,\n\t\t\t...(options.mailFrom ? { mailFrom: options.mailFrom } : {}),\n\t\t\t...(options.addresses ? { addresses: options.addresses } : {}),\n\t\t\t...(lan ? { lanAddress: lan } : {}),\n\t\t\t...(options.metroPorts ? { metroPorts: options.metroPorts } : {}),\n\t\t\t...(options.objectWebhooks?.length\n\t\t\t\t? {\n\t\t\t\t\t\trelayedBuckets: options.objectWebhooks.map((hook) => hook.bucket),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t});\n\t\t// `gkm test` hands no process a telemetry key.\n\t\tconst env = exports\n\t\t\t? resolved\n\t\t\t: scopeTelemetryEnv(resolved, { uses: false, serviceName: project });\n\t\t// Pointed at whether or not it exists yet: the copy below fills it in,\n\t\t// and anything that reads the environment starts after this returns.\n\t\tif (plan.containers.includes('caddy')) {\n\t\t\tenv.NODE_EXTRA_CA_CERTS = join(root, LOCAL_CA_PATH);\n\t\t}\n\t\treturn env;\n\t};\n\tconst env = envWith(options.credentials);\n\n\tconst result: ReconcileResult = {\n\t\tstage,\n\t\tplan,\n\t\tcompose,\n\t\tports,\n\t\tmoved,\n\t\tservices,\n\t\tenv,\n\t\tcredentials: options.credentials,\n\t\tlogins: [],\n\t\tprovisioned: [],\n\t\tfakes: options.fakes ?? {},\n\t\thash,\n\t\tchanged: false,\n\t};\n\n\tconst recorded = await loadState(root, stage);\n\tconst postgresPort = ports[primaryPortKey('postgres')];\n\tconst converged =\n\t\trecorded?.hash === hash &&\n\t\t// The file is gitignored and derived; a fresh checkout with the state\n\t\t// still around must write it rather than trust a hash of nothing.\n\t\texistsSync(composePath) &&\n\t\t(!start ||\n\t\t\t(await docker.healthy(composePath, running, {\n\t\t\t\tmounted: CHECKOUT_MOUNTS,\n\t\t\t}))) &&\n\t\t// Every checkout shares one Postgres, so another one's test teardown can\n\t\t// drop a database this checkout's state still records as created.\n\t\t(!start ||\n\t\t\t!provision ||\n\t\t\tpostgresPort === undefined ||\n\t\t\t(await databasesExist(\n\t\t\t\tsql(postgresPort, options.credentials.postgres),\n\t\t\t\tpostgresDatabaseNames(plan),\n\t\t\t)));\n\n\t// The fast path, and the reason reconciling on every start is acceptable.\n\tif (converged) return result;\n\n\t// Owner-only: it carries the containers' generated logins.\n\tawait write(composePath, toYaml(compose), 0o600);\n\n\t// Before the containers: Caddy reads these at startup, and mounting a file\n\t// that does not exist yet gets a directory instead.\n\tif (plan.containers.includes('caddy')) {\n\t\tawait write(join(root, CADDYFILE_PATH), caddyfileRoot());\n\t\tawait write(join(root, caddySitesPath(stage)), caddyfile);\n\t\tawait pruneCaddySites(root, [stage, options.localStage, TEST_STAGE]);\n\t}\n\n\tif (start && running.length > 0) {\n\t\toptions.progress?.(\n\t\t\t`🐳 Starting ${running.join(', ')} — the first start pulls each image, which can take a few minutes`,\n\t\t);\n\t\tawait docker.up(\n\t\t\tcomposePath,\n\t\t\trunning,\n\t\t\toptions.progress ? { show: true } : {},\n\t\t);\n\t}\n\n\t// A running Caddy does not notice a changed import, so the routes this\n\t// reconcile just wrote are inert until it is told. Failing is not fatal: the\n\t// container may have only this second come up, in which case it already read\n\t// them.\n\tif (start && plan.containers.includes('caddy')) {\n\t\tawait docker.reload(composePath, 'caddy').catch(() => {});\n\t}\n\n\t// After `up`, because Caddy generates its CA on first start — and only then,\n\t// so copying earlier gets nothing.\n\tif (start && plan.containers.includes('caddy')) {\n\t\tawait docker\n\t\t\t.copyOut(\n\t\t\t\tcomposePath,\n\t\t\t\t'caddy',\n\t\t\t\tCADDY_ROOT_IN_CONTAINER,\n\t\t\t\tjoin(root, LOCAL_CA_PATH),\n\t\t\t)\n\t\t\t.catch(() => {\n\t\t\t\t// Not fatal. Without it, `https://` local addresses fail to verify\n\t\t\t\t// and say so clearly; taking the whole reconcile down would be a\n\t\t\t\t// worse trade for a developer who is not using them yet.\n\t\t\t});\n\t}\n\n\t// A container that already had data may have been made with another\n\t// login — an older gkm's fixed one. Brought in line before anything signs\n\t// in, and where one cannot be, its login is what is used.\n\tconst checked =\n\t\tstart && plan.containers.length > 0\n\t\t\t? await logins({\n\t\t\t\t\tcredentials: options.credentials,\n\t\t\t\t\tcontainers: plan.containers,\n\t\t\t\t\tports: {\n\t\t\t\t\t\t...(postgresPort !== undefined ? { postgres: postgresPort } : {}),\n\t\t\t\t\t\t...(ports[primaryPortKey('minio')] !== undefined\n\t\t\t\t\t\t\t? { minio: ports[primaryPortKey('minio')] }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t\t...(docker.exec\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\texec: (service: string, argv: readonly string[]) =>\n\t\t\t\t\t\t\t\t\tdocker.exec!(composePath, service, argv),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t})\n\t\t\t: { credentials: options.credentials, outcomes: [] };\n\tconst credentials = checked.credentials;\n\n\t// Only once the containers are up: there is nothing to create inside a\n\t// container that is not running.\n\tif (start && provision) {\n\t\toptions.progress?.(\n\t\t\t'🗄️ Creating what the constructs declare — databases, roles, buckets, topics',\n\t\t);\n\t}\n\tconst provisioned =\n\t\tstart && provision\n\t\t\t? await create(\n\t\t\t\t\tplan,\n\t\t\t\t\tports,\n\t\t\t\t\tcredentials,\n\t\t\t\t\tsql,\n\t\t\t\t\tbuckets,\n\t\t\t\t\tcarriers,\n\t\t\t\t\tproject,\n\t\t\t\t\t// Only the local stage's buckets post their events: `gkm test`\n\t\t\t\t\t// shares the MinIO, and its uploads are not `gkm dev`'s business.\n\t\t\t\t\tnew Set(\n\t\t\t\t\t\tstage === (options.localStage ?? stage)\n\t\t\t\t\t\t\t? (options.objectWebhooks ?? []).map((hook) => hook.bucket)\n\t\t\t\t\t\t\t: [],\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [];\n\n\tawait saveState(root, { hash, stage });\n\n\treturn {\n\t\t...result,\n\t\t...(credentials === options.credentials\n\t\t\t? {}\n\t\t\t: { env: envWith(credentials) }),\n\t\tcredentials,\n\t\tlogins: checked.outcomes,\n\t\tprovisioned,\n\t\tchanged: true,\n\t};\n}\n\n/**\n * Create the databases, schemas, buckets, topics and queues the plan names.\n *\n * Idempotent throughout, so this runs on every non-converged reconcile rather\n * than being something to remember.\n */\nasync function create(\n\tplan: Plan,\n\tports: PortAssignments,\n\tcredentials: LocalCredentials,\n\tsql: NonNullable<ReconcileOptions['sql']>,\n\tbuckets: NonNullable<ReconcileOptions['buckets']>,\n\temulatorCarriers: NonNullable<ReconcileOptions['carriers']>,\n\t/** Seeds the derived role passwords — see `localRolePassword`. */\n\tproject: string,\n\t/** The buckets, by construct id, whose events MinIO posts on. */\n\twatched: ReadonlySet<string>,\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tconst postgresPort = ports[primaryPortKey('postgres')];\n\tconst statements = postgresStatements(plan, project, credentials.seed);\n\tif (postgresPort !== undefined && statements.length > 0) {\n\t\tapplied.push(\n\t\t\t...(await applyPostgres(\n\t\t\t\tsql(postgresPort, credentials.postgres),\n\t\t\t\tstatements,\n\t\t\t)),\n\t\t);\n\t}\n\n\tconst minioPort = ports[primaryPortKey('minio')];\n\tconst names = bucketNames(plan);\n\tconst policies = bucketPolicies(plan);\n\tconst lifecycles = bucketLifecycles(plan);\n\tif (minioPort !== undefined && (names.length > 0 || policies.length > 0)) {\n\t\tconst client = buckets(minioPort, credentials.minio);\n\n\t\t// Buckets first: a policy or a lifecycle names a bucket, and applying\n\t\t// one to a bucket that does not exist yet fails on the first reconcile\n\t\t// of a new project.\n\t\tif (names.length > 0) applied.push(...(await applyBuckets(client, names)));\n\t\tif (policies.length > 0)\n\t\t\tapplied.push(...(await applyPolicies(client, policies)));\n\t\tif (lifecycles.length > 0)\n\t\t\tapplied.push(...(await applyLifecycles(client, lifecycles)));\n\t\t// After the buckets, and only once MinIO runs with the targets: a rule\n\t\t// naming a target MinIO was not started with is refused.\n\t\tif (names.length > 0) {\n\t\t\tapplied.push(\n\t\t\t\t...(await applyNotifications(\n\t\t\t\t\tclient,\n\t\t\t\t\tplan.resources\n\t\t\t\t\t\t.filter((r) => r.provisions && r.kind === 'objects')\n\t\t\t\t\t\t.map((r) => ({ id: r.id, name: r.name })),\n\t\t\t\t\twatched,\n\t\t\t\t)),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst emulatorPort = ports[primaryPortKey('localstack')];\n\tconst carriers = carrierNames(plan);\n\tif (\n\t\temulatorPort !== undefined &&\n\t\tcarriers.topics.length + carriers.queues.length > 0\n\t) {\n\t\tapplied.push(\n\t\t\t...(await applyCarriers(\n\t\t\t\temulatorCarriers(emulatorPort, credentials.emulator),\n\t\t\t\tcarriers,\n\t\t\t)),\n\t\t);\n\t}\n\n\treturn applied;\n}\n\n/**\n * The host ports of containers already running.\n *\n * Keyed the same way allocation keys them, so the two merge without either\n * knowing about the other.\n */\nasync function observedPorts(\n\tdocker: Docker,\n\tcomposePath: string,\n\tcontainers: readonly string[],\n\tfakes?: Plan['fakes'],\n): Promise<PortAssignments> {\n\tconst observed: Record<string, number> = {};\n\n\tfor (const container of containers) {\n\t\tfor (const port of portsOf(container, fakes)) {\n\t\t\tconst running = await docker.publishedPort(\n\t\t\t\tcomposePath,\n\t\t\t\tcontainer,\n\t\t\t\tport.inside,\n\t\t\t);\n\t\t\tif (running !== undefined) observed[port.key] = running;\n\t\t}\n\t}\n\n\treturn observed;\n}\n\n/** Write a file only when its content would change, so mtimes stay meaningful. */\n/**\n * Remove the routes of stages this project no longer reconciles.\n *\n * Only the local stage and `test` are ever written, so any other file is left\n * over from a stage that was renamed — `development` becoming `dev`. Caddy\n * imports every file, and the leftover declares the same hosts as its\n * replacement: it refuses the whole config as ambiguous, and every URL behind\n * the edge goes with it.\n */\nasync function pruneCaddySites(\n\troot: string,\n\tstages: ReadonlyArray<string | undefined>,\n): Promise<void> {\n\tconst dir = dirname(join(root, caddySitesPath(TEST_STAGE)));\n\tconst keep = new Set(stages.map((stage) => stage && `${stage}.caddy`));\n\n\tfor (const file of await readdir(dir)) {\n\t\tif (file.endsWith('.caddy') && !keep.has(file)) {\n\t\t\tawait rm(join(dir, file));\n\t\t}\n\t}\n}\n\nasync function write(\n\tpath: string,\n\tcontent: string,\n\tmode?: number,\n): Promise<void> {\n\ttry {\n\t\tif ((await readFile(path, 'utf-8')) === content) {\n\t\t\tif (mode !== undefined) await chmod(path, mode);\n\t\t\treturn;\n\t\t}\n\t} catch {\n\t\t// Absent or unreadable — write it.\n\t}\n\n\tawait mkdir(dirname(path), { recursive: true });\n\tawait writeFile(path, content, mode === undefined ? {} : { mode });\n\tif (mode !== undefined) await chmod(path, mode);\n}\n","/**\n * Workspace config → reconcile.\n *\n * Nothing here is read from a `services:` block — there is none. Which\n * containers exist comes from the manifest; which backend a cache or a broker\n * resolves to comes from the deploy target; and an image pin is the project's\n * own `docker-compose.yml`, merged over the generated file.\n *\n * Shared by `gkm setup`, `gkm dev`, and `gkm test` so all three converge on the\n * same state, differing only in the stage they pass.\n */\n\nimport { type ConstructManifest, provisionOrder } from '@geekmidas/manifest';\nimport {\n\tprocessorUnits,\n\tWorkerHasNoApp,\n\ttype WorkerUnit,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { loadPortState, savePortState } from '../credentials/index.js';\nimport { objectsRoute } from '../generators/subscriberRoute.js';\nimport {\n\tcacheBackendFor,\n\teventsBackendFor,\n\tproviderOf,\n} from '../workspace/backends.js';\nimport { appKey } from '../workspace/derive.js';\nimport { allConstructGlobs } from '../workspace/index.js';\nimport { TEST_STAGE } from '../workspace/stages.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { appServices } from './apps.js';\nimport { type BoundSubscriber, discover } from './discover.js';\nimport { readCredentialFakes, readFakes } from './fakes.js';\nimport {\n\tinboxRelayToken,\n\tinboxRelayWorker,\n\tinboxWebhookUrl,\n} from './inboxRelay';\nimport { type ReconcileResult, reconcile } from './index.js';\nimport {\n\tloadLocalCredentials,\n\tsaveLocalCredentials,\n} from './localCredentials.js';\nimport {\n\tHOST_GATEWAY,\n\ttype ObjectWebhook,\n\tobjectsWebhookToken,\n\twatchedBuckets,\n} from './objectEvents.js';\nimport { planFor } from './plan.js';\n\n/**\n * Every constructs glob in the workspace, resolved against its app.\n *\n * Absolute because discovery globs from a single cwd while apps live in\n * different directories.\n */\nexport function constructGlobs(workspace: NormalizedWorkspace): string[] {\n\treturn allConstructGlobs(workspace);\n}\n\n/** The backends a workspace's target implies, as the plan takes them. */\nexport function backendsOf(workspace: NormalizedWorkspace) {\n\tconst on = providerOf(workspace);\n\treturn { events: eventsBackendFor(on), cache: cacheBackendFor(on) };\n}\n\n/**\n * The containers a workspace's declarations imply, without reconciling.\n *\n * The same derivation `reconcileWorkspace` makes, available to callers that\n * need to know *what would run* without starting anything or writing ports —\n * `gkm setup` deciding which credentials to generate, `gkm docker` writing a\n * compose file. Those used to each read a boolean per service out of config,\n * which is how a container could exist because config asked for one rather than\n * because something declared it.\n */\nexport async function derivedContainers(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\tmanifest?: ConstructManifest,\n): Promise<readonly string[]> {\n\tconst found =\n\t\tmanifest ??\n\t\t(await discover({\n\t\t\tpatterns: constructGlobs(workspace),\n\t\t\tcwd: workspace.root,\n\t\t}));\n\n\t// No fakes: they run only for `gkm test` and `gkm dev --fake`, and the\n\t// commands asking this — `setup`, `secrets:*`, `docker` — are neither.\n\treturn planFor(found, stage, provisionOrder(found), {\n\t\tlocalStage: workspace.stages.local,\n\t\t...backendsOf(workspace),\n\t}).containers;\n}\n\nexport interface WorkspaceReconcileOptions {\n\tstage: string;\n\t/** Start containers and wait for health. */\n\tstart?: boolean;\n\t/** A manifest already in hand — the dev watcher has one; setup does not. */\n\tmanifest?: ConstructManifest;\n\t/**\n\t * Point every external API at its fake (`test/fakes/<id>.ts`) instead of\n\t * the provider, and hand every credential with a fake its fake's value —\n\t * `gkm dev --fake`. Always so for the test stage; otherwise an external\n\t * API is the real one, at its URL for this stage, and a credential the\n\t * stage's own.\n\t */\n\tfake?: boolean;\n\t/** Told each slow step as it starts — see `ReconcileOptions.progress`. */\n\tprogress?: (message: string) => void;\n}\n\n/**\n * Set by `gkm dev --fake` for the apps it starts. Each app's own `gkm dev`\n * reconciles too, and must answer the way the workspace did.\n */\nexport const FAKE_ENV = 'GKM_FAKE';\n\n/**\n * Whether third parties are faked — external APIs, and credentials with a\n * fake: always for `gkm test`, and for `gkm dev`\n * only when asked — by `--fake`, or by the workspace that started this app\n * with it. Never for anything acting on a deployed stage.\n */\nexport function fakesApply(\n\tstage: string,\n\tfake?: boolean,\n\tenv: NodeJS.ProcessEnv = process.env,\n): boolean {\n\treturn fake === true || stage === TEST_STAGE || env[FAKE_ENV] === '1';\n}\n\n/**\n * Reconcile a workspace for one stage.\n *\n * Ports are loaded and saved around the call rather than inside it, so the loop\n * stays a pure-ish function of its inputs and the store keeps its single owner.\n */\nexport async function reconcileWorkspace(\n\tworkspace: NormalizedWorkspace,\n\toptions: WorkspaceReconcileOptions,\n): Promise<ReconcileResult & { manifest: ConstructManifest }> {\n\t// Discovered here even when a manifest was handed in: where each worker's\n\t// background work and each bucket's subscribers are is only discovery's.\n\tconst background: Record<string, string[]> = {};\n\tconst subscribers: Record<string, BoundSubscriber[]> = {};\n\tconst discovered = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tbackground,\n\t\tsubscribers,\n\t});\n\tconst manifest = options.manifest ?? discovered;\n\tconst faked = fakesApply(options.stage, options.fake);\n\tconst fakes = faked ? await readFakes(workspace.root, manifest) : {};\n\tconst credentialFakes = faked\n\t\t? await readCredentialFakes(workspace.root, manifest)\n\t\t: {};\n\n\t// Generated the first time anything needs them, and read back after: one\n\t// set per machine and workspace, shared by the local stage and `test`,\n\t// which run on the same containers.\n\tconst { credentials } = await loadLocalCredentials(workspace);\n\n\tconst objectWebhooks = localObjectWebhooks(workspace, manifest, {\n\t\tbackground,\n\t\tsubscribers,\n\t\tseed: credentials.seed,\n\t});\n\n\tconst inboxRelay = localInboxWebhook(workspace, manifest, {\n\t\tbackground,\n\t\tsubscribers,\n\t\tseed: credentials.seed,\n\t});\n\n\tconst result = await reconcile({\n\t\tcredentials,\n\t\troot: workspace.root,\n\t\tproject: workspace.name,\n\t\tmanifest,\n\t\tstage: options.stage,\n\t\tlocalStage: workspace.stages.local,\n\t\t...backendsOf(workspace),\n\t\t...(workspace.protectedSubdomains\n\t\t\t? { protectedSubdomains: workspace.protectedSubdomains }\n\t\t\t: {}),\n\t\tsaved: await loadPortState(workspace.root),\n\t\taddresses: surfaceAddresses(workspace, manifest),\n\t\tprocessorAddresses: processorAddresses(workspace, manifest),\n\t\tmetroPorts: metroPorts(workspace, manifest),\n\t\tfakes,\n\t\tcredentialFakes,\n\t\t...(objectWebhooks.length > 0 ? { objectWebhooks } : {}),\n\t\t...(inboxRelay ? { inboxRelay } : {}),\n\t\tapps: (containers) =>\n\t\t\tappServices(\n\t\t\t\tworkspace,\n\t\t\t\tmanifest,\n\t\t\t\tcontainers,\n\t\t\t\tcredentials,\n\t\t\t\tfakes,\n\t\t\t\tcredentialFakes,\n\t\t\t),\n\t\t...(options.start === undefined ? {} : { start: options.start }),\n\t\t...(options.progress ? { progress: options.progress } : {}),\n\t});\n\n\tawait savePortState(workspace.root, { ...result.ports });\n\tfor (const { key, from, to } of result.moved) {\n\t\tconsole.log(\n\t\t\t`⚠️ Port ${from} (${key}) is held by another process; moved to ${to}.`,\n\t\t);\n\t}\n\n\t// A container that could not be moved to its generated login keeps the\n\t// one it takes, and that is what later runs use.\n\tif (result.credentials !== credentials) {\n\t\tawait saveLocalCredentials(workspace, result.credentials);\n\t}\n\tfor (const outcome of result.logins) {\n\t\tif (outcome.notice) console.log(outcome.notice);\n\t}\n\n\t// With the manifest, so `gkm dev` can say what the workspace declares\n\t// without discovering it a second time.\n\treturn { ...result, manifest };\n}\n\n/**\n * Where MinIO posts each watched bucket's events under `gkm dev`: the dev\n * server of the app that builds the worker running the bucket's subscribers,\n * on the host, on that app's port — the process that relays them onto the\n * broker.\n *\n * None where the broker is SNS: there a bucket's events come from a topic, and\n * nothing relays them. None for a worker no app can build — `gkm build` says\n * so; a dev loop has nothing to post to.\n */\nexport function localObjectWebhooks(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\toptions: {\n\t\tbackground: Readonly<Record<string, readonly string[]>>;\n\t\tsubscribers: Readonly<Record<string, readonly BoundSubscriber[]>>;\n\t\t/** The local logins' seed, which derives each bucket's token. */\n\t\tseed?: string;\n\t},\n): ObjectWebhook[] {\n\tif (backendsOf(workspace).events === 'sns') return [];\n\n\tconst watched = watchedBuckets(manifest, options.subscribers);\n\tif (watched.size === 0) return [];\n\n\tlet units: WorkerUnit[];\n\ttry {\n\t\tunits = workerUnits(workspace, manifest, options.background);\n\t} catch (error) {\n\t\tif (error instanceof WorkerHasNoApp) return [];\n\t\tthrow error;\n\t}\n\n\tconst hooks: ObjectWebhook[] = [];\n\tfor (const [bucket, worker] of watched) {\n\t\tconst app = units.find((unit) => unit.id === worker)?.app;\n\t\tconst port = app ? workspace.apps[app]?.port : undefined;\n\t\tif (!port) continue;\n\t\thooks.push({\n\t\t\tbucket,\n\t\t\tendpoint: `http://${HOST_GATEWAY}:${port}${objectsRoute(bucket)}`,\n\t\t\ttoken: objectsWebhookToken(workspace.name, bucket, options.seed),\n\t\t});\n\t}\n\treturn hooks;\n}\n\n/**\n * Where Mailpit posts each message it receives, locally: the relay route on\n * the dev server of the app that builds the worker running the inbox\n * subscribers, through the host's gateway — as MinIO reaches a bucket's\n * subscribers. `undefined` with no inbox subscriber, or none an app builds.\n */\nexport function localInboxWebhook(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\toptions: {\n\t\tbackground: Readonly<Record<string, readonly string[]>>;\n\t\tsubscribers: Readonly<Record<string, readonly BoundSubscriber[]>>;\n\t\tseed?: string;\n\t},\n): string | undefined {\n\tconst worker = inboxRelayWorker(manifest, options.subscribers);\n\tif (!worker) return undefined;\n\n\tlet units: WorkerUnit[];\n\ttry {\n\t\tunits = workerUnits(workspace, manifest, options.background);\n\t} catch (error) {\n\t\tif (error instanceof WorkerHasNoApp) return undefined;\n\t\tthrow error;\n\t}\n\tconst app = units.find((unit) => unit.id === worker)?.app;\n\tconst port = app ? workspace.apps[app]?.port : undefined;\n\tif (!port) return undefined;\n\treturn inboxWebhookUrl(\n\t\t`http://${HOST_GATEWAY}:${port}`,\n\t\tinboxRelayToken(workspace.name, options.seed),\n\t);\n}\n\n/**\n * Where each mobile app's Metro runs: its app's port, which `gkm exec` hands\n * Expo as `RCT_METRO_PORT`. Kept apart from the surfaces' addresses — a phone\n * reaches Metro by `exp://`, not through the edge.\n */\nexport function metroPorts(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): Record<string, number> {\n\tconst ports: Record<string, number> = {};\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration.kind !== 'mobile-app') continue;\n\t\tconst port = workspace.apps[appKey(id)]?.port;\n\t\tif (port) ports[id] = port;\n\t}\n\treturn ports;\n}\n\n/**\n * Where each file server's processors answer locally: the dev server of the\n * app holding them, which `gkm dev` mounts them on — the same app whose build\n * writes their unit deployed.\n */\nexport function processorAddresses(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): Record<string, string> {\n\tconst addresses: Record<string, string> = {};\n\tfor (const unit of processorUnits(workspace, manifest)) {\n\t\tconst port = workspace.apps[unit.app]?.port;\n\t\tif (port) addresses[unit.id] = localAddress(port);\n\t}\n\treturn addresses;\n}\n\n/**\n * Where each declared surface and site answers locally.\n *\n * The addresses come from the ports the workspace already assigns; which\n * construct sits at which one comes from the manifest. That split is the point:\n * this used to answer \"who may call whom\" by listing every app the workspace\n * runs, which is a different question that happened to give the same answer in\n * a single-repo workspace and no answer at all deployed. Now it answers only\n * \"where does this construct answer\", and the graph answers the rest.\n *\n * A site is matched to its app by `path`, because that is the one thing a site\n * declaration and a workspace app both name. Surfaces are matched to the\n * backend app: every `rest-api` in a process answers on that process's port, so\n * an app serving both its own API and an auth server publishes one address\n * twice — which is exactly what it does at runtime.\n */\nexport function surfaceAddresses(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\t/**\n\t * How an app is addressed: on the host by default, or — for the compose\n\t * apps — by service name on the compose network.\n\t */\n\tat: (app: string, port: number) => string = (_app, port) =>\n\t\tlocalAddress(port),\n): Record<string, string> {\n\tconst addresses: Record<string, string> = {};\n\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (\n\t\t\tdeclaration.kind !== 'rest-api' &&\n\t\t\tdeclaration.kind !== 'websocket-api' &&\n\t\t\tdeclaration.kind !== 'site'\n\t\t)\n\t\t\tcontinue;\n\n\t\t// Every site and every surface is its own app, keyed by its id the way\n\t\t// the derivation keyed it.\n\t\tconst host = appKey(id);\n\t\tconst port = workspace.apps[host]?.port;\n\n\t\tif (port) addresses[id] = at(host, port);\n\t}\n\n\treturn addresses;\n}\n\n/** Where a local process answers, given the port the workspace gave it. */\nfunction localAddress(port: number): string {\n\treturn `http://localhost:${port}`;\n}\n","/**\n * The apps, as services beside the containers their constructs derive.\n *\n * `gkm docker` used to write these by hand: every backend got\n * `DATABASE_URL=postgresql://…@postgres:5432/app` and `REDIS_URL=redis://redis`,\n * which was right only for a project whose single database happened to be\n * called `Database` — an `Orders` database publishes `ORDERS_URL`, a schema\n * tenant has a URL of its own, and buckets and mail were not wired at all.\n *\n * Now an app's environment is exactly what reconcile hands `gkm dev`: every key\n * the declared constructs provide, from the same derivation. The only\n * difference is where the addresses point — at the containers by service name\n * on the compose network, rather than at `localhost` on the ports published for\n * the host.\n *\n * Always from the *local* stage's plan, whichever stage is being reconciled:\n * `gkm test` rewrites the same file, and running the tests must not quietly\n * point these apps at the test databases.\n */\n\nimport {\n\ttype ConstructManifest,\n\tdependenciesOf,\n\tprovideKey,\n\tprovisionOrder,\n\tpublicEnvFor,\n\tTELEMETRY_KEYS,\n} from '@geekmidas/manifest';\nimport { publicBuildValues } from '../compose/siteBuild.js';\nimport { composeBuildPaths } from '../docker/layout.js';\nimport { findBuildRoot } from '../docker/templates.js';\nimport { appTelemetry, scopeTelemetryEnv } from '../telemetry/edges.js';\nimport { appKey } from '../workspace/derive.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport type { ComposeService } from './compose.js';\nimport { portKeys, portsOf } from './containers.js';\nimport { eventsEdgeBucket, workerEdges } from './edges.js';\nimport { type EnvOptions, envFor } from './env.js';\nimport { INBOX_RELAY_TOKEN_KEY } from './inboxRelay.js';\nimport type { LocalCredentials } from './localCredentials.js';\nimport { type Plan, type PlanOptions, planFor } from './plan.js';\nimport { backendsOf, surfaceAddresses } from './workspace.js';\n\n/** The profile app services carry, so `gkm dev` starts only the containers. */\nexport const APPS_PROFILE = 'apps';\n\n/**\n * Where an app's image is built from.\n *\n * An app at the project root is a single-app project, whose `gkm docker`\n * writes `.gkm/docker/Dockerfile`; a workspace writes one per app.\n */\nexport function dockerfileOf(appName: string, path: string): string {\n\treturn path === '.'\n\t\t? '.gkm/docker/Dockerfile'\n\t\t: `.gkm/docker/Dockerfile.${appName}`;\n}\n\n/**\n * Every construct key, addressed across the compose network.\n *\n * `envFor` is asked with a placeholder port for every port key, so each\n * `localhost:<placeholder>` in its answer names exactly one container port —\n * two containers listening on the same port inside cannot be confused — and is\n * rewritten to `<container>:<inside>`.\n */\nexport function inNetworkEnv(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\t/** The workspace's local logins — see `localCredentials.ts`. */\n\tcredentials: LocalCredentials,\n\t/**\n\t * External APIs' fakes. An image fake is a container on the network like\n\t * any other; a module fake is served by `gkm dev` on the host, which an app\n\t * container does not reach, so its URL is left as the host sees it.\n\t */\n\tfakes: PlanOptions['fakes'] = {},\n): Record<string, string> {\n\treturn networkEnv(localPlan(workspace, manifest, fakes), {\n\t\tproject: workspace.name,\n\t\tcredentials,\n\t\tseed: credentials.seed,\n\t\taddresses: surfaceAddresses(\n\t\t\tworkspace,\n\t\t\tmanifest,\n\t\t\t(app, port) => `http://${app}:${port}`,\n\t\t),\n\t});\n}\n\n/**\n * The local stage's plan, which the app services are always written from.\n *\n * Without the edge: these apps reach each other by service name and a browser\n * reaches them on the ports this file publishes. Behind the edge every\n * surface resolved to its `*.localhost` host on the edge's port, which the\n * rewrite to the compose network then turned into an address nothing answers.\n */\nfunction localPlan(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tfakes: PlanOptions['fakes'] = {},\n\tcredentialFakes: PlanOptions['credentialFakes'] = {},\n): Plan {\n\treturn planFor(manifest, workspace.stages.local, provisionOrder(manifest), {\n\t\tlocalStage: workspace.stages.local,\n\t\t...backendsOf(workspace),\n\t\t...(workspace.protectedSubdomains\n\t\t\t? { protectedSubdomains: workspace.protectedSubdomains }\n\t\t\t: {}),\n\t\tfakes,\n\t\tcredentialFakes,\n\t\tedge: false,\n\t});\n}\n\n/**\n * The values a site's bundler inlines, by the name it inlines them under —\n * `{ VITE_API_URL: 'http://localhost:3000' }`.\n *\n * Build arguments, not environment: a static bundle is finished when it is\n * built, so a value handed to its container at runtime reaches nothing. And\n * addresses a *browser* can open, since that is where the bundle runs — the\n * host's port for each app, never a name on the compose network.\n */\nexport function sitePublicArgs(\n\tmanifest: ConstructManifest,\n\tappName: string,\n\t/** Every key the stage resolves, with surfaces at their public addresses. */\n\tenv: Readonly<Record<string, string>>,\n): Record<string, string> {\n\tconst declaration = Object.entries(manifest).find(\n\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t)?.[1];\n\tif (declaration?.kind !== 'site') return {};\n\n\t// The image build's own rule, so a site built here gets what a stage's\n\t// image does. No stage secrets: the local stage's reach a site through\n\t// `gkm exec`, which hands it every one.\n\treturn publicBuildValues(declaration, manifest, (key) => env[key], {});\n}\n\n/**\n * Every key a plan resolves, with each container addressed by its service\n * name on the compose network — `postgres:5432` rather than the port\n * published for the host.\n *\n * The addresses of surfaces and sites are the caller's: on the compose\n * network for a service another service calls, public for what a browser is\n * handed. `gkm compose` asks twice, once for each.\n */\nexport function networkEnv(\n\tplan: Plan,\n\toptions: Omit<EnvOptions, 'ports'>,\n\t/**\n\t * The name a container is reached by, where it is not its service name —\n\t * a stack behind a shared edge reaches its public services by an alias\n\t * unique on the network the edge shares.\n\t */\n\thostOf: (container: string) => string = (container) => container,\n): Record<string, string> {\n\tconst placeholders: Record<string, number> = {};\n\tconst targets = new Map<number, string>();\n\tlet next = 49_152;\n\tfor (const container of [...plan.containers].sort()) {\n\t\tfor (const port of portsOf(container, plan.fakes)) {\n\t\t\tplaceholders[port.key] = next;\n\t\t\ttargets.set(next, `${hostOf(container)}:${port.inside}`);\n\t\t\tnext += 1;\n\t\t}\n\t}\n\t// Every key allocation would have assigned, so envFor finds each one.\n\tfor (const key of portKeys(plan.containers, plan.fakes)) {\n\t\tplaceholders[key] ??= next++;\n\t}\n\n\tconst env = envFor(plan, { ...options, ports: placeholders });\n\n\tconst rewrite = (value: string) =>\n\t\tvalue.replace(/(?:localhost|127\\.0\\.0\\.1):(\\d+)/g, (match, port) => {\n\t\t\treturn targets.get(Number(port)) ?? match;\n\t\t});\n\n\treturn Object.fromEntries(\n\t\tObject.entries(env).map(([key, value]) => [key, rewrite(value)]),\n\t);\n}\n\n/**\n * The keys one app's environment may hold: what its own declaration provides\n * and requires, and what each construct it has an edge to provides.\n *\n * The edges, not the manifest. Every app used to be handed every key the\n * workspace resolved — a web app got the database's owner URL and the auth\n * server's signing secret, and the API got the auth server's database — which\n * is exactly what a declared edge exists to rule out. A deploy composes an\n * app's environment from its edges; so does this.\n *\n * One hop: a surface an app calls is reached over HTTP, so its URL is the\n * app's business and its database is not. A site also gets the public\n * variant of each key its bundle inlines (`NEXT_PUBLIC_API_URL`).\n *\n * A surface's process runs its own endpoints and nothing else. A Worker's\n * crons, queue consumers and subscribers run in the worker's own process\n * (`workerEnvKeys`), so no surface is handed a worker's edges — however its\n * endpoints were found.\n *\n * `undefined` for an app no declaration describes, which gets nothing but its\n * port.\n */\nexport function appEnvKeys(\n\tmanifest: ConstructManifest,\n\tappName: string,\n): Set<string> | undefined {\n\tconst entry = Object.entries(manifest).find(\n\t\t([id, d]) =>\n\t\t\t(d.kind === 'rest-api' ||\n\t\t\t\td.kind === 'websocket-api' ||\n\t\t\t\td.kind === 'site' ||\n\t\t\t\td.kind === 'mobile-app') &&\n\t\t\tappKey(id) === appName,\n\t);\n\tif (!entry) return undefined;\n\tconst [, declaration] = entry;\n\n\tconst keys = new Set<string>([\n\t\t...(declaration.provides ?? []),\n\t\t...(declaration.requires ?? []),\n\t\t// A handler the surface declares itself — an auth server's wildcard —\n\t\t// states what it needs on the handler.\n\t\t...(declaration.kind === 'rest-api'\n\t\t\t? declaration.endpoints.flatMap((endpoint) => endpoint.requires ?? [])\n\t\t\t: []),\n\t]);\n\n\t// A surface's own edges and its endpoints' — every route it serves.\n\tconst edges = dependenciesOf(declaration).map((edge) => edge.target);\n\taddEdgeKeys(\n\t\tmanifest,\n\t\tedges,\n\t\tkeys,\n\t\tdeclaration.kind === 'site' || declaration.kind === 'mobile-app',\n\t);\n\n\tif (declaration.kind === 'site' || declaration.kind === 'mobile-app') {\n\t\t// A site's edge to a `Telemetry` node hands it none of the node's keys:\n\t\t// an exporter's endpoint and headers are a server's, and a site's\n\t\t// environment is a bundle's.\n\t\tfor (const key of TELEMETRY_KEYS) keys.delete(key);\n\t\tfor (const key of Object.keys(publicEnvFor(declaration, manifest))) {\n\t\t\tkeys.add(key);\n\t\t}\n\t}\n\n\treturn keys;\n}\n\n/**\n * The keys a Worker's own process reads: what the worker and everything built\n * from it declared an edge to — the queues its consumers drain and the topics\n * its subscribers are bound to among them (see `workerEdges`) — and the\n * broker its crons schedule through.\n *\n * `undefined` when no worker has that id.\n */\nexport function workerEnvKeys(\n\tmanifest: ConstructManifest,\n\tworkerId: string,\n): Set<string> | undefined {\n\tconst declaration = manifest[workerId];\n\tif (declaration?.kind !== 'worker') return undefined;\n\n\tconst keys = new Set<string>([\n\t\t...(declaration.provides ?? []),\n\t\t...(declaration.requires ?? []),\n\t\t// A server schedules its crons through the broker.\n\t\t'EVENT_PUBLISHER_CONNECTION_STRING',\n\t]);\n\taddEdgeKeys(manifest, workerEdges(manifest, workerId), keys);\n\treturn keys;\n}\n\n/** What each construct an edge reaches hands the process that reaches it. */\n/**\n * The keys a file server's processor unit reads: its bucket's, and what each\n * of its processors depends on. `undefined` for a file server with none.\n */\nexport function processorEnvKeys(\n\tmanifest: ConstructManifest,\n\tfileServerId: string,\n): Set<string> | undefined {\n\tconst server = manifest[fileServerId];\n\tif (server?.kind !== 'file-server' || !server.processors?.length) {\n\t\treturn undefined;\n\t}\n\n\tconst keys = new Set<string>();\n\taddEdgeKeys(\n\t\tmanifest,\n\t\t[\n\t\t\tserver.of,\n\t\t\t...server.processors.flatMap((p) => p.dependencies.map((d) => d.target)),\n\t\t],\n\t\tkeys,\n\t);\n\treturn keys;\n}\n\nfunction addEdgeKeys(\n\tmanifest: ConstructManifest,\n\tedges: readonly string[],\n\tkeys: Set<string>,\n\t/** The process is a bundle a browser or a phone runs. */\n\tclient = false,\n): void {\n\tfor (const id of edges) {\n\t\t// A bucket's events: its subscribers' process reads where they are\n\t\t// delivered from, and nothing else of the bucket.\n\t\tconst bucket = eventsEdgeBucket(id);\n\t\tif (bucket) {\n\t\t\tif (manifest[bucket]?.kind === 'objects') {\n\t\t\t\tkeys.add(provideKey(bucket, 'eventsConnectionString'));\n\t\t\t\tkeys.add(provideKey(bucket, 'eventsToken'));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst target = manifest[id];\n\t\tif (!target) continue;\n\t\t// A surface is reached over HTTP, so its caller is given its address\n\t\t// and nothing else it provides: who it trusts and the domain its\n\t\t// cookies are scoped to are the surface's own settings, read by its own\n\t\t// process. For an auth server that is the whole point — the API gets\n\t\t// AUTH_URL, and the auth app alone holds its secret, tenant and mailer.\n\t\tif (target.kind === 'rest-api') {\n\t\t\tkeys.add(provideKey(id, 'url'));\n\t\t\tcontinue;\n\t\t}\n\t\t// A WebSocket surface is opened at its address, and sent to through its\n\t\t// publisher — which writes to every socket, so a client is handed the\n\t\t// address alone.\n\t\tif (target.kind === 'websocket-api') {\n\t\t\tkeys.add(provideKey(id, 'url'));\n\t\t\tif (!client) keys.add(provideKey(id, 'publisherConnectionString'));\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of target.provides ?? []) keys.add(key);\n\n\t\t// Locally Mailpit posts what an inbox receives to the worker that\n\t\t// runs its subscriber, with this token.\n\t\tif (target.kind === 'inbox') keys.add(INBOX_RELAY_TOKEN_KEY);\n\n\t\tif (target.kind === 'queue' || target.kind === 'topic') {\n\t\t\tkeys.add('EVENT_PUBLISHER_CONNECTION_STRING');\n\t\t}\n\t\t// The S3 client's shared key pair, for a bucket whose URL carries no key\n\t\t// of its own — handed over only where the stage has one. A file server\n\t\t// is reached by its URL alone.\n\t\tif (target.kind === 'objects') {\n\t\t\t// A FileServer is one construct declaring two nodes — the bucket,\n\t\t\t// which the edge points at, and the domain that serves it — and its\n\t\t\t// client reads both: a handler signs uploads to the bucket and hands\n\t\t\t// out URLs on the domain. The domain's address comes with the edge.\n\t\t\tfor (const other of Object.values(manifest)) {\n\t\t\t\tif (other.kind === 'file-server' && other.of === id) {\n\t\t\t\t\tfor (const key of other.provides ?? []) keys.add(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tkeys.add('AWS_ACCESS_KEY_ID');\n\t\t\tkeys.add('AWS_SECRET_ACCESS_KEY');\n\t\t\tkeys.add('AWS_REGION');\n\t\t}\n\t}\n}\n\n/** One compose service per app the workspace runs, behind the apps profile. */\nexport function appServices(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tcontainers: readonly string[],\n\t/** The workspace's local logins — see `localCredentials.ts`. */\n\tcredentials: LocalCredentials,\n\tfakes: PlanOptions['fakes'] = {},\n\t/**\n\t * Each credential's fake value, under `gkm dev --fake` — handed to the\n\t * apps that read the credential, as an external API's fake is.\n\t */\n\tcredentialFakes: PlanOptions['credentialFakes'] = {},\n): Record<string, ComposeService> {\n\tconst plan = localPlan(workspace, manifest, fakes, credentialFakes);\n\tconst derivation = {\n\t\tproject: workspace.name,\n\t\tcredentials,\n\t\tseed: credentials.seed,\n\t};\n\tconst env = networkEnv(plan, {\n\t\t...derivation,\n\t\taddresses: surfaceAddresses(\n\t\t\tworkspace,\n\t\t\tmanifest,\n\t\t\t(app, port) => `http://${app}:${port}`,\n\t\t),\n\t});\n\t// What a browser is handed: each app on the port this file publishes it on.\n\tconst browser = networkEnv(plan, {\n\t\t...derivation,\n\t\taddresses: surfaceAddresses(workspace, manifest),\n\t});\n\tconst services: Record<string, ComposeService> = {};\n\tconst buildRoot = findBuildRoot(workspace.root);\n\n\tfor (const [name, app] of Object.entries(workspace.apps)) {\n\t\t// A mobile app ships through its own toolchain; nothing here runs it.\n\t\tif (app.type === 'mobile' || !app.port) continue;\n\n\t\tconst key = appKey(name);\n\t\tconst health = app.type === 'web' ? '/' : '/health';\n\t\t// Built from the build root — the package manager's, which is above the\n\t\t// workspace when it is nested in a monorepo — by the Dockerfile `gkm\n\t\t// docker` writes under the workspace.\n\t\tconst build = composeBuildPaths({\n\t\t\tcomposeDir: workspace.root,\n\t\t\tbuildRoot,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tdockerfile: dockerfileOf(name, app.path),\n\t\t});\n\t\tconst ports = [`${app.port}:${app.port}`];\n\n\t\t// A site is a bundle: its public URLs are inlined when it is built, so\n\t\t// they are build arguments, and it reads nothing at runtime — no server\n\t\t// env, and nothing to wait for but its own server.\n\t\tif (app.type === 'web') {\n\t\t\tconst args = sitePublicArgs(manifest, name, browser);\n\t\t\tservices[key] = {\n\t\t\t\timage: `${key}:\\${TAG:-latest}`,\n\t\t\t\tbuild: {\n\t\t\t\t\t...build,\n\t\t\t\t\t...(Object.keys(args).length ? { args } : {}),\n\t\t\t\t},\n\t\t\t\tprofiles: [APPS_PROFILE],\n\t\t\t\tports,\n\t\t\t\thealthcheck: healthcheck(app.port, health),\n\t\t\t};\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst allowed = appEnvKeys(manifest, name);\n\t\t// The local stage's telemetry, named for this app, where it has the\n\t\t// edge — and none of it where it has not.\n\t\tconst own = scopeTelemetryEnv(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(env).filter(([envKey]) => allowed?.has(envKey)),\n\t\t\t),\n\t\t\t{\n\t\t\t\tuses: appTelemetry(manifest, name) !== undefined,\n\t\t\t\tserviceName: name,\n\t\t\t\ttelemetry: env,\n\t\t\t},\n\t\t);\n\n\t\tservices[key] = {\n\t\t\timage: `${key}:\\${TAG:-latest}`,\n\t\t\tbuild,\n\t\t\tprofiles: [APPS_PROFILE],\n\t\t\tports,\n\t\t\tenvironment: {\n\t\t\t\tNODE_ENV: 'production',\n\t\t\t\tPORT: String(app.port),\n\t\t\t\t...own,\n\t\t\t},\n\t\t\t// The edge fronts the host's browser; apps talk to each other directly.\n\t\t\t...(containers.some((c) => c !== 'caddy')\n\t\t\t\t? { depends_on: containers.filter((c) => c !== 'caddy') }\n\t\t\t\t: {}),\n\t\t\thealthcheck: healthcheck(app.port, health),\n\t\t};\n\t}\n\n\treturn services;\n}\n\n/** An app's health check: its own server answering on `path`. */\nexport function healthcheck(\n\tport: number,\n\tpath: string,\n): NonNullable<ComposeService['healthcheck']> {\n\treturn {\n\t\ttest: ['CMD', 'wget', '-q', '--spider', `http://localhost:${port}${path}`],\n\t\tinterval: '10s',\n\t\ttimeout: '5s',\n\t\tretries: 5,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAa,wBAAwB;;AAGrC,SAAgB,mBAAmB,cAA8B;CAChE,OAAO,GAAG,wBAAwB;AACnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACiEA,MAAa,aAA6C;CACzD,eAAe;CACf,YAAY;CAEZ,iBAAiB;CACjB,MAAM;AACP;;;;;;;;;AAUA,MAAM,eAAe;;;;;;;;AASrB,MAAa,YAAY;;;;;;;;;AAUzB,SAAgB,SACf,MACA,SAOA,YAA8C,CAAC,GAK/C,qBAAuD,CAAC,GAC1C;CACd,MAAM,OAAO,IAAI,IAAI,KAAK,UAAU,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CACzD,MAAM,QAAqB,CAAC;CAE5B,KAAK,MAAM,YAAY,KAAK,WAAW;EACtC,IAAI,CAAC,WAAW,SAAS,OAAO;EAEhC,MAAM,OAA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