@geekmidas/cli 10.0.0-alpha.189 → 10.0.0-alpha.190
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.
- package/dist/{LegacyStateStore-BI0-sXct.mjs → LegacyStateStore-CWiswz6T.mjs} +2 -2
- package/dist/{LegacyStateStore-BI0-sXct.mjs.map → LegacyStateStore-CWiswz6T.mjs.map} +1 -1
- package/dist/{LegacyStateStore-DSl-Kjhn.cjs → LegacyStateStore-CuSe37fl.cjs} +2 -2
- package/dist/{LegacyStateStore-DSl-Kjhn.cjs.map → LegacyStateStore-CuSe37fl.cjs.map} +1 -1
- package/dist/{LocalStateStore-DlXihNk5.cjs → LocalStateStore-BciJ_DF0.cjs} +2 -2
- package/dist/{LocalStateStore-DlXihNk5.cjs.map → LocalStateStore-BciJ_DF0.cjs.map} +1 -1
- package/dist/{LocalStateStore-CKoytnSh.mjs → LocalStateStore-CLHasLJI.mjs} +2 -2
- package/dist/{LocalStateStore-CKoytnSh.mjs.map → LocalStateStore-CLHasLJI.mjs.map} +1 -1
- package/dist/{S3StateStore-DAQh1WJ_.cjs → S3StateStore-BHLRjoj3.cjs} +4 -4
- package/dist/{S3StateStore-DAQh1WJ_.cjs.map → S3StateStore-BHLRjoj3.cjs.map} +1 -1
- package/dist/{S3StateStore-BWiLJgjA.mjs → S3StateStore-CTiv2_ON.mjs} +4 -4
- package/dist/{S3StateStore-BWiLJgjA.mjs.map → S3StateStore-CTiv2_ON.mjs.map} +1 -1
- package/dist/{SSMStateStore-CwpsKiqW.cjs → SSMStateStore-BqT3MXXb.cjs} +2 -2
- package/dist/{SSMStateStore-CwpsKiqW.cjs.map → SSMStateStore-BqT3MXXb.cjs.map} +1 -1
- package/dist/{SSMStateStore-Dtjc3Tcy.mjs → SSMStateStore-D6qqaem2.mjs} +2 -2
- package/dist/{SSMStateStore-Dtjc3Tcy.mjs.map → SSMStateStore-D6qqaem2.mjs.map} +1 -1
- package/dist/{add-DgoqWfHX.cjs → add-B2OmIQzs.cjs} +4 -4
- package/dist/{add-DgoqWfHX.cjs.map → add-B2OmIQzs.cjs.map} +1 -1
- package/dist/{add-CgR8OZmf.mjs → add-CXwL549o.mjs} +4 -4
- package/dist/{add-CgR8OZmf.mjs.map → add-CXwL549o.mjs.map} +1 -1
- package/dist/{bundler-B0GTqknw.mjs → bundler-CHXyJFsS.mjs} +6 -6
- package/dist/{bundler-B0GTqknw.mjs.map → bundler-CHXyJFsS.mjs.map} +1 -1
- package/dist/{bundler-ZNjpx5xS.cjs → bundler-CLoVtcBi.cjs} +6 -6
- package/dist/{bundler-ZNjpx5xS.cjs.map → bundler-CLoVtcBi.cjs.map} +1 -1
- package/dist/{cli-bjBjd1zg.mjs → cli-Bjua3PaZ.mjs} +4 -4
- package/dist/{cli-bjBjd1zg.mjs.map → cli-Bjua3PaZ.mjs.map} +1 -1
- package/dist/{cli-DqEhTw8n.cjs → cli-DiuUr1Am.cjs} +4 -4
- package/dist/{cli-DqEhTw8n.cjs.map → cli-DiuUr1Am.cjs.map} +1 -1
- package/dist/{clientTelemetry-C3GsvvLK.d.cts → clientTelemetry-DXuYNH-J.d.cts} +2 -2
- package/dist/clientTelemetry-DXuYNH-J.d.cts.map +1 -0
- package/dist/{clientTelemetry-Dcp0jgkV.d.mts → clientTelemetry-eC8VQ6nB.d.mts} +2 -2
- package/dist/clientTelemetry-eC8VQ6nB.d.mts.map +1 -0
- package/dist/{compose-BE2Fi1Bs.mjs → compose-DUOETDhc.mjs} +225 -17
- package/dist/compose-DUOETDhc.mjs.map +1 -0
- package/dist/{compose-QHm47c8E.cjs → compose-gnNrY3NQ.cjs} +226 -17
- package/dist/compose-gnNrY3NQ.cjs.map +1 -0
- package/dist/{config-CDulXPTe.d.mts → config-1zirYXeO.d.mts} +3 -3
- package/dist/{config-B_pfl-ZN.d.cts.map → config-1zirYXeO.d.mts.map} +1 -1
- package/dist/{config-B_pfl-ZN.d.cts → config-rSlB-bXj.d.cts} +3 -3
- package/dist/{config-CDulXPTe.d.mts.map → config-rSlB-bXj.d.cts.map} +1 -1
- package/dist/config.cjs +1 -1
- package/dist/config.d.cts +3 -3
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/{credentials-No8csre7.cjs → credentials-BI52H1ad.cjs} +5 -5
- package/dist/{credentials-No8csre7.cjs.map → credentials-BI52H1ad.cjs.map} +1 -1
- package/dist/{credentials--QL1R8mL.cjs → credentials-Cp09PIsc.cjs} +4 -4
- package/dist/{credentials--QL1R8mL.cjs.map → credentials-Cp09PIsc.cjs.map} +1 -1
- package/dist/{credentials-CRgp0huX.mjs → credentials-DbjLhvix.mjs} +4 -4
- package/dist/{credentials-CRgp0huX.mjs.map → credentials-DbjLhvix.mjs.map} +1 -1
- package/dist/{credentials-0Kmo6GAw.mjs → credentials-VLP_959f.mjs} +5 -5
- package/dist/{credentials-0Kmo6GAw.mjs.map → credentials-VLP_959f.mjs.map} +1 -1
- package/dist/{dbTunnel-DOiMt-yL.mjs → dbTunnel-CLsqWr7o.mjs} +5 -5
- package/dist/{dbTunnel-DOiMt-yL.mjs.map → dbTunnel-CLsqWr7o.mjs.map} +1 -1
- package/dist/{dbTunnel-CEHBYvbM.cjs → dbTunnel-DQcdaaLi.cjs} +5 -5
- package/dist/{dbTunnel-CEHBYvbM.cjs.map → dbTunnel-DQcdaaLi.cjs.map} +1 -1
- package/dist/deploy/public.cjs +10 -10
- package/dist/deploy/public.d.cts +5 -5
- package/dist/deploy/public.d.mts +5 -5
- package/dist/deploy/public.mjs +10 -10
- package/dist/{deploy-KdBFBME1.mjs → deploy-DhIy2Ftj.mjs} +17 -12
- package/dist/deploy-DhIy2Ftj.mjs.map +1 -0
- package/dist/{deploy-Pkvk9jIL.cjs → deploy-DpQ_4Pu1.cjs} +17 -12
- package/dist/deploy-DpQ_4Pu1.cjs.map +1 -0
- package/dist/{destroy-oqNna46x.cjs → destroy-DmTDT6V7.cjs} +9 -9
- package/dist/{destroy-oqNna46x.cjs.map → destroy-DmTDT6V7.cjs.map} +1 -1
- package/dist/{destroy-CFc0rdP4.mjs → destroy-wV9yNLQV.mjs} +9 -9
- package/dist/{destroy-CFc0rdP4.mjs.map → destroy-wV9yNLQV.mjs.map} +1 -1
- package/dist/{dokploy-CxEzce91.cjs → dokploy-B61ww4Yb.cjs} +2 -2
- package/dist/{dokploy-CxEzce91.cjs.map → dokploy-B61ww4Yb.cjs.map} +1 -1
- package/dist/{dokploy-BkwTpeNU.mjs → dokploy-Jhl3sPd4.mjs} +2 -2
- package/dist/{dokploy-BkwTpeNU.mjs.map → dokploy-Jhl3sPd4.mjs.map} +1 -1
- package/dist/{eas-vzSPhv0B.mjs → eas-BmvO40xS.mjs} +3 -3
- package/dist/{eas-vzSPhv0B.mjs.map → eas-BmvO40xS.mjs.map} +1 -1
- package/dist/{eas-DbDHF2WZ.cjs → eas-X09Gz8_E.cjs} +3 -3
- package/dist/{eas-DbDHF2WZ.cjs.map → eas-X09Gz8_E.cjs.map} +1 -1
- package/dist/{encryption-4xb0WByC.cjs → encryption-BBIUewnL.cjs} +3 -3
- package/dist/{encryption-4xb0WByC.cjs.map → encryption-BBIUewnL.cjs.map} +1 -1
- package/dist/{encryption-BJirKe8H.mjs → encryption-BOmswIgE.mjs} +3 -3
- package/dist/{encryption-BJirKe8H.mjs.map → encryption-BOmswIgE.mjs.map} +1 -1
- package/dist/{engine-C-tyF0OQ.cjs → engine-BhjhShKf.cjs} +7 -7
- package/dist/{engine-C-tyF0OQ.cjs.map → engine-BhjhShKf.cjs.map} +1 -1
- package/dist/{engine-Blw0271a.mjs → engine-DW2H3KNa.mjs} +7 -7
- package/dist/{engine-Blw0271a.mjs.map → engine-DW2H3KNa.mjs.map} +1 -1
- package/dist/{github-C_h3NRr7.mjs → github-Ptbigbrq.mjs} +7 -7
- package/dist/{github-C_h3NRr7.mjs.map → github-Ptbigbrq.mjs.map} +1 -1
- package/dist/{github-Aydv6vu5.cjs → github-xUtu4Ur7.cjs} +7 -7
- package/dist/{github-Aydv6vu5.cjs.map → github-xUtu4Ur7.cjs.map} +1 -1
- package/dist/{googlePlay-DpJTysGZ.cjs → googlePlay-B4xhz5xT.cjs} +4 -4
- package/dist/{googlePlay-DpJTysGZ.cjs.map → googlePlay-B4xhz5xT.cjs.map} +1 -1
- package/dist/{googlePlay-B7AYn6Pc.mjs → googlePlay-C9rrwN5b.mjs} +4 -4
- package/dist/{googlePlay-B7AYn6Pc.mjs.map → googlePlay-C9rrwN5b.mjs.map} +1 -1
- package/dist/{iam-DlPqLzjO.cjs → iam-D7mXd6by.cjs} +2 -2
- package/dist/{iam-DlPqLzjO.cjs.map → iam-D7mXd6by.cjs.map} +1 -1
- package/dist/{iam-CE1QQeEQ.mjs → iam-DNlbVN_l.mjs} +2 -2
- package/dist/{iam-CE1QQeEQ.mjs.map → iam-DNlbVN_l.mjs.map} +1 -1
- package/dist/{index-CBl51bCQ.d.cts → index-B1gfXH5K.d.mts} +2 -2
- package/dist/{index-CBl51bCQ.d.cts.map → index-B1gfXH5K.d.mts.map} +1 -1
- package/dist/{index-Dqp1lLjF.d.mts → index-CunkOPOu.d.cts} +2 -2
- package/dist/{index-Dqp1lLjF.d.mts.map → index-CunkOPOu.d.cts.map} +1 -1
- package/dist/index.cjs +60 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +60 -60
- package/dist/index.mjs.map +1 -1
- package/dist/{local-ZaXGH2eP.mjs → local-CvC-z86k.mjs} +2 -2
- package/dist/{local-ZaXGH2eP.mjs.map → local-CvC-z86k.mjs.map} +1 -1
- package/dist/{local-BEM8UVsa.cjs → local-DAJrhvSC.cjs} +2 -2
- package/dist/{local-BEM8UVsa.cjs.map → local-DAJrhvSC.cjs.map} +1 -1
- package/dist/{migrate-DTMYWQn6.cjs → migrate-0-A4BOcd.cjs} +5 -5
- package/dist/{migrate-DTMYWQn6.cjs.map → migrate-0-A4BOcd.cjs.map} +1 -1
- package/dist/{migrate-CkeIl9YW.mjs → migrate-C_36JSwV.mjs} +3 -3
- package/dist/{migrate-CkeIl9YW.mjs.map → migrate-C_36JSwV.mjs.map} +1 -1
- package/dist/{migrate-BuReWK8R.mjs → migrate-DHbXzZIJ.mjs} +5 -5
- package/dist/{migrate-BuReWK8R.mjs.map → migrate-DHbXzZIJ.mjs.map} +1 -1
- package/dist/{migrate-Cq4s3V1M.cjs → migrate-fGWfv2DV.cjs} +3 -3
- package/dist/{migrate-Cq4s3V1M.cjs.map → migrate-fGWfv2DV.cjs.map} +1 -1
- package/dist/openapi.cjs +1 -1
- package/dist/openapi.d.cts +2 -2
- package/dist/openapi.d.mts +2 -2
- package/dist/openapi.mjs +1 -1
- package/dist/{projectBucket-CBzCpLML.cjs → projectBucket-BAoFOQtA.cjs} +2 -2
- package/dist/{projectBucket-CBzCpLML.cjs.map → projectBucket-BAoFOQtA.cjs.map} +1 -1
- package/dist/{projectBucket-BaZfu9b6.mjs → projectBucket-Dxub09V1.mjs} +2 -2
- package/dist/{projectBucket-BaZfu9b6.mjs.map → projectBucket-Dxub09V1.mjs.map} +1 -1
- package/dist/{publish-CLYnKn-k.cjs → publish-BX8_zXaf.cjs} +2 -2
- package/dist/{publish-CLYnKn-k.cjs.map → publish-BX8_zXaf.cjs.map} +1 -1
- package/dist/{publish-UxavszCu.mjs → publish-DE_yBzlz.mjs} +2 -2
- package/dist/{publish-UxavszCu.mjs.map → publish-DE_yBzlz.mjs.map} +1 -1
- package/dist/reconcile/public.d.cts +1 -1
- package/dist/reconcile/public.d.mts +1 -1
- package/dist/{resolve-CeeNr_ex.cjs → resolve-CPB2jkB4.cjs} +4 -4
- package/dist/{resolve-CeeNr_ex.cjs.map → resolve-CPB2jkB4.cjs.map} +1 -1
- package/dist/{resolve-Bk9a9BVj.mjs → resolve-DCPtP7-X.mjs} +4 -4
- package/dist/{resolve-Bk9a9BVj.mjs.map → resolve-DCPtP7-X.mjs.map} +1 -1
- package/dist/{rollback-DyMVhn7L.mjs → rollback-sefKrjlE.mjs} +7 -7
- package/dist/{rollback-DyMVhn7L.mjs.map → rollback-sefKrjlE.mjs.map} +1 -1
- package/dist/{rollback-D6AdPlie.cjs → rollback-ygh2qRWo.cjs} +7 -7
- package/dist/{rollback-D6AdPlie.cjs.map → rollback-ygh2qRWo.cjs.map} +1 -1
- package/dist/{runtime-DFG1CAWA.d.mts → runtime-BwiWhqkI.d.cts} +2 -2
- package/dist/{runtime-DFG1CAWA.d.mts.map → runtime-BwiWhqkI.d.cts.map} +1 -1
- package/dist/{runtime-DjhB4Oxn.d.cts → runtime-Dx5F8-IL.d.mts} +2 -2
- package/dist/{runtime-DjhB4Oxn.d.cts.map → runtime-Dx5F8-IL.d.mts.map} +1 -1
- package/dist/{s3-FbPmbPft.cjs → s3-Bcvbg8io.cjs} +3 -3
- package/dist/{s3-FbPmbPft.cjs.map → s3-Bcvbg8io.cjs.map} +1 -1
- package/dist/{s3-B9UimcQe.mjs → s3-DK1ofU4f.mjs} +3 -3
- package/dist/{s3-B9UimcQe.mjs.map → s3-DK1ofU4f.mjs.map} +1 -1
- package/dist/{serverSetup-CeFkPTVz.cjs → serverSetup-ClU2iSeU.cjs} +7 -7
- package/dist/{serverSetup-CeFkPTVz.cjs.map → serverSetup-ClU2iSeU.cjs.map} +1 -1
- package/dist/{serverSetup-BH7_Zt0N.mjs → serverSetup-D68Otrp0.mjs} +7 -7
- package/dist/{serverSetup-BH7_Zt0N.mjs.map → serverSetup-D68Otrp0.mjs.map} +1 -1
- package/dist/{sniffer-B83jVMSA.cjs → sniffer-CFOmQQit.cjs} +7 -7
- package/dist/{sniffer-B83jVMSA.cjs.map → sniffer-CFOmQQit.cjs.map} +1 -1
- package/dist/{sniffer-8TlRbqb0.mjs → sniffer-CRF3eD_B.mjs} +7 -7
- package/dist/{sniffer-8TlRbqb0.mjs.map → sniffer-CRF3eD_B.mjs.map} +1 -1
- package/dist/{snsSubscriptions-BQcD_3UK.mjs → snsSubscriptions-CwA6Ceg2.mjs} +21 -12
- package/dist/snsSubscriptions-CwA6Ceg2.mjs.map +1 -0
- package/dist/{snsSubscriptions-B7uEpoJ2.cjs → snsSubscriptions-S_CMCXqI.cjs} +21 -12
- package/dist/snsSubscriptions-S_CMCXqI.cjs.map +1 -0
- package/dist/{sst-D0t-8yEl.cjs → sst-BgG7dJJu.cjs} +6 -6
- package/dist/{sst-D0t-8yEl.cjs.map → sst-BgG7dJJu.cjs.map} +1 -1
- package/dist/{sst-w90IUOX_.mjs → sst-CDnHFO3U.mjs} +6 -6
- package/dist/{sst-w90IUOX_.mjs.map → sst-CDnHFO3U.mjs.map} +1 -1
- package/dist/{stack-B5-pHmtX.mjs → stack-BXmLQf3K.mjs} +163 -27
- package/dist/stack-BXmLQf3K.mjs.map +1 -0
- package/dist/{stack-CBgOAZDP.cjs → stack-BtnflNSa.cjs} +161 -25
- package/dist/stack-BtnflNSa.cjs.map +1 -0
- package/dist/{stage-C6ogkiRu.mjs → stage-BbQidxxa.mjs} +5 -5
- package/dist/{stage-C6ogkiRu.mjs.map → stage-BbQidxxa.mjs.map} +1 -1
- package/dist/{stage-EnQ76HLW.cjs → stage-ssuPXLhP.cjs} +5 -5
- package/dist/{stage-EnQ76HLW.cjs.map → stage-ssuPXLhP.cjs.map} +1 -1
- package/dist/{stages-C8HQ9ozh.cjs → stages-CQwD2QxS.cjs} +2 -2
- package/dist/{stages-C8HQ9ozh.cjs.map → stages-CQwD2QxS.cjs.map} +1 -1
- package/dist/{stages-DnN6lwL4.mjs → stages-MA2sXnX4.mjs} +2 -2
- package/dist/{stages-DnN6lwL4.mjs.map → stages-MA2sXnX4.mjs.map} +1 -1
- package/dist/target/public.cjs +1 -1
- package/dist/target/public.d.cts +2 -2
- package/dist/target/public.d.mts +2 -2
- package/dist/target/public.mjs +1 -1
- package/dist/{terminal-Cb58S1Yx.mjs → terminal-BEGE1AEV.mjs} +2 -2
- package/dist/{terminal-Cb58S1Yx.mjs.map → terminal-BEGE1AEV.mjs.map} +1 -1
- package/dist/{terminal-D9abUcq9.cjs → terminal-BecJpgA3.cjs} +2 -2
- package/dist/{terminal-D9abUcq9.cjs.map → terminal-BecJpgA3.cjs.map} +1 -1
- package/dist/{types-B-ohhDwy.d.mts → types-BvokH0ya.d.cts} +40 -1
- package/dist/types-BvokH0ya.d.cts.map +1 -0
- package/dist/{types-BAqI--_q.d.cts → types-DmLnGeii.d.mts} +39 -2
- package/dist/types-DmLnGeii.d.mts.map +1 -0
- package/dist/workspace/index.cjs +1 -1
- package/dist/workspace/index.d.cts +2 -2
- package/dist/workspace/index.d.mts +2 -2
- package/dist/workspace/index.mjs +1 -1
- package/dist/{workspace-K403npiD.cjs → workspace-DEmfa9RO.cjs} +74 -4
- package/dist/workspace-DEmfa9RO.cjs.map +1 -0
- package/dist/{workspace-BSGUH2DO.mjs → workspace-RgU7TBgg.mjs} +69 -5
- package/dist/workspace-RgU7TBgg.mjs.map +1 -0
- package/package.json +16 -16
- package/dist/clientTelemetry-C3GsvvLK.d.cts.map +0 -1
- package/dist/clientTelemetry-Dcp0jgkV.d.mts.map +0 -1
- package/dist/compose-BE2Fi1Bs.mjs.map +0 -1
- package/dist/compose-QHm47c8E.cjs.map +0 -1
- package/dist/deploy-KdBFBME1.mjs.map +0 -1
- package/dist/deploy-Pkvk9jIL.cjs.map +0 -1
- package/dist/snsSubscriptions-B7uEpoJ2.cjs.map +0 -1
- package/dist/snsSubscriptions-BQcD_3UK.mjs.map +0 -1
- package/dist/stack-B5-pHmtX.mjs.map +0 -1
- package/dist/stack-CBgOAZDP.cjs.map +0 -1
- package/dist/types-B-ohhDwy.d.mts.map +0 -1
- package/dist/types-BAqI--_q.d.cts.map +0 -1
- package/dist/workspace-BSGUH2DO.mjs.map +0 -1
- package/dist/workspace-K403npiD.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stack-B5-pHmtX.mjs","names":["run","run","hostFor","connect","SERVICE_KINDS","logger","run","hostFor"],"sources":["../src/run.ts","../src/compose/docker.ts","../src/providers/dns.ts","../src/backups/config.ts","../src/reconcile/signedOrigins.ts","../src/reconcile/env.ts","../src/providers/s3/lifecycle.ts","../src/reconcile/provision.ts","../src/backups/service.ts","../src/build/workers.ts","../src/compose/siteBuild.ts","../src/exec/imageBuild.ts","../src/docker/templates.ts","../src/docker/layout.ts","../src/providers/processorOrigin.ts","../src/secrets/stackKeys.ts","../src/compose/edge.ts","../src/reconcile/clients.ts","../src/reconcile/docker.ts","../src/reconcile/files.ts","../src/reconcile/lan.ts","../src/reconcile/caddyfile.ts","../src/reconcile/localEdge.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","../src/deploy/devServices.ts","../src/docker/imageRef.ts","../src/build/types.ts","../src/build/owners.ts","../src/build/outputDir.ts","../src/generators/ProcessorGenerator.ts","../src/generators/CronGenerator.ts","../src/generators/QueueGenerator.ts","../src/generators/WorkerGenerator.ts","../src/docker/index.ts","../src/providers/types.ts","../src/providers/notes.ts","../src/providers/aws.ts","../src/providers/s3/plannedOrigin.ts","../src/deploy/state.ts","../src/dns/providers.ts","../src/dns/index.ts","../src/compose/acmeDns.ts","../src/compose/sitePassword.ts","../src/compose/stack.ts"],"sourcesContent":["/**\n * Start a program with an argument array, never a shell string.\n *\n * `gkm build`, `gkm docker` and `gkm deploy` pass values that come from the\n * workspace — image refs, tags, build args, package names — to `docker` and\n * `turbo`. Joined into a string and handed to a shell, a package named\n * `x;curl …|sh` or a tag holding `$(…)` became part of the command line, which\n * matters most where the CLI builds a repository it didn't write: a CI job for a\n * fork, a shared build runner. Here every value reaches the program as one\n * `argv` element, whatever it contains.\n */\n\nimport { type SpawnOptions, spawn } from 'node:child_process';\n\n/** Long enough for a cold image build; short enough that a hung one ends. */\nexport const DEFAULT_TIMEOUT_MS = 30 * 60_000;\n\n/** How long a timed-out child has to exit on SIGTERM before it is killed. */\nconst KILL_GRACE_MS = 5_000;\n\nexport interface RunOptions {\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n\tstdio?: SpawnOptions['stdio'];\n\t/** Kill the child after this long. Defaults to {@link DEFAULT_TIMEOUT_MS}. */\n\ttimeoutMs?: number;\n\t/**\n\t * Kills the child when aborted, and rejects with the signal's reason — the\n\t * same as a stopped deploy's other calls.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The command line as a person would read it — for messages, never to run. */\nfunction display(command: string, args: readonly string[]): string {\n\treturn [command, ...args].join(' ');\n}\n\n/** The program ran and exited unsuccessfully; its own output said why. */\nexport class CommandFailed extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly exitCode: number | null,\n\t\treadonly signal: NodeJS.Signals | null,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` ${exitCode === null ? `was stopped by ${signal ?? 'a signal'}` : `exited with code ${exitCode}`}. Its output above says why; run it by hand to see it again.`,\n\t\t);\n\t\tthis.name = 'CommandFailed';\n\t}\n}\n\n/** The program ran past its timeout and was killed. */\nexport class CommandTimedOut extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly timeoutMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` was still running after ${Math.round(timeoutMs / 1000)}s and was stopped. Check what it was waiting on — a registry, the Docker daemon, a prompt — and run it again.`,\n\t\t);\n\t\tthis.name = 'CommandTimedOut';\n\t}\n}\n\n/**\n * Run `command` with `args`, resolving when it exits 0.\n *\n * Rejects with {@link CommandFailed} on any other exit, {@link CommandTimedOut}\n * once `timeoutMs` passes (after the child is gone), and with the spawn error\n * itself when the program cannot be started at all — `ENOENT` already names it.\n */\nexport async function run(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions = {},\n): Promise<void> {\n\tawait spawnChild(command, args, options, false);\n}\n\n/**\n * {@link run}, resolving with what the program wrote to stdout — for a value\n * the CLI reads back, such as the digest `docker inspect` reports. stderr still\n * reaches the terminal, so a failure explains itself the same way.\n */\nexport function runOutput(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: Omit<RunOptions, 'stdio'> = {},\n): Promise<string> {\n\treturn spawnChild(command, args, options, true);\n}\n\nfunction spawnChild(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions,\n\tcapture: boolean,\n): Promise<string> {\n\tconst { timeoutMs = DEFAULT_TIMEOUT_MS, ...spawnOptions } = options;\n\n\treturn new Promise<string>((resolve, reject) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\tstdio: 'inherit',\n\t\t\t...spawnOptions,\n\t\t\t...(capture ? { stdio: ['ignore', 'pipe', 'inherit'] } : {}),\n\t\t\tshell: false,\n\t\t});\n\n\t\tlet stdout = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\n\t\tlet timedOut = false;\n\t\tlet killer: NodeJS.Timeout | undefined;\n\t\tconst timer = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tchild.kill('SIGTERM');\n\t\t\t// A child that ignores SIGTERM would hold the deploy open forever.\n\t\t\tkiller = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);\n\t\t\tkiller.unref?.();\n\t\t}, timeoutMs);\n\t\ttimer.unref?.();\n\n\t\tconst settle = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tif (killer) clearTimeout(killer);\n\t\t};\n\n\t\tchild.on('error', (error) => {\n\t\t\tsettle();\n\t\t\t// Node reports an abort as its own `AbortError`; the caller asked\n\t\t\t// with a reason, and that is what it should get back.\n\t\t\treject(spawnOptions.signal?.aborted ? spawnOptions.signal.reason : error);\n\t\t});\n\n\t\tchild.on('close', (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\tsettle();\n\t\t\tif (spawnOptions.signal?.aborted) reject(spawnOptions.signal.reason);\n\t\t\telse if (timedOut) reject(new CommandTimedOut(command, args, timeoutMs));\n\t\t\telse if (code === 0) resolve(stdout);\n\t\t\telse reject(new CommandFailed(command, args, code, signal));\n\t\t});\n\t});\n}\n","import { existsSync } from 'node:fs';\n/**\n * The Docker operations `gkm compose` needs, behind an interface.\n *\n * Small on purpose, like reconcile's: the rules about *when* each runs — the\n * registry is asked before anything is pulled, nothing is started for a tag\n * that is missing — are asserted against a fake, and this file is only the\n * wiring to the real CLI.\n *\n * Every call is an argument array. Image refs, tags and paths come from the\n * workspace, and none of them reaches a shell.\n */\n\nimport { spawn } from 'node:child_process';\nimport { GkmError } from '../errors';\nimport { type RunOptions, run, runOutput } from '../run';\n\n/** Where one stack lives: its compose project and the file that defines it. */\nexport interface StackRef {\n\tproject: string;\n\tfile: string;\n\t/**\n\t * The project's own files merged over `file`, in order — its\n\t * `docker-compose.<stage>.yml`, where it has one.\n\t */\n\toverrides?: readonly string[];\n\t/** Where relative paths in the file resolve — the workspace root. */\n\tcwd: string;\n\t/**\n\t * The Docker engine the stack runs on, as `DOCKER_HOST` names it: a\n\t * deployed stage's server, `ssh://user@host`. Absent for this machine's\n\t * engine — the local stage — whose environment is left as it is.\n\t *\n\t * Compose is a client: it reads the compose file and every `env_file` here\n\t * and sends their values in the API calls that create each container. A\n\t * stage's secrets therefore never land on the server as a file — they are\n\t * in the container's configuration, which only the server's Docker group\n\t * can read.\n\t */\n\thost?: string;\n\t/**\n\t * Where docker's own output goes: the terminal (the default), stderr — so\n\t * a `--json` run's stdout carries only events — or nowhere.\n\t */\n\toutput?: 'inherit' | 'stderr' | 'ignore';\n\t/** Stops whatever docker is doing for the stack. */\n\tsignal?: AbortSignal;\n}\n\n/** `output` as `spawn` reads it. */\nconst STDIO: Record<NonNullable<StackRef['output']>, RunOptions['stdio']> = {\n\tinherit: 'inherit',\n\tstderr: ['ignore', 2, 2],\n\tignore: 'ignore',\n};\n\n/**\n * The environment a docker command for `engine` runs with: this process's,\n * with `DOCKER_HOST` pointing at the stack's engine when it is a server's.\n */\nexport function engineEnv(\n\tengine: Pick<StackRef, 'host'>,\n\textra: NodeJS.ProcessEnv = {},\n): NodeJS.ProcessEnv | undefined {\n\tif (!engine.host && Object.keys(extra).length === 0) return undefined;\n\treturn {\n\t\t...process.env,\n\t\t...extra,\n\t\t...(engine.host ? { DOCKER_HOST: engine.host } : {}),\n\t};\n}\n\n/** How a stack's docker commands run: where it is, where output goes. */\nfunction runOptions(stack: StackRef, extra?: NodeJS.ProcessEnv): RunOptions {\n\tconst env = engineEnv(stack, extra);\n\treturn {\n\t\tcwd: stack.cwd,\n\t\tstdio: STDIO[stack.output ?? 'inherit'],\n\t\t...(env ? { env } : {}),\n\t\t...(stack.signal ? { signal: stack.signal } : {}),\n\t};\n}\n\n/** What a command run in a container said, whatever it exited with. */\nexport interface ExecResult {\n\t/** Its exit code — null when the service has no running container. */\n\tcode: number | null;\n\tstdout: string;\n\tstderr: string;\n}\n\n/** The engine a call that is about no stack in particular is made against. */\nexport type DockerEngine = Pick<StackRef, 'host'>;\n\n/** What the registry said about one image ref. */\nexport type ImageLookup =\n\t| { ref: string; status: 'found' }\n\t| { ref: string; status: 'missing' }\n\t| { ref: string; status: 'unreachable'; detail: string };\n\n/** A running container that publishes a host port. */\nexport interface PortHolder {\n\t/** The container's name. */\n\tcontainer: string;\n\t/** Its compose project and service, when compose started it. */\n\tproject?: string;\n\tservice?: string;\n}\n\nexport interface ComposeDocker {\n\t/** Ask the registry whether `ref` exists, without pulling it. */\n\tlookup(ref: string): Promise<ImageLookup>;\n\t/** Build every service with a `build:` entry. */\n\tbuild(stack: StackRef, services: readonly string[]): Promise<void>;\n\t/** Pull the named services' images. */\n\tpull(stack: StackRef, services: readonly string[]): Promise<void>;\n\t/**\n\t * Start services, detached, and wait for their health checks. With no\n\t * services named, the whole stack — and anything it no longer defines is\n\t * removed.\n\t */\n\tup(stack: StackRef, services?: readonly string[]): Promise<void>;\n\t/**\n\t * Stop and remove the stack's containers. `volumes` removes its volumes\n\t * too — only `gkm compose --destroy` asks for that.\n\t */\n\tdown(stack: StackRef, options?: { volumes?: boolean }): Promise<void>;\n\t/** The host port a running service publishes for `inside`. */\n\tport(stack: StackRef, service: string, inside: number): Promise<number>;\n\t/**\n\t * A running service's health, as its own check reports it — `healthy`,\n\t * `starting`, `unhealthy` — or undefined when it is not running.\n\t */\n\thealth(stack: StackRef, service: string): Promise<string | undefined>;\n\t/**\n\t * A service's last `lines` lines of output, stopped containers included —\n\t * what a container that never turned healthy said before it gave up.\n\t * Empty when it said nothing, or never ran.\n\t */\n\tlogs(stack: StackRef, service: string, lines: number): Promise<string>;\n\t/**\n\t * Push an image built here to its registry, and return the digest the\n\t * registry stored it under (`sha256:…`).\n\t */\n\tpush(stack: StackRef, ref: string): Promise<string>;\n\t/**\n\t * What an image resolved to on the stack's engine: the registry digest a\n\t * pulled image has, or the content id of one built and never pushed.\n\t */\n\tdigest(engine: DockerEngine, ref: string): Promise<string | undefined>;\n\t/** Create a network on the engine, unless one by that name is there. */\n\tensureNetwork(engine: DockerEngine, name: string): Promise<void>;\n\t/** Every running container publishing `port` on the engine's host. */\n\tpublishers(engine: DockerEngine, port: number): Promise<PortHolder[]>;\n\t/**\n\t * Run a command in a service's running container, `input` on its stdin —\n\t * how files reach a container on a server, through the engine alone.\n\t */\n\texec(\n\t\tstack: StackRef,\n\t\tservice: string,\n\t\tcommand: readonly string[],\n\t\tinput?: string,\n\t): Promise<ExecResult>;\n\t/**\n\t * A compose project's running container for `service` on the engine, by\n\t * its labels — found without the stack's compose file.\n\t */\n\tcontainer(\n\t\tengine: DockerEngine,\n\t\tproject: string,\n\t\tservice: string,\n\t): Promise<{ id: string; image: string } | undefined>;\n\t/**\n\t * The host port a compose project's running `service` publishes for\n\t * `inside` on the engine, by its labels — found without the stack's\n\t * compose file. Undefined when it is not running or publishes none.\n\t */\n\tpublished(\n\t\tengine: DockerEngine,\n\t\tproject: string,\n\t\tservice: string,\n\t\tinside: number,\n\t): Promise<number | undefined>;\n\t/**\n\t * Stop every running container of a compose project but those of the\n\t * services in `keep`, found by their labels — without the stack's compose\n\t * file. Resolves with the ids it stopped, for {@link ComposeDocker.start}.\n\t *\n\t * @throws {ContainersNotStopped} with every id it meant to stop\n\t */\n\tstop(\n\t\tengine: DockerEngine,\n\t\tproject: string,\n\t\tkeep: readonly string[],\n\t): Promise<string[]>;\n\t/**\n\t * Start containers by id — what {@link ComposeDocker.stop} stopped, with\n\t * the configuration and network compose gave them.\n\t *\n\t * @throws {ContainersNotStarted}\n\t */\n\tstart(engine: DockerEngine, ids: readonly string[]): Promise<void>;\n\t/**\n\t * Stop and remove every container of one service of a compose project,\n\t * found by its labels — a service the stack's compose file no longer\n\t * defines, so `docker compose` cannot name it. Resolves with the ids it\n\t * removed.\n\t *\n\t * @throws {ContainersNotRemoved} with every id it meant to remove\n\t */\n\tremove(\n\t\tengine: DockerEngine,\n\t\tproject: string,\n\t\tservice: string,\n\t): Promise<string[]>;\n\t/**\n\t * Run `command` once on the engine, in a new container of `image` on\n\t * `network`, removed when it ends, with `stdin` streamed in. Each of `env`\n\t * is passed by name, never on the command line. Resolves with its exit\n\t * code.\n\t */\n\trunOnce(\n\t\tengine: DockerEngine,\n\t\toptions: {\n\t\t\timage: string;\n\t\t\tnetwork: string;\n\t\t\tcommand: readonly string[];\n\t\t\tenv?: Readonly<Record<string, string>>;\n\t\t\t/** `volume:/path` mounts — a compose project's volume by its full name. */\n\t\t\tvolumes?: readonly string[];\n\t\t\tstdin?: NodeJS.ReadableStream;\n\t\t\toutput?: StackRef['output'];\n\t\t},\n\t): Promise<number>;\n}\n\n/** The network compose puts a project's services on. */\nexport function projectNetwork(project: string): string {\n\treturn `${project}_default`;\n}\n\n/** The name compose gives a project's volume: `<project>_<volume>`. */\nexport function projectVolume(project: string, volume: string): string {\n\treturn `${project}_${volume}`;\n}\n\n/**\n * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,\n * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.\n */\nexport function publishedPorts(column: string): number[] {\n\tconst ports = new Set<number>();\n\tfor (const match of column.matchAll(\n\t\t/(?:[\\d.]+|\\[[^\\]]*\\]):(\\d+)(?:-(\\d+))?->/g,\n\t)) {\n\t\tconst first = Number(match[1]);\n\t\tconst last = match[2] ? Number(match[2]) : first;\n\t\tfor (let port = first; port <= last; port++) ports.add(port);\n\t}\n\treturn [...ports];\n}\n\n/**\n * The host port a `docker ps` Ports column publishes for `inside`:\n * `127.0.0.1:54321->5432/tcp` is 54321.\n */\nexport function publishedPort(\n\tcolumn: string,\n\tinside: number,\n): number | undefined {\n\tconst match = new RegExp(\n\t\t`(?:[\\\\d.]+|\\\\[[^\\\\]]*\\\\]):(\\\\d+)->${inside}/tcp`,\n\t).exec(column);\n\treturn match ? Number(match[1]) : undefined;\n}\n\n/** Each line `docker ps` printed, as the containers holding `port`. */\nexport function portHolders(output: string, port: number): PortHolder[] {\n\treturn output\n\t\t.split('\\n')\n\t\t.filter(Boolean)\n\t\t.map((line) => line.split('\\t'))\n\t\t.filter(([, , , column = '']) => publishedPorts(column).includes(port))\n\t\t.map(([container = '', project, service]) => ({\n\t\t\tcontainer,\n\t\t\t...(project ? { project } : {}),\n\t\t\t...(service ? { service } : {}),\n\t\t}));\n}\n\n/** How long a stack has to pass its health checks. */\nconst WAIT_TIMEOUT_S = 180;\n\n/** `docker` itself failed, before it could say anything about a service. */\nexport class DockerUnreachable extends GkmError {\n\tconstructor(\n\t\treadonly engine: string,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not ask Docker on ${engine} which ports its services publish ` +\n\t\t\t\t`(docker said: ${stderr.trim() || 'nothing'}). Check that ` +\n\t\t\t\t`\\`DOCKER_HOST=${engine} docker ps\\` works from here.`,\n\t\t);\n\t\tthis.name = 'DockerUnreachable';\n\t}\n}\n\n/** `docker compose port` printed nothing a port can be read from. */\nexport class ServicePortUnknown extends GkmError {\n\tconstructor(\n\t\treadonly service: string,\n\t\treadonly inside: number,\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${service}' publishes no host port for ${inside} (docker said: ${output.trim() || 'nothing'}). Is it running? \\`docker compose ps\\` shows the stack.`,\n\t\t);\n\t\tthis.name = 'ServicePortUnknown';\n\t}\n}\n\n/**\n * Whether `ref` names a registry on this machine's loopback — which the\n * daemon pulls from and pushes to over plain HTTP by default, and `docker\n * manifest inspect` reaches only when told `--insecure` (without it, a local\n * registry's image is reported as no such manifest).\n */\nexport function isLoopbackRegistry(ref: string): boolean {\n\tconst first = ref.split('/')[0]!;\n\tif (!ref.includes('/') || !/[.:]|^localhost$/.test(first)) return false;\n\tconst host = first.replace(/:\\d+$/, '');\n\treturn host === 'localhost' || /^127(?:\\.\\d{1,3}){3}$/.test(host);\n}\n\n/** `docker push` finished without saying what digest the registry stored. */\nexport class PushDigestUnknown extends GkmError {\n\tconstructor(\n\t\treadonly ref: string,\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\t`Pushed ${ref}, but docker did not say which digest the registry stored ` +\n\t\t\t\t`(it said: ${output.trim().split('\\n').slice(-3).join(' / ') || 'nothing'}). ` +\n\t\t\t\t`Check the push with \\`docker buildx imagetools inspect ${ref}\\`.`,\n\t\t);\n\t\tthis.name = 'PushDigestUnknown';\n\t}\n}\n\n/** The digest `docker push` reports last: `<tag>: digest: sha256:… size: …`. */\nexport function pushedDigest(output: string): string | undefined {\n\tconst matches = [...output.matchAll(/digest: (sha256:[0-9a-f]{64})/g)];\n\treturn matches.at(-1)?.[1];\n}\n\nfunction compose(stack: StackRef, args: readonly string[]): string[] {\n\treturn [\n\t\t'compose',\n\t\t'-p',\n\t\tstack.project,\n\t\t'-f',\n\t\tstack.file,\n\t\t...(stack.overrides ?? []).flatMap((file) => ['-f', file]),\n\t\t...args,\n\t];\n}\n\n/** Run a program and keep everything it said, whatever it exits with. */\nfunction capture(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: { env?: NodeJS.ProcessEnv; input?: string; timeoutMs?: number } = {},\n): Promise<{ code: number | null; stdout: string; stderr: string }> {\n\tconst { timeoutMs = 60_000 } = options;\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\tstdio: [options.input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n\t\t\tshell: false,\n\t\t\t...(options.env ? { env: options.env } : {}),\n\t\t});\n\t\tif (options.input !== undefined) child.stdin?.end(options.input);\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t});\n\t\tconst timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs);\n\t\ttimer.unref?.();\n\t\tchild.on('error', (error) => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(error);\n\t\t});\n\t\tchild.on('close', (code) => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve({ code, stdout, stderr });\n\t\t});\n\t});\n}\n\n/**\n * Whether a failed `docker manifest inspect` means the tag is not there, as\n * opposed to the registry not answering.\n *\n * Read off the message because that is all the CLI gives. Anything not\n * recognisably \"no such tag\" is treated as the registry being unreachable:\n * a registry that refused credentials must not be reported as a tag that was\n * never pushed, or the fix offered would be the wrong one.\n */\nexport function isMissingManifest(output: string): boolean {\n\treturn /no such manifest|manifest unknown|manifest for .* not found|not found: manifest/i.test(\n\t\toutput,\n\t);\n}\n\nexport const dockerCompose: ComposeDocker = {\n\tasync lookup(ref) {\n\t\tconst { code, stdout, stderr } = await capture('docker', [\n\t\t\t'manifest',\n\t\t\t'inspect',\n\t\t\t...(isLoopbackRegistry(ref) ? ['--insecure'] : []),\n\t\t\tref,\n\t\t]);\n\t\tif (code === 0) return { ref, status: 'found' };\n\n\t\tconst output = `${stderr}\\n${stdout}`.trim();\n\t\treturn isMissingManifest(output)\n\t\t\t? { ref, status: 'missing' }\n\t\t\t: { ref, status: 'unreachable', detail: output };\n\t},\n\n\tasync build(stack, services) {\n\t\tawait run(\n\t\t\t'docker',\n\t\t\tcompose(stack, ['build', ...services]),\n\t\t\trunOptions(stack, { ...process.env, DOCKER_BUILDKIT: '1' }),\n\t\t);\n\t},\n\n\tasync pull(stack, services) {\n\t\tawait run(\n\t\t\t'docker',\n\t\t\tcompose(stack, ['pull', ...services]),\n\t\t\trunOptions(stack),\n\t\t);\n\t},\n\n\tasync up(stack, services) {\n\t\tawait run(\n\t\t\t'docker',\n\t\t\tcompose(stack, [\n\t\t\t\t'up',\n\t\t\t\t'-d',\n\t\t\t\t'--wait',\n\t\t\t\t`--wait-timeout=${WAIT_TIMEOUT_S}`,\n\t\t\t\t// Only when the whole stack is asked for: starting the databases\n\t\t\t\t// first must not remove the apps an earlier run left running.\n\t\t\t\t...(services ? [] : ['--remove-orphans']),\n\t\t\t\t...(services ?? []),\n\t\t\t]),\n\t\t\trunOptions(stack),\n\t\t);\n\t},\n\n\tasync down(stack, options) {\n\t\tconst args = ['down', ...(options?.volumes ? ['--volumes'] : [])];\n\t\tawait run(\n\t\t\t'docker',\n\t\t\t// A stack whose file is gone is still found by its project's name.\n\t\t\texistsSync(stack.file)\n\t\t\t\t? compose(stack, args)\n\t\t\t\t: ['compose', '-p', stack.project, ...args],\n\t\t\trunOptions(stack),\n\t\t);\n\t},\n\n\tasync port(stack, service, inside) {\n\t\tconst env = engineEnv(stack);\n\t\tconst output = await runOutput(\n\t\t\t'docker',\n\t\t\tcompose(stack, ['port', service, String(inside)]),\n\t\t\t{\n\t\t\t\tcwd: stack.cwd,\n\t\t\t\t...(env ? { env } : {}),\n\t\t\t\t...(stack.signal ? { signal: stack.signal } : {}),\n\t\t\t},\n\t\t);\n\t\t// `127.0.0.1:54321` — the part after the last colon is the host port.\n\t\tconst port = Number(output.trim().split(':').pop());\n\t\tif (!Number.isInteger(port) || port <= 0) {\n\t\t\tthrow new ServicePortUnknown(service, inside, output);\n\t\t}\n\t\treturn port;\n\t},\n\n\tasync health(stack, service) {\n\t\tconst env = engineEnv(stack);\n\t\tconst { code, stdout } = await capture(\n\t\t\t'docker',\n\t\t\tcompose(stack, ['ps', '--format', '{{.Health}}', service]),\n\t\t\tenv ? { env } : {},\n\t\t);\n\t\tif (code !== 0) return undefined;\n\t\treturn stdout.trim().split('\\n')[0] || undefined;\n\t},\n\n\tasync logs(stack, service, lines) {\n\t\tconst env = engineEnv(stack);\n\t\tconst { stdout, stderr } = await capture(\n\t\t\t'docker',\n\t\t\tcompose(stack, [\n\t\t\t\t'logs',\n\t\t\t\t'--no-color',\n\t\t\t\t'--no-log-prefix',\n\t\t\t\t'--tail',\n\t\t\t\tString(lines),\n\t\t\t\tservice,\n\t\t\t]),\n\t\t\tenv ? { env } : {},\n\t\t);\n\t\treturn `${stdout}${stderr}`.trimEnd();\n\t},\n\n\tasync push(stack, ref) {\n\t\t// What it printed is read back for the digest; its errors still reach\n\t\t// the terminal.\n\t\tconst output = await runOutput('docker', ['push', ref], {\n\t\t\tcwd: stack.cwd,\n\t\t\t...(stack.signal ? { signal: stack.signal } : {}),\n\t\t});\n\t\tconst digest = pushedDigest(output);\n\t\tif (!digest) throw new PushDigestUnknown(ref, output);\n\t\treturn digest;\n\t},\n\n\tasync digest(engine, ref) {\n\t\tconst env = engineEnv(engine);\n\t\tconst { code, stdout } = await capture(\n\t\t\t'docker',\n\t\t\t['image', 'inspect', '--format={{json .RepoDigests}} {{.Id}}', ref],\n\t\t\tenv ? { env } : {},\n\t\t);\n\t\tif (code !== 0) return undefined;\n\n\t\tconst [json = '[]', id] = stdout.trim().split(' ');\n\t\tconst repository = ref.split('@')[0]!.replace(/:[\\w][\\w.-]*$/, '');\n\t\ttry {\n\t\t\tconst digests = JSON.parse(json) as unknown;\n\t\t\tconst match = Array.isArray(digests)\n\t\t\t\t? digests.find(\n\t\t\t\t\t\t(entry): entry is string =>\n\t\t\t\t\t\t\ttypeof entry === 'string' && entry.startsWith(`${repository}@`),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tif (match) return match.slice(repository.length + 1);\n\t\t} catch {\n\t\t\t// Fall through to the content id.\n\t\t}\n\t\treturn id || undefined;\n\t},\n\n\tasync ensureNetwork(engine, name) {\n\t\tconst env = engineEnv(engine);\n\t\tconst options = env ? { env } : {};\n\t\tconst { code } = await capture(\n\t\t\t'docker',\n\t\t\t['network', 'inspect', name],\n\t\t\toptions,\n\t\t);\n\t\tif (code === 0) return;\n\t\tconst created = await capture(\n\t\t\t'docker',\n\t\t\t['network', 'create', name],\n\t\t\toptions,\n\t\t);\n\t\t// Another run may have created it between the two calls.\n\t\tif (created.code !== 0 && !/already exists/.test(created.stderr)) {\n\t\t\tthrow new NetworkCreateFailed(name, created.stderr);\n\t\t}\n\t},\n\n\tasync publishers(engine, port) {\n\t\tconst env = engineEnv(engine);\n\t\tconst { stdout } = await capture(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'ps',\n\t\t\t\t'--format',\n\t\t\t\t'{{.Names}}\\t{{.Label \"com.docker.compose.project\"}}\\t{{.Label \"com.docker.compose.service\"}}\\t{{.Ports}}',\n\t\t\t],\n\t\t\tenv ? { env } : {},\n\t\t);\n\t\treturn portHolders(stdout, port);\n\t},\n\n\tasync exec(stack, service, command, input) {\n\t\tconst env = engineEnv(stack);\n\t\tconst options = env ? { env } : {};\n\t\t// By its compose labels, so it needs no compose file: `--down` reaches\n\t\t// the shared edge with nothing but its project's name.\n\t\tconst { stdout: ids } = await capture(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'ps',\n\t\t\t\t'-q',\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.project=${stack.project}`,\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.service=${service}`,\n\t\t\t],\n\t\t\toptions,\n\t\t);\n\t\tconst container = ids.trim().split('\\n')[0];\n\t\tif (!container) {\n\t\t\treturn { code: null, stdout: '', stderr: `${service} is not running` };\n\t\t}\n\t\treturn capture(\n\t\t\t'docker',\n\t\t\t['exec', ...(input === undefined ? [] : ['-i']), container, ...command],\n\t\t\t{ ...options, ...(input === undefined ? {} : { input }) },\n\t\t);\n\t},\n\n\tasync container(engine, project, service) {\n\t\tconst env = engineEnv(engine);\n\t\tconst { stdout } = await capture(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'ps',\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.project=${project}`,\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.service=${service}`,\n\t\t\t\t'--format',\n\t\t\t\t'{{.ID}}\\t{{.Image}}',\n\t\t\t],\n\t\t\tenv ? { env } : {},\n\t\t);\n\t\tconst [id, image] = stdout.trim().split('\\n')[0]?.split('\\t') ?? [];\n\t\treturn id && image ? { id, image } : undefined;\n\t},\n\n\tasync published(engine, project, service, inside) {\n\t\tconst env = engineEnv(engine);\n\t\tconst { code, stdout, stderr } = await capture(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'ps',\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.project=${project}`,\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.service=${service}`,\n\t\t\t\t'--format',\n\t\t\t\t'{{.Ports}}',\n\t\t\t],\n\t\t\tenv ? { env } : {},\n\t\t);\n\t\t// Docker not answering is not a service that publishes nothing.\n\t\tif (code !== 0) {\n\t\t\tthrow new DockerUnreachable(engine.host ?? 'this machine', stderr);\n\t\t}\n\t\treturn publishedPort(stdout, inside);\n\t},\n\n\tasync stop(engine, project, keep) {\n\t\tconst env = engineEnv(engine);\n\t\tconst options = env ? { env } : {};\n\t\tconst listed = await capture(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'ps',\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.project=${project}`,\n\t\t\t\t'--format',\n\t\t\t\t'{{.ID}}\\t{{.Label \"com.docker.compose.service\"}}',\n\t\t\t],\n\t\t\toptions,\n\t\t);\n\t\tif (listed.code !== 0) {\n\t\t\tthrow new DockerUnreachable(engine.host ?? 'this machine', listed.stderr);\n\t\t}\n\t\tconst ids = listed.stdout\n\t\t\t.split('\\n')\n\t\t\t.filter(Boolean)\n\t\t\t.map((line) => line.split('\\t'))\n\t\t\t.filter(([, service = '']) => !keep.includes(service))\n\t\t\t.map(([id = '']) => id)\n\t\t\t.filter(Boolean);\n\t\tif (ids.length === 0) return [];\n\t\tconst stopped = await capture('docker', ['stop', ...ids], {\n\t\t\t...options,\n\t\t\ttimeoutMs: 120_000,\n\t\t});\n\t\tif (stopped.code !== 0) {\n\t\t\tthrow new ContainersNotStopped(project, ids, stopped.stderr);\n\t\t}\n\t\treturn ids;\n\t},\n\n\tasync start(engine, ids) {\n\t\tif (ids.length === 0) return;\n\t\tconst env = engineEnv(engine);\n\t\tconst started = await capture('docker', ['start', ...ids], {\n\t\t\t...(env ? { env } : {}),\n\t\t\ttimeoutMs: 120_000,\n\t\t});\n\t\tif (started.code !== 0) {\n\t\t\tthrow new ContainersNotStarted(ids, started.stderr);\n\t\t}\n\t},\n\n\tasync remove(engine, project, service) {\n\t\tconst env = engineEnv(engine);\n\t\tconst options = env ? { env } : {};\n\t\tconst listed = await capture(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'ps',\n\t\t\t\t'--all',\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.project=${project}`,\n\t\t\t\t'--filter',\n\t\t\t\t`label=com.docker.compose.service=${service}`,\n\t\t\t\t'--format',\n\t\t\t\t'{{.ID}}',\n\t\t\t],\n\t\t\toptions,\n\t\t);\n\t\tif (listed.code !== 0) {\n\t\t\tthrow new DockerUnreachable(engine.host ?? 'this machine', listed.stderr);\n\t\t}\n\t\tconst ids = listed.stdout.split('\\n').filter(Boolean);\n\t\tif (ids.length === 0) return [];\n\t\tconst removed = await capture('docker', ['rm', '--force', ...ids], {\n\t\t\t...options,\n\t\t\ttimeoutMs: 120_000,\n\t\t});\n\t\tif (removed.code !== 0) {\n\t\t\tthrow new ContainersNotRemoved(project, service, ids, removed.stderr);\n\t\t}\n\t\treturn ids;\n\t},\n\n\trunOnce(engine, options) {\n\t\treturn dockerExit(\n\t\t\t[\n\t\t\t\t'run',\n\t\t\t\t'--rm',\n\t\t\t\t...(options.stdin ? ['-i'] : []),\n\t\t\t\t'--network',\n\t\t\t\toptions.network,\n\t\t\t\t...(options.volumes ?? []).flatMap((volume) => ['-v', volume]),\n\t\t\t\t...Object.keys(options.env ?? {}).flatMap((name) => ['-e', name]),\n\t\t\t\t'--entrypoint',\n\t\t\t\t'',\n\t\t\t\toptions.image,\n\t\t\t\t...options.command,\n\t\t\t],\n\t\t\t{\n\t\t\t\tenv: engineEnv(engine, { ...options.env }) ?? process.env,\n\t\t\t\t...(options.stdin ? { stdin: options.stdin } : {}),\n\t\t\t\t...(options.output ? { output: options.output } : {}),\n\t\t\t},\n\t\t);\n\t},\n};\n\n/** Spawn `docker`, its output where `output` says; resolve with the exit code. */\nfunction dockerExit(\n\targs: readonly string[],\n\toptions: {\n\t\tenv?: NodeJS.ProcessEnv;\n\t\tstdin?: NodeJS.ReadableStream;\n\t\toutput?: StackRef['output'];\n\t} = {},\n): Promise<number> {\n\tconst output = STDIO[options.output ?? 'inherit'];\n\tconst out = Array.isArray(output) ? output : [output, output, output];\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn('docker', [...args], {\n\t\t\tstdio: [options.stdin ? 'pipe' : 'ignore', out[1], out[2]] as never,\n\t\t\tenv: options.env ?? process.env,\n\t\t\tshell: false,\n\t\t});\n\t\t// A stdin that fails partway must not look like one that ended: the\n\t\t// command would see a short input and fail for a reason it can't name.\n\t\tlet stdinFailed: Error | undefined;\n\t\tif (options.stdin && child.stdin) {\n\t\t\toptions.stdin.on('error', (error) => {\n\t\t\t\tstdinFailed = error;\n\t\t\t\tchild.stdin?.destroy(error);\n\t\t\t});\n\t\t\tchild.stdin.on('error', () => {});\n\t\t\toptions.stdin.pipe(child.stdin);\n\t\t}\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => {\n\t\t\tif (stdinFailed) reject(new StdinNotDelivered(stdinFailed));\n\t\t\telse resolve(code ?? 1);\n\t\t});\n\t});\n}\n\n/** What a command run with {@link dockerExit} read from stdin failed partway. */\nexport class StdinNotDelivered extends GkmError {\n\tconstructor(readonly reason: Error) {\n\t\tsuper(\n\t\t\t`The input to docker stopped before its end (${reason.message}), so ` +\n\t\t\t\t'the command only read part of it. Run it again.',\n\t\t);\n\t\tthis.name = 'StdinNotDelivered';\n\t}\n}\n\n/** `docker stop` failed for some of a project's containers. */\nexport class ContainersNotStopped extends GkmError {\n\tconstructor(\n\t\treadonly project: string,\n\t\treadonly ids: readonly string[],\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not stop ${project}'s containers ${ids.join(', ')} (docker said: ` +\n\t\t\t\t`${output.trim() || 'nothing'}). Check \\`docker ps\\` on the stage's server.`,\n\t\t);\n\t\tthis.name = 'ContainersNotStopped';\n\t}\n}\n\n/** `docker start` failed for containers that were stopped. */\nexport class ContainersNotStarted extends GkmError {\n\tconstructor(\n\t\treadonly ids: readonly string[],\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not start the containers ${ids.join(', ')} again (docker said: ` +\n\t\t\t\t`${output.trim() || 'nothing'}). Start them on the stage's server with ` +\n\t\t\t\t`\\`docker start ${ids.join(' ')}\\`, or deploy the stage.`,\n\t\t);\n\t\tthis.name = 'ContainersNotStarted';\n\t}\n}\n\n/** `docker rm` failed for a service's containers. */\nexport class ContainersNotRemoved extends GkmError {\n\tconstructor(\n\t\treadonly project: string,\n\t\treadonly service: string,\n\t\treadonly ids: readonly string[],\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not remove ${project}'s ${service} containers ${ids.join(', ')} ` +\n\t\t\t\t`(docker said: ${output.trim() || 'nothing'}). Remove them on the ` +\n\t\t\t\t`stage's server with \\`docker rm --force ${ids.join(' ')}\\`, and deploy again.`,\n\t\t);\n\t\tthis.name = 'ContainersNotRemoved';\n\t}\n}\n\n/** `docker network create` failed. */\nexport class NetworkCreateFailed extends GkmError {\n\tconstructor(\n\t\treadonly network: string,\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not create the Docker network '${network}' (docker said: ${output.trim() || 'nothing'}). Create it by hand with \\`docker network create ${network}\\` and run again.`,\n\t\t);\n\t\tthis.name = 'NetworkCreateFailed';\n\t}\n}\n","/**\n * What the deploy's DNS step needs to know about a workspace before its\n * stack is run: whether it deploys with compose.\n *\n * The step itself is `stageDns` in `compose/dns.ts`, run by every deploy\n * (`gkm deploy`, and `gkm compose`, the same run) where the deploy runs — a\n * CI runner or a developer's machine, which hold the DNS provider's token.\n * The server never does.\n */\n\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/** Whether the workspace deploys through the compose target. */\nexport function deploysWithCompose(workspace: NormalizedWorkspace): boolean {\n\treturn (\n\t\tworkspace.deploy?.default === 'compose' ||\n\t\tObject.values(workspace.apps).some(\n\t\t\t(app) => app.resolvedDeployTarget === 'compose',\n\t\t)\n\t);\n}\n","/**\n * Which stages take backups, and where they are kept.\n *\n * A deployed compose stage whose stack runs Postgres is backed up by\n * default — every day at 02:00 UTC, kept 30 days — unless\n * `deploy.backups.<stage>` says otherwise. The local stage never is.\n *\n * Every backup is kept in the project bucket (`providers/projectBucket.ts`),\n * beside the stage's deploy state, one folder per run and one file per\n * database:\n *\n * ```\n * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/database.sql.gz\n * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/auth-database.sql.gz\n * ```\n *\n * Beside the runs, `imports/` holds files prepared by hand for\n * `gkm backup:restore --from` — never listed as a run, never expired — and,\n * with `pitr`, `pitr/` holds WAL-G's archive: `pitr/wal_005/` and\n * `pitr/basebackups_005/`, for `gkm backup:restore --to`.\n *\n * The file is named after the database's construct, the way its migrations\n * folder is: `AuthDatabase` is `db/auth-database`, and `auth-database.sql.gz`.\n */\n\nimport { type ConstructManifest, kebabCase } from '@geekmidas/manifest';\nimport { deploysWithCompose } from '../providers/dns.js';\nimport type { PrefixExpiry } from '../providers/projectBucket.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { checkStageBackups, type StageBackups } from './schedule.js';\n\n/** What a stage's backups come to. */\nexport type StageBackupsChoice =\n\t| {\n\t\t\tmode: 'on';\n\t\t\tbackups: StageBackups;\n\t\t\t/** Whether the stage named it, or took the default. */\n\t\t\tsource: 'config' | 'default';\n\t }\n\t/** `deploy.backups.<stage>: false`. */\n\t| { mode: 'disabled' }\n\t/** Nothing to back up, or nowhere it applies. */\n\t| { mode: 'none'; reason: 'local' | 'not-compose' | 'no-postgres' };\n\n/** The workspace parts {@link stageBackups} reads. */\nexport type BackupsWorkspace = Pick<\n\tNormalizedWorkspace,\n\t'name' | 'apps' | 'deploy' | 'stages' | 'state'\n>;\n\n/** Whether the stack runs Postgres: some construct is a database. */\nexport function runsPostgres(manifest: ConstructManifest): boolean {\n\treturn Object.values(manifest).some((d) => d.kind === 'database');\n}\n\n/**\n * What `stage`'s backups are: on — by its entry or the default — off by\n * `false`, or none, for the local stage, a stage compose does not deploy,\n * and a stack with no database.\n */\nexport function stageBackups(\n\tworkspace: BackupsWorkspace,\n\tmanifest: ConstructManifest,\n\tstage: string,\n): StageBackupsChoice {\n\tif (stage === workspace.stages?.local) {\n\t\treturn { mode: 'none', reason: 'local' };\n\t}\n\tif (!deploysWithCompose(workspace as NormalizedWorkspace)) {\n\t\treturn { mode: 'none', reason: 'not-compose' };\n\t}\n\tif (!runsPostgres(manifest)) return { mode: 'none', reason: 'no-postgres' };\n\tconst value = (\n\t\tworkspace.deploy?.backups as Record<string, unknown> | undefined\n\t)?.[stage];\n\tconst checked = checkStageBackups(stage, value ?? {});\n\tif (checked === false) return { mode: 'disabled' };\n\treturn {\n\t\tmode: 'on',\n\t\tbackups: checked,\n\t\tsource: value === undefined ? 'default' : 'config',\n\t};\n}\n\n/**\n * Where a stage's backups are, in the project bucket — under the same\n * `<prefix>/<project>/<stage>` its deploy state is: `gkm/shop/production/backups`.\n */\nexport function backupsPrefix(\n\tworkspace: Pick<NormalizedWorkspace, 'name' | 'state'>,\n\tstage: string,\n): string {\n\tconst state = workspace.state;\n\tconst prefix =\n\t\tstate?.provider === 's3' && state.prefix !== undefined\n\t\t\t? state.prefix.replace(/\\/+$/, '')\n\t\t\t: 'gkm';\n\treturn `${prefix ? `${prefix}/` : ''}${workspace.name}/${stage}/backups`;\n}\n\n/**\n * Where a stage's point-in-time recovery is kept, beside its runs: WAL-G's\n * own layout under it, `wal_005/` and `basebackups_005/`.\n */\nexport function pitrPrefix(\n\tworkspace: Pick<NormalizedWorkspace, 'name' | 'state'>,\n\tstage: string,\n): string {\n\treturn `${backupsPrefix(workspace, stage)}/${PITR_FOLDER}`;\n}\n\n/** The folder point-in-time recovery is kept in, under the backups prefix. */\nexport const PITR_FOLDER = 'pitr';\n\n/** WAL-G's folder of WAL segments, under the PITR prefix. */\nexport const WAL_FOLDER = 'wal_005';\n\n/** WAL-G's folder of base backups, under the PITR prefix. */\nexport const BASE_BACKUPS_FOLDER = 'basebackups_005';\n\n/**\n * A database's copy, restored beside the live one with `--into <name>`:\n * `drill_auth_database`. The runner (`runner.ts`), which ships alone,\n * keeps a copy of this; a test holds the two to the same answers.\n */\nexport function intoDatabase(into: string, file: string): string {\n\treturn `${into}_${file.replace(/-/g, '_')}`;\n}\n\n/**\n * What every run folder's key starts with, under the stage's backups prefix:\n * the first digit of its year. What the expiry rule matches — `imports/`\n * does not.\n */\nexport const RUNS_PREFIX = '2';\n\n/** One run's folder: `2026-10-10/02-00-00Z`, for the time it started. */\nexport function runFolder(at: Date): string {\n\tconst iso = at.toISOString();\n\treturn `${iso.slice(0, 10)}/${iso.slice(11, 19).replace(/:/g, '-')}Z`;\n}\n\n/** A run folder's time back, or `undefined` for a key that is not one. */\nexport function runTime(folder: string): Date | undefined {\n\tconst match = /^(\\d{4}-\\d{2}-\\d{2})\\/(\\d{2})-(\\d{2})-(\\d{2})Z$/.exec(folder);\n\tif (!match) return undefined;\n\tconst at = new Date(`${match[1]}T${match[2]}:${match[3]}:${match[4]}Z`);\n\treturn Number.isNaN(at.getTime()) ? undefined : at;\n}\n\n/** One database the stack backs up. */\nexport interface BackupDatabase {\n\t/** Its construct: `AuthDatabase`. */\n\tid: string;\n\t/** Its file in a run's folder, less `.sql.gz`: `auth-database`. */\n\tfile: string;\n\t/** Its name in the stack's Postgres: `auth_database_production`. */\n\tname: string;\n}\n\n/** A database's file in a run's folder: `auth-database.sql.gz`. */\nexport function backupFile(database: Pick<BackupDatabase, 'file'>): string {\n\treturn `${database.file}.sql.gz`;\n}\n\n/** Each database the stack runs, by its construct and its name in Postgres. */\nexport function backupDatabases(\n\tresources: readonly { id: string; kind: string; name: string }[],\n): BackupDatabase[] {\n\treturn resources\n\t\t.filter((r) => r.kind === 'database')\n\t\t.map((r) => ({ id: r.id, file: kebabCase(r.id), name: r.name }))\n\t\t.sort((a, b) => a.file.localeCompare(b.file));\n}\n\n/**\n * The expiry of every stage's backups, by each stage's own entry — what the\n * project bucket's lifecycle carries beside its own rule.\n *\n * A put replaces a bucket's whole lifecycle, so this is built from every\n * deployed stage each time, never from the stage being deployed alone: one\n * stage's deploy keeps every other's rule. A stage set to `false` has none,\n * and its backups are kept until someone deletes them.\n *\n * The rule covers the runs and nothing else beside them: a lifecycle filter\n * cannot leave a folder out, so it matches what every run folder starts\n * with — its year, `2…` — and the stage's `imports/` is never expired.\n *\n * A stage with point-in-time recovery has two more: its base backups expire\n * after `pitr.keep`, and its WAL a `pitr.base` interval later, so every\n * segment the oldest kept base backup replays from is still there. Expiry is\n * the bucket's, never `wal-g delete`: the stage's key stays put-only.\n */\nexport function backupExpiries(\n\tworkspace: BackupsWorkspace,\n\tmanifest: ConstructManifest,\n): PrefixExpiry[] {\n\tconst expiries: PrefixExpiry[] = [];\n\tfor (const stage of [...(workspace.stages?.deployed ?? [])].sort()) {\n\t\tconst choice = stageBackups(workspace, manifest, stage);\n\t\tif (choice.mode !== 'on') continue;\n\t\texpiries.push({\n\t\t\tid: `gkm-backups-${stage}`,\n\t\t\tprefix: `${backupsPrefix(workspace, stage)}/${RUNS_PREFIX}`,\n\t\t\tdays: choice.backups.keepDays,\n\t\t\tabortIncompleteDays: 1,\n\t\t});\n\t\tconst pitr = choice.backups.pitr;\n\t\tif (!pitr) continue;\n\t\tconst prefix = pitrPrefix(workspace, stage);\n\t\texpiries.push(\n\t\t\t{\n\t\t\t\tid: `gkm-backups-${stage}-pitr-base`,\n\t\t\t\tprefix: `${prefix}/${BASE_BACKUPS_FOLDER}/`,\n\t\t\t\tdays: pitr.keepDays,\n\t\t\t\tabortIncompleteDays: 1,\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: `gkm-backups-${stage}-pitr-wal`,\n\t\t\t\tprefix: `${prefix}/${WAL_FOLDER}/`,\n\t\t\t\tdays: pitr.walKeepDays,\n\t\t\t\tabortIncompleteDays: 1,\n\t\t\t},\n\t\t);\n\t}\n\treturn expiries;\n}\n","/**\n * Where each bucket's presigned links point, derived from its connection.\n *\n * Not stored and not provisioned: the origin is a function of the connection\n * string (`s3Url.signedOrigin`), so it is computed wherever the connection is\n * resolved — a stage's secrets, MinIO locally — and can never disagree with\n * the links the bucket's client signs.\n */\n\nimport { providedKeyFor } from '@geekmidas/manifest';\nimport * as s3Url from '@geekmidas/storage/s3-url';\n\n/**\n * `<ID>_SIGNED_ORIGIN` for each bucket whose connection `lookup` resolves to\n * an `s3://` URL with a knowable host. A bucket with none, or another scheme,\n * gets nothing rather than a guess.\n */\nexport function signedOrigins(\n\tbuckets: Iterable<string>,\n\tlookup: (key: string) => string | undefined,\n): Record<string, string> {\n\tconst origins: Record<string, string> = {};\n\tfor (const id of buckets) {\n\t\tconst connection = lookup(\n\t\t\tprovidedKeyFor(id, 'objects', 'connectionString'),\n\t\t);\n\t\tif (!connection?.startsWith('s3:')) continue;\n\t\tlet origin: string | undefined;\n\t\ttry {\n\t\t\torigin = s3Url.signedOrigin(s3Url.parse(connection));\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (origin) origins[providedKeyFor(id, 'objects', 'signedOrigin')] = origin;\n\t}\n\treturn origins;\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\tEDGE_TOKEN_KEY,\n\texternalApiUrl,\n\timageOrigins,\n\tmobileOrigins,\n\tPUBLIC_STAGE_KEYS,\n\tprovidedKeyFor,\n\tschemeBase,\n\tsenderAddress,\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 { 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';\nimport { hostFor, hostsFor } from './routes';\nimport { signedOrigins } from './signedOrigins';\n\n/** Where Node reads extra roots from: gkm's local CA, behind the local edge. */\nexport const LOCAL_CA_KEY = 'NODE_EXTRA_CA_CERTS';\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 * The other addresses each construct answers on, keyed by id: its\n\t * `aliases`, as a target placed them (`gkm compose`'s edge). Absent, a\n\t * construct behind the local edge answers its aliases under the project,\n\t * as `hostsFor` names them. A site's are origins every surface it calls\n\t * trusts; its `redirects` are not, since the browser never runs there.\n\t */\n\taliasAddresses?: Readonly<Record<string, readonly 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, `localhost` by default. Each mail\n\t * construct sends as its own local part at it (`senderAddress`).\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\tmailDomain?: 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 *\n * But for a frontend's stage (`PUBLIC_STAGE_KEYS`), which is a name rather\n * than an address: a stored one is how the stage told its bundle what it is\n * called, and it wins here as it wins in an image build.\n */\nexport function stageEnv(\n\tstored: Readonly<Record<string, string>>,\n\tresolved: Readonly<Record<string, string>>,\n): Record<string, string> {\n\tconst env = { ...stored, ...resolved };\n\tfor (const key of PUBLIC_STAGE_KEYS) {\n\t\tconst value = stored[key];\n\t\tif (value !== undefined) env[key] = value;\n\t}\n\treturn env;\n}\n\n/**\n * The token a stack's own services prove themselves with at its edge\n * (`EDGE_TOKEN_HEADER`): derived from the stage's seed, as a bucket's webhook\n * token is, so every process, the edge and the auth server agree on it with\n * nothing stored.\n */\nexport function edgeToken(project: string, seed?: string): string {\n\treturn createHash('sha256')\n\t\t.update(`${seed ? `${seed}:` : ''}${project}:edge-token`)\n\t\t.digest('base64url')\n\t\t.slice(0, 43);\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\tconst aliased = aliasAddressesFor(plan, options);\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\taliased,\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, { aliased })[\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'trustedOrigins')\n\t\t\t];\n\t\t\tif (origins !== undefined) {\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'trustedOrigins')] =\n\t\t\t\t\torigins;\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[\n\t\t\t\t\tprovidedKeyFor(\n\t\t\t\t\t\tresource.id,\n\t\t\t\t\t\tresource.kind,\n\t\t\t\t\t\t'publisherConnectionString',\n\t\t\t\t\t)\n\t\t\t\t] = 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[providedKeyFor(resource.id, resource.kind, 'domain')] = domain;\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, '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)\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, '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[providedKeyFor(resource.id, resource.kind, 'credentials')] =\n\t\t\t\tresource.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[providedKeyFor(resource.id, resource.kind, '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[providedKeyFor(resource.id, resource.kind, '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[providedKeyFor(resource.id, resource.kind, 'from')] = senderAddress(\n\t\t\t\tresource,\n\t\t\t\toptions.mailDomain ?? LOCAL_HOST,\n\t\t\t);\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[providedKeyFor(resource.id, resource.kind, '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(\n\t\tenv,\n\t\tsignedOrigins(\n\t\t\tplan.resources.filter((r) => r.kind === 'objects').map((r) => r.id),\n\t\t\t(key) => env[key],\n\t\t),\n\t);\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[\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'eventsConnectionString')\n\t\t\t] = relay;\n\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'eventsToken')] =\n\t\t\t\tobjectsWebhookToken(\n\t\t\t\t\toptions.project ?? '',\n\t\t\t\t\tresource.id,\n\t\t\t\t\tcredential.seed,\n\t\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// The stack's token, which its services send when they call a sibling\n\t// through the edge — and which the edge and the auth server know it by.\n\t// Only where a surface resolved: with none, there is no sibling to call.\n\tif (\n\t\tplan.resources.some(\n\t\t\t(r) =>\n\t\t\t\t(r.kind === 'rest-api' || r.kind === 'websocket-api') && env[r.envKey],\n\t\t)\n\t) {\n\t\tenv[EDGE_TOKEN_KEY] = edgeToken(options.project ?? '', credential.seed);\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\tif (resource.imageOrigins) {\n\t\t\tconst origins = imageOrigins(\n\t\t\t\tresource.imageOrigins.sources,\n\t\t\t\t(key) => resolved[key],\n\t\t\t);\n\t\t\tif (origins) env[resource.imageOrigins.key] = origins;\n\t\t}\n\t\t// The stage it runs in, as a deployed build inlines it — so a gate on\n\t\t// `NEXT_PUBLIC_STAGE` behaves the same under `gkm dev` and `gkm test`.\n\t\t// Beside its own value, as every key a construct has: a frontend this\n\t\t// stage does not run is handed nothing.\n\t\tif (resource.stageKey && resolved[resource.envKey]) {\n\t\t\tenv[resource.stageKey] = plan.stage;\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\t/** Each caller's alias addresses — origins beside its own. */\n\t\taliased?: Readonly<Record<string, readonly string[]>>;\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.flatMap((caller) =>\n\t\t\t\t\tresolved[caller]\n\t\t\t\t\t\t? [resolved[caller], ...(local.aliased?.[caller] ?? [])]\n\t\t\t\t\t\t: [],\n\t\t\t\t)\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[providedKeyFor(resource.id, resource.kind, 'trustedOrigins')]: [\n\t\t\t...origins,\n\t\t\t...new Set(schemes),\n\t\t].join(','),\n\t\t...(domain\n\t\t\t? { [providedKeyFor(resource.id, resource.kind, 'cookieDomain')]: domain }\n\t\t\t: {}),\n\t\t...(device\n\t\t\t? { [providedKeyFor(resource.id, resource.kind, 'deviceUrl')]: device }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Every construct's alias addresses: where a target placed them, and\n * otherwise — behind the local edge — each alias under the project, on the\n * edge's port, as {@link hostsFor} names it. Never a redirect's.\n */\nfunction aliasAddressesFor(\n\tplan: Plan,\n\toptions: EnvOptions,\n): Record<string, readonly string[]> {\n\tif (options.aliasAddresses) return { ...options.aliasAddresses };\n\tconst edge = localEdgePort(plan, options.ports);\n\tif (edge === undefined) return {};\n\tconst aliased: Record<string, readonly string[]> = {};\n\tfor (const resource of plan.resources) {\n\t\tif (!resource.aliases?.length) continue;\n\t\tif (!options.addresses?.[resource.id]) continue;\n\t\taliased[resource.id] = hostsFor(\n\t\t\tresource,\n\t\t\toptions.project ?? '',\n\t\t).aliases.map((host) => onEdge('https', host, edge));\n\t}\n\treturn aliased;\n}\n\n/**\n * The port the local edge answers on, on this machine — its Caddy's assigned\n * one, or the shared Traefik edge's — or undefined where no edge serves the\n * stage.\n */\nexport function localEdgePort(\n\tplan: Plan,\n\tports: PortAssignments,\n): number | undefined {\n\tif (!plan.edge) return undefined;\n\treturn plan.edge.proxy === 'caddy'\n\t\t? ports[primaryPortKey('caddy')]\n\t\t: plan.edge.ports.https;\n}\n\n/** A host's address on the local edge: its port kept where it is not 443. */\nfunction onEdge(scheme: 'https' | 'wss', host: string, port: number): string {\n\treturn `${scheme}://${host}${port === 443 ? '' : `:${port}`}`;\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. */\nexport function 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 = localEdgePort(plan, ports);\n\n\t\treturn address && edge !== undefined\n\t\t\t? onEdge('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 = localEdgePort(plan, ports);\n\n\t\treturn address && edge !== undefined\n\t\t\t? onEdge('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\tconst edge = localEdgePort(plan, ports);\n\t\t\treturn edge !== undefined\n\t\t\t\t? onEdge('https', hostFor(resource, project), edge)\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","/**\n * The stack's `backups` service: what a deployed compose stage with Postgres\n * runs beside its apps, unless `deploy.backups.<stage>` is `false`.\n *\n * - **The image** is built from the stack's own Postgres image —\n * `postgres:<major>-alpine`, already on the server for the stack, and with\n * the `pg_dump` that matches the server — with Node added and gkm's runner\n * (`runner.ts`) copied in. Nothing is pulled that the stack does not have,\n * and nothing is mounted from the host: the build context is two files.\n * - **Its key** is `BACKUPS_URL`, from the stage's secrets, like any app's:\n * allowed to put objects under the stage's backups prefix and nothing else.\n * The server holds no AWS credentials of its own.\n * - **Its login** is a role of its own, `<project>_backups`, granted\n * `pg_read_all_data` — it can read every database and write none. Postgres\n * before 14 has no such role, and there it signs in as the stack's\n * superuser.\n * - **Its health** is the last good run: unhealthy once that is more than\n * twice the schedule's longest gap old, after a startup grace.\n *\n * With `pitr`, point-in-time recovery runs beside the dumps:\n *\n * - **The stack's Postgres** is built from its own image with WAL-G added —\n * compiled from source in a build stage, statically, so it runs on any\n * base — and archives its WAL: `wal_level=replica`, `archive_mode=on`,\n * `archive_command='wal-g wal-push %p'`, `archive_timeout=60`. WAL-G reads\n * the backups key and `PITR_KEY` from its own env file, `postgres.env`.\n * - **The backups service** gets the same WAL-G, the data volume mounted\n * read-only, and takes a base backup (`wal-g backup-push`) on `pitr.base`'s\n * schedule. Its health also reads `pg_stat_archiver`.\n * - **Everything is encrypted** client-side (libsodium) with `PITR_KEY`, a\n * stage secret the deploy generates once, so the bucket never holds\n * readable WAL.\n */\n\nimport { createHash, randomBytes } from 'node:crypto';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n\tDEFAULT_POSTGRES_VERSION,\n\ttype PostgresVersion,\n} from '@geekmidas/manifest';\nimport * as s3Url from '@geekmidas/storage/s3-url';\nimport { GkmError } from '../errors';\nimport { declaredPostgresImage, POSTGRES_MOUNT } from '../reconcile/compose.js';\nimport { postgresImage, volumeOf } from '../reconcile/containers.js';\nimport { localRolePassword } from '../reconcile/env.js';\nimport { postgresRoleSlug } from '../reconcile/localCredentials.js';\nimport type { Plan } from '../reconcile/plan.js';\nimport { quoteIdentifier, type Statement } from '../reconcile/provision.js';\nimport {\n\ttype BackupDatabase,\n\ttype BackupsWorkspace,\n\tbackupDatabases,\n\tbackupsPrefix,\n\tpitrPrefix,\n} from './config.js';\nimport type { StageBackups, StagePitr } from './schedule.js';\n\n/** The service's name in the stack. */\nexport const BACKUPS_SERVICE = 'backups';\n\n/** The secret its key is written to. */\nexport const BACKUPS_URL_KEY = 'BACKUPS_URL';\n\n/** The secret WAL and base backups are encrypted with: 32 bytes, hex. */\nexport const PITR_KEY = 'PITR_KEY';\n\n/** A new {@link PITR_KEY}: random, generated once, kept in the stage. */\nexport function newPitrKey(): string {\n\treturn randomBytes(32).toString('hex');\n}\n\n/** The stack's Postgres service, which archives its WAL with `pitr`. */\nexport const POSTGRES_SERVICE = 'postgres';\n\n/** The WAL-G release built into the images. */\nexport const WALG_VERSION = 'v3.0.9';\n\n/** Where WAL-G is, in either image. */\nexport const WALG_PATH = '/usr/local/bin/wal-g';\n\n/** The settings that make Postgres archive its WAL through WAL-G. */\nexport const ARCHIVE_SETTINGS: Readonly<Record<string, string>> = {\n\twal_level: 'replica',\n\tarchive_mode: 'on',\n\tarchive_command: 'wal-g wal-push %p',\n\t// A segment ships at least each minute, even when writes are quiet.\n\tarchive_timeout: '60',\n};\n\n/** Where the runner is, in the image. */\nexport const RUNNER_PATH = '/gkm/backup.mjs';\n\n/** The first Postgres with `pg_read_all_data`. */\nconst READ_ALL_DATA_SINCE = 14;\n\n/** A stage with point-in-time recovery, and no key to encrypt it with. */\nexport class PitrKeyMissing extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(\n\t\t\t`deploy.backups.${stage}.pitr is on, and the stage's secrets hold no ` +\n\t\t\t\t`${PITR_KEY} to encrypt its WAL and base backups with. The deploy ` +\n\t\t\t\t\"generates it, beside BACKUPS_URL — run the deploy with the stage's \" +\n\t\t\t\t'AWS credentials.',\n\t\t);\n\t\tthis.name = 'PitrKeyMissing';\n\t}\n}\n\n/** A stage that backs up, and no key to back up with. */\nexport class BackupsUrlMissing extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(\n\t\t\t`'${stage}' runs Postgres, so its stack backs it up, and its secrets ` +\n\t\t\t\t`hold no ${BACKUPS_URL_KEY} to back up with. The deploy writes it — ` +\n\t\t\t\t\"the IAM user and key it creates in the stage's AWS account — so \" +\n\t\t\t\t'run the deploy with the ' +\n\t\t\t\t\"account's credentials. To take no backups on this stage, set \" +\n\t\t\t\t`deploy.backups.${stage}: false.`,\n\t\t);\n\t\tthis.name = 'BackupsUrlMissing';\n\t}\n}\n\n/** The backups role: `<project>_backups`, as the superuser is `<project>_admin`. */\nexport function backupsRole(project: string): string {\n\treturn `${postgresRoleSlug(project)}_backups`;\n}\n\n/** The stack's backups, as its compose file and env file have them. */\nexport interface StackBackups {\n\tbackups: StageBackups;\n\tdatabases: BackupDatabase[];\n\t/** `gkm/<project>/<stage>/backups`. */\n\tprefix: string;\n\t/** The Postgres image it is built from. */\n\tfrom: string;\n\t/** The stack's Postgres major. */\n\tversion: PostgresVersion;\n\t/** `<project>-backups:pg18-<hash>`: built on the server, never pushed. */\n\timage: string;\n\t/** Its build context: the Dockerfile and the runner. */\n\tfiles: { Dockerfile: string; 'backup.mjs': string };\n\t/** What it signs in to Postgres as. */\n\tlogin: { user: string; password: string };\n\t/** Whether that is its own read-only role (else the superuser). */\n\treadOnly: boolean;\n\t/** Its environment — empty in a stack that only builds. */\n\tenv: Record<string, string>;\n\t/** Point-in-time recovery, when the stage's entry turns it on. */\n\tpitr?: StackPitr;\n}\n\n/** The stack's point-in-time recovery: its Postgres image, and WAL-G's env. */\nexport interface StackPitr {\n\tpitr: StagePitr;\n\t/** `gkm/<project>/<stage>/backups/pitr`. */\n\tprefix: string;\n\t/** The stack's Postgres, with WAL-G: built on the server, never pushed. */\n\tpostgres: {\n\t\t/** The image it is built from: the stack's own Postgres image. */\n\t\tfrom: string;\n\t\t/** `<project>-postgres:pg18-<hash>`. */\n\t\timage: string;\n\t\tfiles: { Dockerfile: string };\n\t\t/** What Postgres runs: its archive settings. */\n\t\tcommand: string[];\n\t\t/** WAL-G's environment, for `archive_command` — empty in a stack that only builds. */\n\t\tenv: Record<string, string>;\n\t};\n}\n\n/**\n * The runner's source, as JavaScript: the built `backups/runner.mjs` beside\n * the CLI's bundle, or — run from source — `runner.ts`, with its types\n * stripped by esbuild.\n */\nexport function runnerSource(): string {\n\tconst here = dirname(fileURLToPath(import.meta.url));\n\tfor (const path of [\n\t\tjoin(here, 'backups', 'runner.mjs'),\n\t\tjoin(here, 'runner.mjs'),\n\t\tjoin(here, '..', 'backups', 'runner.mjs'),\n\t]) {\n\t\tif (existsSync(path)) return readFileSync(path, 'utf-8');\n\t}\n\tconst { transformSync } = createRequire(import.meta.url)(\n\t\t'esbuild',\n\t) as typeof import('esbuild');\n\treturn transformSync(readFileSync(join(here, 'runner.ts'), 'utf-8'), {\n\t\tloader: 'ts',\n\t\tformat: 'esm',\n\t\ttarget: 'node22',\n\t}).code;\n}\n\n/**\n * The build stage both images copy WAL-G from: built from source at\n * {@link WALG_VERSION}, with libsodium for its encryption, linked statically\n * so it runs on whatever base the stack's Postgres image has. The same text\n * in both Dockerfiles, so the second build is the first's cache.\n */\nexport function walgStage(): string {\n\treturn `FROM golang:1-alpine AS wal-g\nRUN apk add --no-cache build-base git libsodium-dev libsodium-static\nRUN git clone --depth 1 --branch ${WALG_VERSION} https://github.com/wal-g/wal-g.git /src\nWORKDIR /src/main/pg\nENV GOTOOLCHAIN=auto CGO_ENABLED=1\nRUN go build -tags libsodium -ldflags '-s -w -linkmode external -extldflags \"-static\"' -o /wal-g .\n`;\n}\n\n/**\n * The image's Dockerfile: the stack's Postgres, Node, and the runner — and,\n * with `pitr`, WAL-G.\n */\nexport function backupsDockerfile(from: string, pitr = false): string {\n\treturn `# Generated by gkm — the stage's backups: pg_dump from ${from}, and gkm's uploader${pitr ? ', and WAL-G' : ''}.\n${pitr ? `${walgStage()}\\n` : ''}FROM ${from}\nRUN apk add --no-cache nodejs\n${pitr ? `COPY --from=wal-g /wal-g ${WALG_PATH}\\n` : ''}COPY backup.mjs ${RUNNER_PATH}\nUSER postgres\nENTRYPOINT []\nCMD [\"node\", \"${RUNNER_PATH}\", \"serve\"]\n`;\n}\n\n/** The stack's Postgres image, with WAL-G added for `archive_command`. */\nexport function pitrPostgresDockerfile(from: string): string {\n\treturn `# Generated by gkm — the stage's Postgres, ${from}, with WAL-G: it archives its WAL.\n${walgStage()}\nFROM ${from}\nCOPY --from=wal-g /wal-g ${WALG_PATH}\n`;\n}\n\n/** What Postgres runs with `pitr`: the image's own command, and the archive settings. */\nexport function pitrPostgresCommand(): string[] {\n\treturn [\n\t\t'postgres',\n\t\t...Object.entries(ARCHIVE_SETTINGS).flatMap(([name, value]) => [\n\t\t\t'-c',\n\t\t\t`${name}=${value}`,\n\t\t]),\n\t];\n}\n\n/**\n * WAL-G's environment, from the stage's backups key and its PITR key:\n * where the archive is, as whom it is put, and the key it is encrypted with.\n * The restore builds the same from the caller's own credentials.\n */\nexport function walgEnv(input: {\n\tbucket: string;\n\tregion?: string;\n\tendpoint?: string;\n\taccessKeyId?: string;\n\tsecretAccessKey?: string;\n\tsessionToken?: string;\n\tprefix: string;\n\tkey: string;\n}): Record<string, string> {\n\treturn {\n\t\tWALG_S3_PREFIX: `s3://${input.bucket}/${input.prefix}`,\n\t\tAWS_REGION: input.region ?? 'us-east-1',\n\t\t...(input.endpoint\n\t\t\t? { AWS_ENDPOINT: input.endpoint, AWS_S3_FORCE_PATH_STYLE: 'true' }\n\t\t\t: {}),\n\t\t...(input.accessKeyId && input.secretAccessKey\n\t\t\t? {\n\t\t\t\t\tAWS_ACCESS_KEY_ID: input.accessKeyId,\n\t\t\t\t\tAWS_SECRET_ACCESS_KEY: input.secretAccessKey,\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(input.sessionToken ? { AWS_SESSION_TOKEN: input.sessionToken } : {}),\n\t\tWALG_LIBSODIUM_KEY: input.key,\n\t\tWALG_LIBSODIUM_KEY_TRANSFORM: 'hex',\n\t\tWALG_COMPRESSION_METHOD: 'lz4',\n\t};\n}\n\nexport interface StackBackupsInput {\n\tworkspace: BackupsWorkspace;\n\tstage: string;\n\tproject: string;\n\tplan: Plan;\n\tbackups: StageBackups;\n\t/** The stage's secrets, by key. */\n\tcustom: Readonly<Record<string, string>>;\n\tseed: string;\n\t/** The stack's superuser. */\n\tsuperuser: { user: string; password: string };\n\t/** What the stage's telemetry hands a process, when it is on. */\n\ttelemetry?: Readonly<Record<string, string>>;\n\t/** The stack only builds: no environment, no key needed. */\n\tbuildOnly?: boolean;\n}\n\n/**\n * The stack's backups service, for a stage whose backups are on.\n *\n * @throws {BackupsUrlMissing} when the stage's secrets hold no key\n * @throws {PitrKeyMissing} with `pitr`, when they hold no PITR key\n */\nexport function stackBackups(input: StackBackupsInput): StackBackups {\n\tconst { plan, stage } = input;\n\tconst pitr = input.backups.pitr;\n\tconst version =\n\t\tplan.resources.find((r) => r.version)?.version ?? DEFAULT_POSTGRES_VERSION;\n\tconst from = postgresImage(version);\n\tconst script = runnerSource();\n\tconst dockerfile = backupsDockerfile(from, pitr !== undefined);\n\tconst hash = createHash('sha256')\n\t\t.update(dockerfile)\n\t\t.update(script)\n\t\t.digest('hex')\n\t\t.slice(0, 12);\n\n\tconst readOnly = version >= READ_ALL_DATA_SINCE;\n\tconst role = backupsRole(input.workspace.name);\n\tconst login = readOnly\n\t\t? {\n\t\t\t\tuser: role,\n\t\t\t\tpassword: localRolePassword(\n\t\t\t\t\tinput.workspace.name,\n\t\t\t\t\tplan,\n\t\t\t\t\trole,\n\t\t\t\t\tinput.seed,\n\t\t\t\t),\n\t\t\t}\n\t\t: input.superuser;\n\n\tconst databases = backupDatabases(plan.resources);\n\tconst prefix = backupsPrefix(input.workspace, stage);\n\tconst { kind, ...schedule } = input.backups.schedule;\n\n\tconst archive = pitr ? pitrPrefix(input.workspace, stage) : undefined;\n\tlet walg: Record<string, string> = {};\n\tlet env: Record<string, string> = {};\n\tif (!input.buildOnly) {\n\t\tconst url = input.custom[BACKUPS_URL_KEY];\n\t\tif (!url) throw new BackupsUrlMissing(stage);\n\t\tif (pitr && archive) {\n\t\t\tconst key = input.custom[PITR_KEY];\n\t\t\tif (!key) throw new PitrKeyMissing(stage);\n\t\t\tconst address = s3Url.parse(url);\n\t\t\twalg = walgEnv({\n\t\t\t\tbucket: address.bucket,\n\t\t\t\t...(address.region ? { region: address.region } : {}),\n\t\t\t\t...(address.endpoint ? { endpoint: address.endpoint } : {}),\n\t\t\t\t...(address.accessKeyId ? { accessKeyId: address.accessKeyId } : {}),\n\t\t\t\t...(address.secretAccessKey\n\t\t\t\t\t? { secretAccessKey: address.secretAccessKey }\n\t\t\t\t\t: {}),\n\t\t\t\tprefix: archive,\n\t\t\t\tkey,\n\t\t\t});\n\t\t}\n\t\tenv = {\n\t\t\tBACKUPS_URL: url,\n\t\t\tBACKUPS_PREFIX: prefix,\n\t\t\tBACKUPS_DATABASES: JSON.stringify(\n\t\t\t\tdatabases.map(({ file, name }) => ({ file, name })),\n\t\t\t),\n\t\t\tBACKUPS_SCHEDULE: JSON.stringify(\n\t\t\t\tkind === 'cron'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tminutes: input.backups.schedule.minutes,\n\t\t\t\t\t\t\thours: input.backups.schedule.hours,\n\t\t\t\t\t\t\tdays: input.backups.schedule.days,\n\t\t\t\t\t\t\tmonths: input.backups.schedule.months,\n\t\t\t\t\t\t\tweekdays: input.backups.schedule.weekdays,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { kind, ...schedule },\n\t\t\t),\n\t\t\tBACKUPS_MAX_GAP_SECONDS: String(input.backups.maxGapSeconds),\n\t\t\t...(pitr\n\t\t\t\t? {\n\t\t\t\t\t\tPITR_BASE_SCHEDULE: JSON.stringify(pitr.base),\n\t\t\t\t\t\tPITR_BASE_MAX_GAP_SECONDS: String(pitr.base.seconds),\n\t\t\t\t\t\t...walg,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tPGHOST: 'postgres',\n\t\t\tPGPORT: '5432',\n\t\t\tPGUSER: login.user,\n\t\t\tPGPASSWORD: login.password,\n\t\t\t...(input.telemetry?.OTEL_EXPORTER_OTLP_ENDPOINT\n\t\t\t\t? {\n\t\t\t\t\t\tOTEL_EXPORTER_OTLP_ENDPOINT:\n\t\t\t\t\t\t\tinput.telemetry.OTEL_EXPORTER_OTLP_ENDPOINT,\n\t\t\t\t\t\t...(input.telemetry.OTEL_EXPORTER_OTLP_HEADERS\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tOTEL_EXPORTER_OTLP_HEADERS:\n\t\t\t\t\t\t\t\t\t\tinput.telemetry.OTEL_EXPORTER_OTLP_HEADERS,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tOTEL_SERVICE_NAME: BACKUPS_SERVICE,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\treturn {\n\t\tbackups: input.backups,\n\t\tdatabases,\n\t\tprefix,\n\t\tfrom,\n\t\tversion,\n\t\timage: `${input.project}-backups:pg${version}-${hash}`,\n\t\tfiles: { Dockerfile: dockerfile, 'backup.mjs': script },\n\t\tlogin,\n\t\treadOnly,\n\t\tenv,\n\t\t...(pitr && archive\n\t\t\t? { pitr: stackPitr(input.project, plan, version, pitr, archive, walg) }\n\t\t\t: {}),\n\t};\n}\n\n/** The stack's Postgres with WAL-G, built from the stack's own image. */\nfunction stackPitr(\n\tproject: string,\n\tplan: Plan,\n\tversion: PostgresVersion,\n\tpitr: StagePitr,\n\tprefix: string,\n\tenv: Record<string, string>,\n): StackPitr {\n\tconst from = declaredPostgresImage(plan) ?? postgresImage(version);\n\tconst dockerfile = pitrPostgresDockerfile(from);\n\tconst hash = createHash('sha256')\n\t\t.update(dockerfile)\n\t\t.digest('hex')\n\t\t.slice(0, 12);\n\treturn {\n\t\tpitr,\n\t\tprefix,\n\t\tpostgres: {\n\t\t\tfrom,\n\t\t\timage: `${project}-postgres:pg${version}-${hash}`,\n\t\t\tfiles: { Dockerfile: dockerfile },\n\t\t\tcommand: pitrPostgresCommand(),\n\t\t\tenv,\n\t\t},\n\t};\n}\n\n/**\n * The stack's Postgres service made to archive its WAL: built from its own\n * image with WAL-G, run with the archive settings, and handed WAL-G's\n * environment from its own env file.\n */\nexport function withArchiving<S extends { image: string }>(\n\tpostgres: S,\n\tpitr: StackPitr,\n\tenvFiles: boolean,\n) {\n\treturn {\n\t\t...postgres,\n\t\timage: pitr.postgres.image,\n\t\tbuild: { context: `./${POSTGRES_SERVICE}`, dockerfile: 'Dockerfile' },\n\t\tpull_policy: 'build' as const,\n\t\tcommand: pitr.postgres.command,\n\t\t...(envFiles\n\t\t\t? {\n\t\t\t\t\tenv_file: [\n\t\t\t\t\t\t{ path: `./${POSTGRES_SERVICE}.env`, format: 'raw' as const },\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/** The service in the stack's compose file. */\nexport function backupsService(backups: StackBackups, envFiles: boolean) {\n\treturn {\n\t\timage: backups.image,\n\t\t// Built on the server from two files; there is nothing to pull.\n\t\tbuild: { context: `./${BACKUPS_SERVICE}`, dockerfile: 'Dockerfile' },\n\t\tpull_policy: 'build' as const,\n\t\trestart: 'unless-stopped',\n\t\t...(envFiles\n\t\t\t? {\n\t\t\t\t\tenv_file: [\n\t\t\t\t\t\t{ path: `./${BACKUPS_SERVICE}.env`, format: 'raw' as const },\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t: {}),\n\t\t// A base backup reads the cluster's files; it never writes them.\n\t\t...(backups.pitr\n\t\t\t? { volumes: [`${volumeOf(POSTGRES_SERVICE)}:${POSTGRES_MOUNT}:ro`] }\n\t\t\t: {}),\n\t\tdepends_on: { postgres: { condition: 'service_healthy' as const } },\n\t\thealthcheck: {\n\t\t\ttest: ['CMD', 'node', RUNNER_PATH, 'health'],\n\t\t\tinterval: '1m',\n\t\t\ttimeout: '10s',\n\t\t\tretries: 3,\n\t\t\tstart_period: '30s',\n\t\t},\n\t};\n}\n\n/**\n * What a base backup calls, by major: Postgres 15 renamed the functions,\n * and 14 — the first the role is used on — has the old ones.\n */\nfunction baseBackupFunctions(version: PostgresVersion): string[] {\n\treturn version >= 15\n\t\t? ['pg_backup_start(text, boolean)', 'pg_backup_stop(boolean)']\n\t\t: [\n\t\t\t\t'pg_start_backup(text, boolean, boolean)',\n\t\t\t\t'pg_stop_backup(boolean, boolean)',\n\t\t\t];\n}\n\n/**\n * The backups role, created and kept: able to sign in and read every\n * database, and nothing else. None when it signs in as the superuser.\n *\n * With `pitr` it may also take a base backup — start and stop one, and\n * switch to a new WAL segment — and read the archiver's statistics\n * (`pg_monitor`), which its health check reads. It still writes nothing.\n */\nexport function backupsRoleStatements(backups: StackBackups): Statement[] {\n\tif (!backups.readOnly) return [];\n\tconst role = quoteIdentifier(backups.login.user);\n\tconst password = `'${backups.login.password.replace(/'/g, \"''\")}'`;\n\tconst pitr: Statement[] = backups.pitr\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tid: BACKUPS_SERVICE,\n\t\t\t\t\tdescribe: `role ${backups.login.user}: read the archiver's statistics`,\n\t\t\t\t\tcreate: `GRANT pg_monitor TO ${role}`,\n\t\t\t\t},\n\t\t\t\t...[...baseBackupFunctions(backups.version), 'pg_switch_wal()'].map(\n\t\t\t\t\t(fn): Statement => ({\n\t\t\t\t\t\tid: BACKUPS_SERVICE,\n\t\t\t\t\t\tdescribe: `role ${backups.login.user}: take a base backup — ${fn}`,\n\t\t\t\t\t\tcreate: `GRANT EXECUTE ON FUNCTION ${fn} TO ${role}`,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t]\n\t\t: [];\n\treturn [\n\t\t{\n\t\t\tid: BACKUPS_SERVICE,\n\t\t\tdescribe: `role ${backups.login.user}`,\n\t\t\texists: {\n\t\t\t\tsql: 'SELECT 1 FROM pg_roles WHERE rolname = $1',\n\t\t\t\tvalues: [backups.login.user],\n\t\t\t},\n\t\t\tcreate: `CREATE ROLE ${role} LOGIN PASSWORD ${password}`,\n\t\t},\n\t\t{\n\t\t\tid: BACKUPS_SERVICE,\n\t\t\tdescribe: `role ${backups.login.user}: its password`,\n\t\t\tcreate: `ALTER ROLE ${role} WITH LOGIN PASSWORD ${password}`,\n\t\t},\n\t\t{\n\t\t\tid: BACKUPS_SERVICE,\n\t\t\tdescribe: `role ${backups.login.user}: read every database`,\n\t\t\tcreate: `GRANT pg_read_all_data TO ${role}`,\n\t\t},\n\t\t...pitr,\n\t];\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 { fileServerLabel } from '../workspace/fileServerLabel.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 `${fileServerLabel(fileServerId)}-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\timageOrigins,\n\timageOriginsFor,\n\tPUBLIC_PREFIX,\n\ttype PublicDeclaration,\n\tprovidedKeyFor,\n\tpublicEnvFor,\n\tpublicStageKey,\n\tpublicValues,\n\ttype SiteDeclaration,\n} from '@geekmidas/manifest';\nimport { GkmError } from '../errors.js';\nimport { signedOrigins } from '../reconcile/signedOrigins.js';\nimport { appKey } from '../workspace/derive.js';\n\n/**\n * A site's build inlines where it loads files from — a file server's URL, a\n * bucket's signed origin — and the stage has not resolved it yet: a provider\n * writes it on the stage's first deploy. Built anyway, the bundle would ship\n * without its own asset host, and every image from it would be refused.\n */\nexport class SiteBuildValueUnresolved extends GkmError {\n\tconstructor(\n\t\treadonly site: string,\n\t\treadonly key: string,\n\t\treadonly stage: string,\n\t\t/** The stored key it is derived from, where it is derived. */\n\t\treadonly from?: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${site}' inlines ${key} into its build, and the stage '${stage}' ` +\n\t\t\t\t`has ${from ? `no ${from} to derive it from` : 'no value for it'} yet. ` +\n\t\t\t\t`A provider writes it on the stage's first deploy: deploy the stage ` +\n\t\t\t\t`first (gkm deploy --stage ${stage}), then build. Or set it: ` +\n\t\t\t\t`gkm secrets:set ${from ?? key} '…' --stage ${stage}`,\n\t\t);\n\t\tthis.name = 'SiteBuildValueUnresolved';\n\t}\n}\n\n/** The stage a site is built for, and how a missing value is treated. */\nexport interface PublicBuildOptions {\n\t/** The stage being built for: inlined as `publicStageKey`. */\n\tstage: string;\n\t/**\n\t * Refuse a build whose file origins — each file server's URL, each\n\t * bucket's signed origin — the stage has not resolved, naming the stage.\n\t * A deployed stage's build; locally every one resolves.\n\t */\n\trequireFileOrigins?: boolean;\n}\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 * - **The stage it is built for**, under the prefix (`NEXT_PUBLIC_STAGE`):\n * what a bundle gates production-only code on, as a process reads `STAGE`.\n * A stage secret of that name wins, unlike every other derived value.\n *\n * A value the stage resolves to nothing is left out rather than passed empty\n * — except, with `requireFileOrigins`, where its pages load files from.\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: PublicDeclaration,\n\tmanifest: ConstructManifest,\n\tresolve: (key: string) => string | undefined,\n\tsecrets: Readonly<Record<string, string>>,\n\toptions: PublicBuildOptions,\n): Record<string, string> {\n\tconst args: Record<string, string> = {};\n\n\tconst own = providedKeyFor(\n\t\tsite.id,\n\t\tsite.kind,\n\t\tsite.kind === 'site' ? 'url' : 'scheme',\n\t);\n\tconst ownValue = resolve(own);\n\tif (ownValue) args[own] = ownValue;\n\n\t// A bucket's signed origin is derived from its connection, wherever that\n\t// resolved — so it is resolved here too, rather than looked up.\n\tconst derived = signedOrigins(\n\t\tObject.keys(manifest).filter((id) => manifest[id]?.kind === 'objects'),\n\t\tresolve,\n\t);\n\tfor (const [key, source] of Object.entries(publicEnvFor(site, manifest))) {\n\t\tconst value = resolve(source) ?? derived[source];\n\t\tif (value) args[key] = value;\n\t}\n\n\tconst prefix = PUBLIC_PREFIX[site.variant];\n\tif (options.requireFileOrigins) {\n\t\tfor (const value of publicValues(site, manifest)) {\n\t\t\tif (value.kind === 'file-server' && value.role === 'url') {\n\t\t\t\tif (!resolve(value.key)) {\n\t\t\t\t\tthrow new SiteBuildValueUnresolved(site.id, value.key, options.stage);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A signed origin is derived: what has to resolve is the connection.\n\t\t\t// One that resolved to no knowable host is not a missing value.\n\t\t\tif (value.kind === 'objects' && value.role === 'signedOrigin') {\n\t\t\t\tconst connection = providedKeyFor(\n\t\t\t\t\tvalue.id,\n\t\t\t\t\t'objects',\n\t\t\t\t\t'connectionString',\n\t\t\t\t);\n\t\t\t\tif (!resolve(value.key) && !resolve(connection)) {\n\t\t\t\t\tthrow new SiteBuildValueUnresolved(\n\t\t\t\t\t\tsite.id,\n\t\t\t\t\t\tvalue.key,\n\t\t\t\t\t\toptions.stage,\n\t\t\t\t\t\tconnection,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tconst images = imageOriginsFor(site, manifest);\n\tconst origins =\n\t\timages &&\n\t\timageOrigins(\n\t\t\timages.sources,\n\t\t\t(source) => resolve(source) ?? derived[source],\n\t\t);\n\tif (images && origins) args[images.key] = origins;\n\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\targs[publicStageKey(site)] ??= options.stage;\n\n\treturn args;\n}\n\n/**\n * Where a site's own hosts point during its image build: this loopback\n * address, on which nothing in a build container listens — so a request to\n * one is refused at once instead of waiting on a host that is not up yet.\n */\nexport const OFFLINE_BUILD_ADDRESS = '127.0.0.1';\n\n/**\n * The hosts a site's image build must not wait on: its own and those of the\n * constructs its `.dependsOn()` names, as this stage serves them.\n *\n * None of them answers while the image is built — the stack the site belongs\n * to is started after it — and a fetch to a public host that does not answer\n * yet can stall until the framework's prerender limit (Next's 60s). Mapped to\n * {@link OFFLINE_BUILD_ADDRESS} in the build's `/etc/hosts`, each is refused\n * at once, and the page renders on its first request instead.\n *\n * The mapping is the build's only: the URLs the bundle inlines are the real\n * ones, and the running container resolves them as anything else does. A\n * stage secret named for the bundle is someone else's host (an analytics\n * service, a store) and is left alone, as are `localhost` and an address.\n *\n * None for a site that pre-renders against its stage (`prerender: 'stage'`):\n * it is built once those hosts answer, and has to reach them.\n */\nexport function offlineBuildHosts(\n\tsite: SiteDeclaration,\n\tmanifest: ConstructManifest,\n\tresolve: (key: string) => string | undefined,\n): string[] {\n\tif (site.prerender === 'stage') return [];\n\tconst sources = [\n\t\tprovidedKeyFor(site.id, site.kind, 'url'),\n\t\t...Object.values(publicEnvFor(site, manifest)),\n\t];\n\tconst hosts = new Set<string>();\n\tfor (const source of sources) {\n\t\tconst host = hostOf(resolve(source));\n\t\tif (host) hosts.add(host);\n\t}\n\treturn [...hosts].sort();\n}\n\n/** A URL's host, where it is a name `/etc/hosts` can map. */\nfunction hostOf(value: string | undefined): string | undefined {\n\tif (!value || !URL.canParse(value)) return undefined;\n\tconst { protocol, hostname } = new URL(value);\n\tif (!/^(https?|wss?):$/.test(protocol)) return undefined;\n\t// A wildcard is no one name: `/etc/hosts` maps names, not patterns.\n\tif (hostname === 'localhost' || hostname.includes('*')) return undefined;\n\t// An address is reached as it is; only a name is looked up.\n\tif (/^[\\d.]+$/.test(hostname) || hostname.startsWith('[')) return undefined;\n\treturn hostname;\n}\n\n/**\n * {@link offlineBuildHosts} for a target that knows each app's public URL by\n * its app key rather than by construct key — the site's own, and each app it\n * calls. None, for an app that declares no site.\n */\nexport function siteOfflineHosts(\n\tmanifest: ConstructManifest,\n\tappName: string,\n\townUrl: string,\n\turls: Readonly<Record<string, string>>,\n): string[] {\n\tconst entries = Object.entries(manifest);\n\tconst site = entries.find(\n\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t)?.[1];\n\tif (site?.kind !== 'site') return [];\n\n\tconst byKey = new Map<string, string>();\n\tfor (const [id] of entries) {\n\t\tconst name = appKey(id);\n\t\tconst url = name === appName ? ownUrl : urls[name];\n\t\tif (url) byKey.set(providedKeyFor(id, manifest[id]!.kind, 'url'), url);\n\t}\n\treturn offlineBuildHosts(site, manifest, (key) => byKey.get(key));\n}\n\n/**\n * Whether a site runs a server of its own — Next's, TanStack Start's — which\n * reads an environment at runtime as a backend does: its edges' public URLs\n * and the stage's secrets. A `static` site is a finished bundle, and reads\n * nothing once it is built.\n */\nexport function runsServer(site: Pick<SiteDeclaration, 'variant'>): boolean {\n\treturn site.variant !== 'static';\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 * Set by a site's Dockerfile in its builder stage: this build is offline —\n * no stage is reachable from it.\n *\n * A site's image is built before the stack it belongs to runs, so the APIs\n * its `.dependsOn()` names do not answer yet: data a page fetches while the\n * framework prerenders it would be none, cached as the page. A site tests\n * `process.env.GKM_BUILD_OFFLINE === '1'` to skip that fetch, and renders the\n * page on its first request instead — which gkm's warm-up after a deploy\n * makes before any visitor does.\n *\n * Separate from {@link IMAGE_BUILD_ENV}, which says what `gkm exec` injects:\n * this says what the build can reach. Only the builder stage sets it; the\n * running container never has it.\n */\nexport const BUILD_OFFLINE_ENV = 'GKM_BUILD_OFFLINE';\n\n/** Whether this process is a build that no stage is reachable from. */\nexport function isOfflineBuild(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn env[BUILD_OFFLINE_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, posix } from 'node:path';\nimport { externalsManifestName } from '../build/native';\nimport {\n\tNEXT_ACTIONS_KEY,\n\tNEXT_DEPLOYMENT_ID_KEY,\n} from '../deploy/nextRelease';\nimport { BUILD_OFFLINE_ENV, 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\t/**\n\t * A backend's: its workspace name, when its directory holds another app.\n\t * The build in the image is told which app it is (`gkm build --app`),\n\t * since the directory alone names the first, and writes under\n\t * `.gkm/server/<app>/`.\n\t */\n\tsharedDirectoryApp?: string;\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\t/**\n\t * The site pre-renders against its stage (`prerender: 'stage'`): its\n\t * build is not offline — it runs once the site's APIs are up, and reaches\n\t * them — so `GKM_BUILD_OFFLINE` is not set, and the build trusts the root\n\t * {@link LOCAL_CA_BUILD_SECRET} hands it, where it is handed one.\n\t */\n\tprerender?: boolean;\n}\n\n/**\n * The build secret a site that pre-renders against its stage reads the root\n * certificate of the stage's edge from — gkm's local CA, on the local stage,\n * whose hosts no public root vouches for. A certificate, not a key; a secret\n * only because a build has no other way to be handed a file it should not\n * keep. Absent on a deployed stage, whose certificates are public ones.\n */\nexport const LOCAL_CA_BUILD_SECRET = 'gkm_local_ca';\n\n/**\n * The build argument naming the deploy a site that pre-renders against its\n * stage is built for — new on every deploy, so the layer that fetches the\n * stage's data is never served from Docker's cache.\n */\nexport const PRERENDER_RUN_ARG = 'GKM_PRERENDER_RUN';\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 * - `GKM_BUILD_OFFLINE`, which tells the site's own code that no stage is\n * reachable from this build: its APIs are not up yet, so a page that\n * fetches from them renders on request rather than at build.\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: FrontendDockerfileOptions): 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\n${\n\toptions.prerender\n\t\t? `# Built once the site's APIs are up on its stage: it pre-renders from them`\n\t\t: `# No stage is reachable from this build: the site's APIs are not up yet\nENV ${BUILD_OFFLINE_ENV}=1`\n}${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, `GKM_IMAGE_BUILD` and `GKM_BUILD_OFFLINE`\n * — whatever the project's turbo.json declares: the image's environment\n * holds nothing else.\n */\nfunction siteBuild(options: FrontendDockerfileOptions): string {\n\tconst { turbo } = layout(options);\n\tconst build = `${turbo} run build --filter='${options.turboPackage}' --env-mode=loose`;\n\tif (!options.prerender) return `RUN ${build}`;\n\t// Its APIs answer at their public hosts, behind the stage's certificate:\n\t// on the local stage that chains to gkm's own root, handed in as a secret.\n\t// What they answer changes with no change to the source, so each deploy's\n\t// run is part of the cache key: a cached layer would ship the last data.\n\tconst ca = `/run/secrets/${LOCAL_CA_BUILD_SECRET}`;\n\treturn `ARG ${PRERENDER_RUN_ARG}=\"\"\nRUN --mount=type=secret,id=${LOCAL_CA_BUILD_SECRET},required=false \\\\\n echo \"prerendered for: \\${${PRERENDER_RUN_ARG}:-any run}\" && \\\\\n if [ -s ${ca} ]; then export NODE_EXTRA_CA_CERTS=${ca}; fi && \\\\\n ${build}`;\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\tdistDir: 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 ${distDir}/${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 * What every Next build is handed beside its public values: its release, as\n * its `deploymentId`, and the stage's server actions key (`nextBuildValues`).\n * Build args of the builder stage alone — the runner's history has neither,\n * though Next writes the key into the server's manifest it copies.\n */\nconst NEXT_RELEASE_ARGS = [NEXT_DEPLOYMENT_ID_KEY, NEXT_ACTIONS_KEY];\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, ...NEXT_RELEASE_ARGS] })}\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 * Where Next's prerender manifest is in the image {@link\n * generateNextjsDockerfile} builds: the standalone output is copied to the\n * runner's `/app`, and the app's `.next/` — its manifests among them — sits\n * beside its `server.js`, at `appPath` under it.\n */\nexport function nextPrerenderManifest(appPath: string): string {\n\treturn posix.join('/app', appPath, '.next', 'prerender-manifest.json');\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\t// Where `gkm build` leaves the bundles: its own tree, for an app sharing\n\t// its directory with another.\n\tconst shared = options.sharedDirectoryApp;\n\tconst dist = `${app}/.gkm/server${shared ? `/${shared}` : ''}/dist`;\n\tconst externals = externalsStages(dist, 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${shared ? ` --app ${shared}` : ''}${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 ${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(\n\tlayout: Pick<ImageLayout, 'gkmRoot'>,\n\tpath: string,\n): 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 * A file server's processors as a CDN origin: the names both sides agree on.\n *\n * On a compose stage whose bucket is on S3, the CDN serves the bucket and\n * sends each processor pattern to the stack's processor unit, at a host of\n * its own. That host is public — a CDN reaches its origin over the internet —\n * so the CDN adds a secret header and the edge refuses any request without\n * it. One definition, read by the CDN that sends the header and by the stack\n * whose edge checks it, so the two cannot drift.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { environmentCase } from '@geekmidas/manifest';\nimport { fileServerLabel } from '../workspace/fileServerLabel.js';\n\n/** The header the CDN adds to every request it sends a processor. */\nexport const ORIGIN_VERIFY_HEADER = 'X-Gkm-Origin-Verify';\n\n/**\n * Where a file server's processors answer the CDN:\n * `<fileserver>-processors.<domain>`, `assets-processors.example.com` for\n * `AssetsServer`.\n */\nexport function processorOriginHost(serverId: string, domain: string): string {\n\treturn `${fileServerLabel(serverId)}-processors.${domain}`.toLowerCase();\n}\n\n/** The stage secret holding the header's value: `ASSETS_SERVER_ORIGIN_SECRET`. */\nexport function originSecretKey(serverId: string): string {\n\t// A key of the surface node itself, not one it provides.\n\treturn environmentCase(`${serverId}_originSecret`);\n}\n\n/**\n * What the processor unit reads that secret from. Set wherever the CDN fronts\n * it, so the unit refuses a request without the header itself — on Dokploy,\n * whose edge cannot match a header, the only check; behind the stack's own\n * edge, a second one.\n */\nexport const PROCESSOR_ORIGIN_SECRET_ENV = 'GKM_PROCESSOR_ORIGIN_SECRET';\n\n/** A new value for that secret: random, generated once, kept in the stage. */\nexport function newOriginSecret(): string {\n\treturn randomBytes(32).toString('base64url');\n}\n","/**\n * The stage secrets gkm keeps for the stack itself rather than for the\n * application: the server's address, the logins of the containers it runs\n * (Redis, OpenObserve), the key backups write with, the secret a CDN sends a\n * file server's processors, the keys the shared edge answers the DNS challenge\n * with.\n *\n * Nothing in an app reads them, so no process is handed one as \"the stage's\n * own\" (`processEnvKeys`) — the containers that do read them are given them\n * by name.\n */\n\nimport { ACME_DNS_SECRET_KEYS } from '@geekmidas/edge/proxy/traefik';\nimport { BACKUPS_URL_KEY, PITR_KEY } from '../backups/service.js';\nimport { isReservedStageKey } from '../compose/dnsConfig.js';\nimport { LOGS_EMAIL_KEY, LOGS_PASSWORD_KEY } from '../compose/logs.js';\nimport { REDIS_PASSWORD_KEY } from '../compose/redis.js';\nimport { NEXT_ACTIONS_KEY } from '../deploy/nextRelease.js';\nimport { PROCESSOR_ORIGIN_SECRET_ENV } from '../providers/processorOrigin.js';\n\nconst STACK_KEYS: ReadonlySet<string> = new Set([\n\tBACKUPS_URL_KEY,\n\tPITR_KEY,\n\tLOGS_EMAIL_KEY,\n\tLOGS_PASSWORD_KEY,\n\tREDIS_PASSWORD_KEY,\n\tPROCESSOR_ORIGIN_SECRET_ENV,\n\t// A Next site's server is handed it by name (`nextRuntimeValues`).\n\tNEXT_ACTIONS_KEY,\n]);\n\n/** A file server's origin secret: `ASSETS_SERVER_ORIGIN_SECRET`. */\nconst ORIGIN_SECRET = /_ORIGIN_SECRET$/;\n\n/** Whether a stage secret is the stack's own, which no app process reads. */\nexport function isStackKey(key: string): boolean {\n\treturn (\n\t\tisReservedStageKey(key) ||\n\t\tACME_DNS_SECRET_KEYS.includes(key) ||\n\t\tkey.startsWith('GKM_') ||\n\t\tSTACK_KEYS.has(key) ||\n\t\tORIGIN_SECRET.test(key)\n\t);\n}\n","/**\n * The server's shared Traefik edge, in Docker: started when a stack needs it,\n * and each stack's routes written to — and removed from — the directory it\n * watches.\n *\n * Everything goes through the server's Docker engine, never its filesystem:\n * the edge's static configuration is handed to it inline, and the directories\n * it watches are volumes each stack writes into with `docker exec`. So the\n * deploy runs anywhere that reaches the engine — a CI runner over SSH — and\n * nothing it writes depends on a path on that machine.\n *\n * gkm-edge (compose project — `GKM_EDGE_PROJECT` renames it)\n * traefik.yml its static configuration (inline config)\n * dynamic/<project>.yml one per stack: routers, services, middlewares\n * certs/<project>.crt|.key a stack's own certificate, where it has one\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport {\n\tclaimsOverlap,\n\tEDGE_CERTS_DIR,\n\tEDGE_DYNAMIC_DIR,\n\tEDGE_NETWORK,\n\tEDGE_PROJECT,\n\tEDGE_SERVICE,\n\ttype EdgeClaim,\n\ttype EdgePorts,\n\tedgeComposeFile,\n\treadEdgeClaims,\n\ttraefikStaticFile,\n} from '@geekmidas/edge/proxy/traefik';\nimport type { ComposeProxy } from '@geekmidas/edge/routes';\nimport { GkmError } from '../errors';\nimport type {\n\tComposeDocker,\n\tDockerEngine,\n\tPortHolder,\n\tStackRef,\n} from './docker.js';\n\n/** The ports the edge is published on, and the variables that move them. */\nexport const EDGE_PORT_ENV = {\n\thttps: 'GKM_COMPOSE_HTTPS_PORT',\n\thttp: 'GKM_COMPOSE_HTTP_PORT',\n} as const;\n\n/**\n * The variable that moves the local stage's OpenObserve off its loopback\n * port, 5080 — which the local stage takes from nowhere else, since it\n * ignores `deploy.telemetry`. Another stack, or another tool, may hold 5080.\n */\nexport const LOGS_PORT_ENV = 'GKM_COMPOSE_LOGS_PORT';\n\n/** A port variable that does not hold a port. */\nexport class EdgePortInvalid extends GkmError {\n\tconstructor(\n\t\treadonly variable: string,\n\t\treadonly value: string,\n\t) {\n\t\tsuper(\n\t\t\t`${variable}=${value} is not a port. Set it to a number between 1 and 65535, or unset it for the default.`,\n\t\t);\n\t\tthis.name = 'EdgePortInvalid';\n\t}\n}\n\n/**\n * The edge's ports, from the environment — 443 and 80 when unset: where\n * `gkm compose` publishes a stack's own Caddy or the shared Traefik edge, and\n * where `gkm dev` finds that edge.\n */\nexport function edgePorts(env: NodeJS.ProcessEnv = process.env): {\n\thttps: number;\n\thttp: number;\n\tlogs?: number;\n} {\n\tconst read = (variable: string, fallback: number) => {\n\t\tconst value = env[variable];\n\t\tif (value === undefined || value === '') return fallback;\n\t\tconst port = Number(value);\n\t\tif (!Number.isInteger(port) || port < 1 || port > 65_535) {\n\t\t\tthrow new EdgePortInvalid(variable, value);\n\t\t}\n\t\treturn port;\n\t};\n\tconst logs = env[LOGS_PORT_ENV] ? read(LOGS_PORT_ENV, 0) : undefined;\n\treturn {\n\t\thttps: read(EDGE_PORT_ENV.https, 443),\n\t\thttp: read(EDGE_PORT_ENV.http, 80),\n\t\t...(logs ? { logs } : {}),\n\t};\n}\n\n/** The edge's compose project, as docker is asked about it. */\nexport function edgeRef(\n\tfile: string,\n\toptions: Pick<StackRef, 'output' | 'signal' | 'host'> = {},\n): StackRef {\n\treturn {\n\t\tproject: EDGE_PROJECT,\n\t\tfile,\n\t\tcwd: dirname(file),\n\t\t...options,\n\t};\n}\n\n/** Writing to or removing from the edge's volumes failed. */\nexport class EdgeWriteFailed extends GkmError {\n\tconstructor(\n\t\treadonly path: string,\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not write ${path} in the shared edge (${EDGE_PROJECT}): ${output.trim() || 'it is not running'}. ` +\n\t\t\t\t`Check it with \\`docker compose -p ${EDGE_PROJECT} ps\\` on the server, and run gkm compose again.`,\n\t\t);\n\t\tthis.name = 'EdgeWriteFailed';\n\t}\n}\n\n/**\n * Something other than the proxy a stack is set to holds the edge's ports.\n *\n * With `proxy: 'traefik'`, any container but the shared edge and the stack's\n * own Caddy, which the deploy moves (see {@link assertEdgePorts}); with\n * `proxy: 'caddy'`, the shared edge, or another stack's Caddy. Refused before\n * anything is started, so the stack is never left half on one proxy and half\n * on the other.\n */\nexport class ComposeProxyClash extends GkmError {\n\tconstructor(\n\t\treadonly project: string,\n\t\treadonly proxy: ComposeProxy,\n\t\treadonly port: number,\n\t\treadonly holder: PortHolder,\n\t) {\n\t\tconst by = holder.project\n\t\t\t? `${holder.container} (compose project ${holder.project})`\n\t\t\t: holder.container;\n\t\tconst fix =\n\t\t\tproxy === 'traefik'\n\t\t\t\t? `The shared edge needs ports 80 and 443. Stop ${holder.container}${holder.project ? ` (docker compose -p ${holder.project} down, or its own gkm compose --down)` : ''}, or move the edge with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.`\n\t\t\t\t: holder.project === EDGE_PROJECT\n\t\t\t\t\t? `That is the server's shared Traefik edge, which other stacks register with. Set deploy.compose.proxy to 'traefik' for this stage so the stack registers with it too, or stop the edge once nothing uses it (docker compose -p ${EDGE_PROJECT} down).`\n\t\t\t\t\t: `Stop ${holder.container}, or publish this stack's Caddy elsewhere with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.`;\n\t\tsuper(\n\t\t\t`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`,\n\t\t);\n\t\tthis.name = 'ComposeProxyClash';\n\t}\n}\n\n/**\n * Refuse a stack whose edge ports are held by anything but its own proxy:\n * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.\n *\n * One holder is not refused: with `'traefik'`, the stack's own Caddy, still\n * running from before the stage was switched. It is this stack's to move and\n * no other's, so it is returned for the deploy to remove just before the edge\n * takes the ports — the moment's downtime the switch costs. Undefined when\n * there is nothing to move.\n */\nexport async function assertEdgePorts(\n\tdocker: ComposeDocker,\n\toptions: {\n\t\tproject: string;\n\t\tproxy: ComposeProxy;\n\t\tports: EdgePorts;\n\t\tengine: DockerEngine;\n\t},\n): Promise<PortHolder | undefined> {\n\tconst { project, proxy, ports } = options;\n\tconst ownCaddy = (holder: PortHolder) =>\n\t\tholder.project === project && holder.service === 'caddy';\n\tlet move: PortHolder | undefined;\n\tfor (const port of [ports.https, ports.http]) {\n\t\tfor (const holder of await docker.publishers(options.engine, port)) {\n\t\t\tif (proxy === 'traefik' && ownCaddy(holder)) {\n\t\t\t\tmove = holder;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst own =\n\t\t\t\tproxy === 'traefik'\n\t\t\t\t\t? holder.project === EDGE_PROJECT\n\t\t\t\t\t: ownCaddy(holder);\n\t\t\tif (!own) throw new ComposeProxyClash(project, proxy, port, holder);\n\t\t}\n\t}\n\treturn move;\n}\n\n/**\n * Write a file into the edge's running container whole or not at all: a\n * temporary name, then a rename. Not `.yml`: the edge reads only `.yml`,\n * `.yaml` and `.toml` files, so it never sees one half written.\n */\nasync function put(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tpath: string,\n\tcontent: string,\n\tmode: '600' | '644' = '644',\n): Promise<void> {\n\tconst result = await docker.exec(\n\t\tedge,\n\t\tEDGE_SERVICE,\n\t\t[\n\t\t\t'sh',\n\t\t\t'-c',\n\t\t\t'set -e; t=\"$1.tmp\"; cat > \"$t\"; chmod \"$2\" \"$t\"; mv \"$t\" \"$1\"',\n\t\t\t'sh',\n\t\t\tpath,\n\t\t\tmode,\n\t\t],\n\t\tcontent,\n\t);\n\tif (result.code !== 0) {\n\t\tthrow new EdgeWriteFailed(path, `${result.stderr}${result.stdout}`);\n\t}\n}\n\n/** Remove files from the edge's container; whether the first was there. */\nasync function remove(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tpaths: readonly string[],\n): Promise<boolean> {\n\tconst result = await docker.exec(edge, EDGE_SERVICE, [\n\t\t'sh',\n\t\t'-c',\n\t\t'e=1; [ -f \"$1\" ] && e=0; rm -f \"$@\"; exit $e',\n\t\t'sh',\n\t\t...paths,\n\t]);\n\treturn result.code === 0;\n}\n\n/**\n * The edge, up: its network and its container — started when it is not\n * running, and recreated when its configuration changed. Idempotent: on a\n * server where it already runs as configured, `up` changes nothing. Its\n * compose file is written to `file`, on this machine: compose reads it here.\n */\nexport async function ensureEdge(\n\tdocker: ComposeDocker,\n\toptions: {\n\t\tfile: string;\n\t\tports: EdgePorts;\n\t\tlogging: { driver: string; options: Record<string, string> };\n\t\thost?: string;\n\t\toutput?: StackRef['output'];\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<string[]> {\n\tconst { file, ports } = options;\n\tconst staticConfig = traefikStaticFile(ports);\n\tconst content = edgeComposeFile({\n\t\tports,\n\t\tstaticConfig,\n\t\tlogging: options.logging,\n\t});\n\tawait mkdir(dirname(file), { recursive: true });\n\tif ((await readFile(file, 'utf-8').catch(() => undefined)) !== content) {\n\t\tawait writeFile(file, content);\n\t}\n\n\tconst ref = edgeRef(file, {\n\t\t...(options.host ? { host: options.host } : {}),\n\t\t...(options.output ? { output: options.output } : {}),\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tawait docker.ensureNetwork(ref, EDGE_NETWORK);\n\tawait docker.up(ref, [EDGE_SERVICE]);\n\treturn [file];\n}\n\n/** A file inside the edge's running container, or undefined where there is none. */\nexport async function readEdgeFile(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tpath: string,\n): Promise<string | undefined> {\n\tconst result = await docker.exec(edge, EDGE_SERVICE, ['cat', path]);\n\treturn result.code === 0 ? result.stdout : undefined;\n}\n\n/** A file written into the edge's running container, whole, readable by it alone. */\nexport async function writeEdgeSecret(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tpath: string,\n\tcontent: string,\n): Promise<void> {\n\tawait put(docker, edge, path, content, '600');\n}\n\n/**\n * The edge restarted — what it reads once and keeps, a key among them, read\n * again — and waited on until it is healthy. Its own restart policy brings\n * it back; `up` waits for it.\n */\nexport async function restartEdge(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n): Promise<void> {\n\tawait docker.exec(edge, EDGE_SERVICE, ['kill', '1']);\n\tawait docker.up(edge, [EDGE_SERVICE]);\n}\n\n/** A stack's routes, inside the edge's container. */\nexport function routesPath(project: string): string {\n\treturn `${EDGE_DYNAMIC_DIR}/${project}.yml`;\n}\n\n/**\n * A host this stack routes is already routed through the shared edge by\n * another project: two routers for one host, and which stack serves it — and\n * which gets its certificate — would be the edge's choice.\n */\nexport class EdgeHostClaimed extends GkmError {\n\tconstructor(\n\t\treadonly host: string,\n\t\treadonly owner: string,\n\t\treadonly project: string,\n\t\treadonly edge: string = EDGE_PROJECT,\n\t) {\n\t\tsuper(\n\t\t\t`${project} routes ${host}, and ${owner} already routes it through the ` +\n\t\t\t\t`shared edge (${edge}) on this server. A host is served by one ` +\n\t\t\t\t`stack only. Give ${project} another domain, or take ${owner} off the ` +\n\t\t\t\t`edge first: gkm compose --stage <stage> --down in its workspace (or ` +\n\t\t\t\t`remove ${routesPath(owner)} from the edge).`,\n\t\t);\n\t\tthis.name = 'EdgeHostClaimed';\n\t}\n}\n\n/**\n * Every other stack's claims on the edge, by project: each `dynamic/*.yml`\n * but this project's, read through the engine. None where the edge is not\n * running — nothing is routed through it.\n */\nexport async function edgeClaimsByProject(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tproject: string,\n): Promise<Map<string, EdgeClaim[]>> {\n\tconst claimed = new Map<string, EdgeClaim[]>();\n\tconst listed = await docker.exec(edge, EDGE_SERVICE, [\n\t\t'ls',\n\t\t'-1',\n\t\tEDGE_DYNAMIC_DIR,\n\t]);\n\tif (listed.code !== 0) return claimed;\n\tfor (const name of listed.stdout.split('\\n').map((line) => line.trim())) {\n\t\t// Only what the edge loads, and only a stack's: a file being written\n\t\t// is `.tmp` until its rename.\n\t\tif (!name.endsWith('.yml')) continue;\n\t\tconst owner = name.slice(0, -'.yml'.length);\n\t\tif (!owner || owner === project) continue;\n\t\tconst file = await readEdgeFile(docker, edge, routesPath(owner));\n\t\tif (file === undefined) continue;\n\t\tconst claims = readEdgeClaims(file);\n\t\tif (claims.length > 0) claimed.set(owner, claims);\n\t}\n\treturn claimed;\n}\n\n/**\n * Refuse a stack's routes when a host in them is routed through the edge by\n * another project — checked before a deploy changes anything, and again\n * before its routes are written. Its own file, from its last deploy, is\n * replaced, never a clash.\n */\nexport async function assertEdgeHostsFree(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tproject: string,\n\troutes: string,\n): Promise<void> {\n\tconst mine = readEdgeClaims(routes);\n\tif (mine.length === 0) return;\n\tconst others = await edgeClaimsByProject(docker, edge, project);\n\tfor (const [owner, theirs] of [...others].sort(([a], [b]) =>\n\t\ta.localeCompare(b),\n\t)) {\n\t\tfor (const claim of mine) {\n\t\t\tfor (const other of theirs) {\n\t\t\t\tconst host = claimsOverlap(claim, other);\n\t\t\t\tif (host !== undefined) {\n\t\t\t\t\tthrow new EdgeHostClaimed(host, owner, project, edge.project);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction certificatePaths(project: string): [string, string] {\n\treturn [\n\t\t`${EDGE_CERTS_DIR}/${project}.crt`,\n\t\t`${EDGE_CERTS_DIR}/${project}.key`,\n\t];\n}\n\n/**\n * Register a stack with the edge — refused, before anything is written, when\n * another project routes one of its hosts: its certificate first, where it has one,\n * so the routes that need it never load without it — then its routes, in one\n * rename the edge picks up whole. The certificate — the stage's own, or the\n * one gkm's local CA issued the local stage — is PEM read on this machine and\n * written through the engine. The paths written, inside the edge.\n */\nexport async function writeEdgeRoutes(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tproject: string,\n\troutes: string,\n\tcertificate?: { cert: string; key: string },\n): Promise<string[]> {\n\tawait assertEdgeHostsFree(docker, edge, project, routes);\n\tconst written: string[] = [];\n\tconst [crt, key] = certificatePaths(project);\n\tif (certificate) {\n\t\tawait put(docker, edge, crt, certificate.cert);\n\t\tawait put(docker, edge, key, certificate.key, '600');\n\t\twritten.push(crt, key);\n\t} else {\n\t\tawait remove(docker, edge, [crt, key]);\n\t}\n\tawait put(docker, edge, routesPath(project), routes);\n\twritten.push(routesPath(project));\n\treturn written;\n}\n\n/** What a stack's file holds for the moment between emptying and removal. */\nconst UNREGISTERED = '# Unregistered by gkm compose --down.\\n';\n\n/**\n * Unregister a stack: its routes, then its certificate. Whether there was\n * anything to remove — false, too, when the edge is not running.\n */\nexport async function removeEdgeRoutes(\n\tdocker: ComposeDocker,\n\tedge: StackRef,\n\tproject: string,\n): Promise<boolean> {\n\tconst file = routesPath(project);\n\tconst there = await docker.exec(edge, EDGE_SERVICE, ['test', '-f', file]);\n\tif (there.code !== 0) return false;\n\t// Emptied by a rename before it is removed: a watcher that misses the\n\t// removal has still seen the stack's routes go.\n\tawait put(docker, edge, file, UNREGISTERED);\n\tawait remove(docker, edge, [file, ...certificatePaths(project)]);\n\treturn true;\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 { 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 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\t// Forced: a certificate issued again changes no line of the config, and\n\t\t// an unforced reload of an unchanged config is skipped.\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\t'--force',\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","import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\n\n/** Write a file only when its content would change, so mtimes stay meaningful. */\nexport async 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 * 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 * The local edge's routes, rendered for the Caddy of this project's — the\n * proxy `gkm dev` and `gkm test` run behind unless the local stage's\n * `deploy.compose.proxy` is Traefik (see `localEdge.ts`).\n *\n * The routes are data (`routes.ts`, as `@geekmidas/edge/routes` models them\n * for every proxy); this is one adapter over them. One Caddy serves every\n * stage — the same way one Postgres holds `orders` and `orders_test` — so its\n * root config only imports, and each stage's routes are a file of their own.\n *\n * Pure, like `composeFor`: rendering the routes is one string.\n */\n\nimport { clientIpRule } from '@geekmidas/edge/proxy/caddy';\nimport {\n\ttype EdgeRoute,\n\ttype Upstream,\n\tupstreamAddress,\n} from '@geekmidas/edge/routes';\n\n/** Where the edge's container reads `.gkm/caddy-sites/` — routes and certificates. */\nexport const CADDY_SITES_IN_CONTAINER = '/etc/caddy/sites';\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: each stage's certificate is gkm's, beside its\n\t# routes, and the names are local.\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 ${CADDY_SITES_IN_CONTAINER}/*.caddy\n`;\n}\n\n/** An upstream as Caddy dials it from this project's network. */\nfunction dial(upstreams: readonly Upstream[]): string {\n\treturn upstreams\n\t\t.map((upstream) => `http://${upstreamAddress(upstream)}`)\n\t\t.join(' ');\n}\n\n/**\n * One stage's routes, 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(\n\troutes: readonly EdgeRoute[],\n\toptions: {\n\t\t/**\n\t\t * The stage's certificate and key, one PEM file, as the edge's\n\t\t * container reads it.\n\t\t */\n\t\tcertificate: string;\n\t\t/** The stack's token: see {@link clientIpRule}. */\n\t\tedgeToken?: string;\n\t},\n): string {\n\tif (routes.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 = routes.map((route) => {\n\t\tconst { host, prefix, handlers, wildcard, aliases, redirects } = route;\n\t\tconst proxy = `reverse_proxy ${dial(route.upstreams)} {${\n\t\t\tprefix\n\t\t\t\t? `\n\t\trewrite ${prefix}{uri}\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: `\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}\n\t}`;\n\n\t\t// Each redirect host, one block: the browser is sent to the\n\t\t// canonical host with its path and query, and nothing is proxied.\n\t\tconst redirectBlocks = (redirects?.hosts ?? [])\n\t\t\t.map(\n\t\t\t\t(from) => `\nhttps://${from} {\n\ttls ${options.certificate} ${options.certificate}\n\n\tredir ${redirects?.to}{uri} permanent\n}`,\n\t\t\t)\n\t\t\t.join('');\n\t\tconst names = [host, ...(aliases ?? [])]\n\t\t\t.map((name) => `https://${name}`)\n\t\t\t.join(', ');\n\n\t\treturn `\n${names} {\n\ttls ${options.certificate} ${options.certificate}\n\n${clientIpRule(options.edgeToken)}\n${(handlers ?? [])\n\t.map(\n\t\t(handler) => `\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@${handler.name} path ${handler.prefixes.map((p) => `${p}*`).join(' ')}\n\thandle @${handler.name} {\n\t\treverse_proxy ${dial(handler.upstreams)} {${\n\t\t\thandler.under\n\t\t\t\t? `\n\t\t\trewrite ${handler.under}{uri}`\n\t\t\t\t: ''\n\t\t}\n\t\t\theader_up Host {host}\n\t\t}\n\t}\n`,\n\t)\n\t.join('')}${wildcard ? tenantBlock(wildcard, proxy) : `\t${proxy}`}\n}${redirectBlocks}`;\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\twildcard: NonNullable<EdgeRoute['wildcard']>,\n\tproxy: string,\n): string {\n\tconst refused = wildcard.except.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 ${wildcard.except.map((label) => `${label}.${wildcard.domain}`).join(' ')}\n\thandle @protected {\n\t\trespond 404\n\t}\n`\n\t\t: '';\n\tconst check = wildcard.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 ${dial([wildcard.hosts.upstream])} {\n\t\t\turi ${wildcard.hosts.path}?domain={host}\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 gkm's local CA. \"gkm dev\" and \"gkm test\" point Node at\n# its root, so nothing has to be installed to use these URLs from code; a\n# browser needs the root trusted once (\"gkm trust\").\n`;\n","/**\n * The local edge, as reconcile drives it: the stage's routes (`routes.ts`)\n * handed to whichever proxy the local stage runs — `deploy.compose.proxy`,\n * resolved by `proxyFor` as `gkm compose` resolves it.\n *\n * Two adapters over one route plan:\n *\n * - **Caddy** — a container of this project's, on a port it was assigned.\n * Its routes are files under `.gkm/`, one per stage, and a running Caddy is\n * told about a change with `caddy reload`.\n * - **Traefik** — this machine's shared edge, the same one `gkm compose`\n * registers the local stage with: started where it is not running, and the\n * stage's routes and certificate written into the directory it watches\n * (`compose/edge.ts`), under the stage's compose project. Traefik picks a\n * changed file up on its own.\n *\n * Either way the certificate is gkm's local authority's, so a browser that\n * trusts it needs nothing new.\n */\n\nimport { readdir, rm } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { LocalCertificate } from '@geekmidas/edge/certificates/local';\nimport {\n\tEDGE_PROJECT,\n\tedgeCertificatePaths,\n\ttraefikDynamicFile,\n} from '@geekmidas/edge/proxy/traefik';\nimport type { EdgeRoute } from '@geekmidas/edge/routes';\nimport type { ComposeDocker } from '../compose/docker.js';\nimport {\n\tassertEdgePorts,\n\tedgeRef,\n\tensureEdge,\n\treadEdgeFile,\n\troutesPath,\n\twriteEdgeRoutes,\n} from '../compose/edge.js';\nimport { LOG_ROTATION } from '../compose/stack.js';\nimport { TEST_STAGE } from '../workspace/stages';\nimport {\n\tCADDY_SITES_IN_CONTAINER,\n\tcaddyfileRoot,\n\ttoCaddyfile,\n} from './caddyfile';\nimport { write } from './files';\nimport type { Docker } from './index';\nimport type { LocalEdge } from './plan';\n\n/**\n * The local edge's Caddy 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 * 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 one stage's certificate is kept: certificate and key in one PEM,\n * issued from gkm's local authority (`@geekmidas/edge/certificates/local`),\n * beside the stage's Caddy routes — so Caddy reads it through the mount it\n * already has, and a stage removed takes its certificate with it. The shared\n * Traefik edge is handed the same one.\n */\nexport const edgeCertificatePath = (stage: string) =>\n\t`.gkm/caddy-sites/${stage}.pem`;\n\n/**\n * The shared edge's compose file, as this machine hands it to compose — the\n * same document `gkm compose` writes beside a stack.\n */\nexport const EDGE_COMPOSE_PATH = `.gkm/${EDGE_PROJECT}.yml`;\n\n/** One proxy, driven through the steps every reconcile takes. */\nexport interface LocalEdgeAdapter {\n\t/**\n\t * The stage's routes as the proxy reads them: part of what \"converged\"\n\t * means, since a route can change without any container doing so.\n\t */\n\treadonly generated: Readonly<Record<string, string>>;\n\t/** Whether the running edge already serves exactly that. */\n\tserving(): Promise<boolean>;\n\t/** Before the project's containers start: what they read at startup. */\n\tprepare(): Promise<void>;\n\t/** Once they run: the edge told about the routes, and their certificate. */\n\tapply(certificate: LocalCertificate): Promise<void>;\n}\n\n/** The Caddy of this project's. */\nexport function caddyEdge(options: {\n\troot: string;\n\tstage: string;\n\t/** The project's local stage, whose routes are kept beside `test`'s. */\n\tlocalStage?: string;\n\troutes: readonly EdgeRoute[];\n\tedgeToken: string;\n\tdocker: Docker;\n\tcomposePath: string;\n}): LocalEdgeAdapter {\n\tconst { root, stage } = options;\n\tconst caddyfile = toCaddyfile(options.routes, {\n\t\tcertificate: `${CADDY_SITES_IN_CONTAINER}/${stage}.pem`,\n\t\t// What the apps are handed (`envFor`), so a service calling a sibling\n\t\t// through this edge keeps the client's address.\n\t\tedgeToken: options.edgeToken,\n\t});\n\treturn {\n\t\tgenerated: { caddyfile },\n\t\t// A container of this project's: its health is reconcile's own check.\n\t\tserving: async () => true,\n\t\t// Before the containers: Caddy reads these at startup, and mounting a\n\t\t// file that does not exist yet gets a directory instead.\n\t\tasync prepare() {\n\t\t\tawait write(join(root, CADDYFILE_PATH), caddyfileRoot());\n\t\t\tawait write(join(root, caddySitesPath(stage)), caddyfile);\n\t\t\tawait pruneCaddySites(root, [stage, options.localStage, TEST_STAGE]);\n\t\t},\n\t\t// A running Caddy does not notice a changed import or a certificate\n\t\t// issued again, so what this reconcile just wrote is inert until it is\n\t\t// told. Failing is not fatal: the container may have only this second\n\t\t// come up, in which case it already read them.\n\t\tasync apply() {\n\t\t\tawait options.docker.reload(options.composePath, 'caddy').catch(() => {});\n\t\t},\n\t};\n}\n\n/** This machine's shared Traefik edge. */\nexport function traefikEdge(options: {\n\troot: string;\n\tedge: Extract<LocalEdge, { proxy: 'traefik' }>;\n\troutes: readonly EdgeRoute[];\n\tedgeToken: string;\n\tdocker: ComposeDocker;\n}): LocalEdgeAdapter {\n\tconst { docker } = options;\n\tconst { project, ports } = options.edge;\n\t// What `gkm compose` registers for a stack on the local stage: its routes,\n\t// with the certificate gkm's local authority issued it.\n\tconst routes = traefikDynamicFile(options.routes, {\n\t\tproject,\n\t\ttls: { kind: 'files', ...edgeCertificatePaths(project) },\n\t\tedgeToken: options.edgeToken,\n\t});\n\tconst file = join(options.root, EDGE_COMPOSE_PATH);\n\tconst edge = edgeRef(file);\n\treturn {\n\t\tgenerated: { traefik: routes },\n\t\t// The edge is shared, so what it serves is only known by asking it: one\n\t\t// restarted, or this stage's file replaced by `gkm compose` for the\n\t\t// same stage, is registered again.\n\t\tserving: async () =>\n\t\t\t(await readEdgeFile(docker, edge, routesPath(project))) === routes,\n\t\t// Nothing of this project's reads the routes: the edge is not one of\n\t\t// its containers.\n\t\tprepare: async () => {},\n\t\tasync apply(certificate) {\n\t\t\t// Nothing but the shared edge may hold its ports. The stage's own\n\t\t\t// Caddy from `gkm compose` — before the stage was switched — is the\n\t\t\t// one holder moved rather than refused, as `gkm compose` moves it.\n\t\t\tconst own = await assertEdgePorts(docker, {\n\t\t\t\tproject,\n\t\t\t\tproxy: 'traefik',\n\t\t\t\tports,\n\t\t\t\tengine: {},\n\t\t\t});\n\t\t\tif (own) await docker.remove({}, project, 'caddy');\n\t\t\tawait ensureEdge(docker, {\n\t\t\t\tfile,\n\t\t\t\tports,\n\t\t\t\tlogging: {\n\t\t\t\t\tdriver: LOG_ROTATION.driver,\n\t\t\t\t\toptions: { ...LOG_ROTATION.options },\n\t\t\t\t},\n\t\t\t});\n\t\t\tawait writeEdgeRoutes(docker, edge, project, routes, {\n\t\t\t\tcert: certificate.cert,\n\t\t\t\tkey: certificate.key,\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * Remove the Caddy 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(\n\t\tstages.flatMap((stage) =>\n\t\t\tstage ? [`${stage}.caddy`, `${stage}.pem`] : [],\n\t\t),\n\t);\n\n\tfor (const file of await readdir(dir)) {\n\t\t// A stage's certificate goes with its routes.\n\t\tif (/\\.(caddy|pem)$/.test(file) && !keep.has(file)) {\n\t\t\tawait rm(join(dir, file));\n\t\t}\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 { join } from 'node:path';\nimport {\n\tensureLocalAuthority,\n\tensureLocalCertificate,\n\ttype LocalAuthorityPaths,\n\tlocalAuthorityPaths,\n\tlocalCertificateNames,\n} from '@geekmidas/edge/certificates/local';\nimport { routeHosts } from '@geekmidas/edge/routes';\nimport { type ConstructManifest, provisionOrder } from '@geekmidas/manifest';\nimport { type ComposeDocker, dockerCompose } from '../compose/docker.js';\nimport { gkmHome } from '../home';\nimport { scopeTelemetryEnv } from '../telemetry/edges';\nimport type { CacheBackend, EventsBackend } from '../types';\nimport { TEST_STAGE } from '../workspace/stages';\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 { edgeToken, envFor, LOCAL_CA_KEY, localEdgePort } from './env';\nimport type { LocalFake } from './fakes';\nimport { write } from './files';\nimport { lanAddress } from './lan';\nimport type { LocalCredentials, Login } from './localCredentials';\nimport { caddyEdge, edgeCertificatePath, traefikEdge } from './localEdge';\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 { localRoutes } from './routes';\nimport { loadState, planHash, saveState } from './state';\n\nexport type { ComposeFile } from './compose';\nexport type { LocalEdge, 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 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 * 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 * 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 * gkm's local certificate authority, which the edge's certificate is\n\t * issued from and every process is pointed at. The CLI's home's when not\n\t * given.\n\t */\n\tauthority?: LocalAuthorityPaths;\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/**\n\t * The local edge that fronts surfaces, sites and file servers — the local\n\t * stage's proxy (`localEdgeFor`) — or `false` for none. A Caddy of this\n\t * project's when not given.\n\t */\n\tedge?: PlanOptions['edge'];\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 domain mail is sent from locally — see `EnvOptions.mailDomain`. */\n\tmailDomain?: 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\t/**\n\t * Docker as `gkm compose` drives it, for the shared Traefik edge: started,\n\t * and the stage's routes written into it. Injected for tests.\n\t */\n\tedgeDocker?: ComposeDocker;\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\t//\n\t// One route plan, whichever proxy serves it: a Caddy of this project's\n\t// reaches MinIO on its network, and the shared Traefik edge — on none of\n\t// this project's — on the port MinIO publishes on the host.\n\tconst edgePort = localEdgePort(plan, ports);\n\tconst minioPort = ports[primaryPortKey('minio')];\n\tconst routes = localRoutes(plan, project, {\n\t\t...(options.addresses ? { addresses: options.addresses } : {}),\n\t\t...(options.processorAddresses\n\t\t\t? { processorAddresses: options.processorAddresses }\n\t\t\t: {}),\n\t\t...(plan.edge?.proxy === 'traefik' && minioPort !== undefined\n\t\t\t? { objects: { onHost: true, port: minioPort } }\n\t\t\t: {}),\n\t\t...(edgePort !== undefined ? { port: edgePort } : {}),\n\t});\n\tconst edged = plan.edge !== undefined;\n\tconst authorityPaths = options.authority ?? localAuthorityPaths(gkmHome());\n\t// What the apps are handed (`envFor`), so a service calling a sibling\n\t// through the edge keeps the client's address.\n\tconst token = edgeToken(project, seed);\n\tconst edge =\n\t\tplan.edge?.proxy === 'traefik'\n\t\t\t? traefikEdge({\n\t\t\t\t\troot,\n\t\t\t\t\tedge: plan.edge,\n\t\t\t\t\troutes,\n\t\t\t\t\tedgeToken: token,\n\t\t\t\t\tdocker: options.edgeDocker ?? dockerCompose,\n\t\t\t\t})\n\t\t\t: caddyEdge({\n\t\t\t\t\troot,\n\t\t\t\t\tstage,\n\t\t\t\t\t...(options.localStage ? { localStage: options.localStage } : {}),\n\t\t\t\t\troutes,\n\t\t\t\t\tedgeToken: token,\n\t\t\t\t\tdocker,\n\t\t\t\t\tcomposePath,\n\t\t\t\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, { ...edge.generated, 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.mailDomain ? { mailDomain: options.mailDomain } : {}),\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// gkm's root, which the edge's certificate is issued from — made below,\n\t\t// before anything that reads the environment starts.\n\t\tif (edged) env[LOCAL_CA_KEY] = authorityPaths.certFile;\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\t// The edge's certificate, issued before anything starts: the root exists\n\t// from the first run, and one issued again — expiring, or a host it did\n\t// not name — is a change the running edge has to be told about.\n\tconst certificate = edged\n\t\t? await ensureLocalCertificate(\n\t\t\t\tawait ensureLocalAuthority(authorityPaths),\n\t\t\t\tlocalCertificateNames(project, routes.flatMap(routeHosts)),\n\t\t\t\tjoin(root, edgeCertificatePath(stage)),\n\t\t\t)\n\t\t: undefined;\n\n\tconst recorded = await loadState(root, stage);\n\tconst postgresPort = ports[primaryPortKey('postgres')];\n\tconst converged =\n\t\t!certificate?.issued &&\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// The shared edge is no container of this project's: whether it still\n\t\t// serves this stage's routes is asked of it.\n\t\t(!start || !edged || (await edge.serving())) &&\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: what the edge reads as it starts.\n\tif (edged) await edge.prepare();\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// The edge told about the routes and their certificate: a running Caddy\n\t// reloaded, or the shared edge started and the stage registered with it.\n\tif (start && certificate) await edge.apply(certificate);\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 * 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 { edgePorts } from '../compose/edge.js';\nimport { proxyFor } from '../compose/proxy.js';\nimport { composeProject } from '../compose/stack.js';\nimport { loadPortState, savePortState } from '../credentials/index.js';\nimport { deployIdentity } from '../deploy/identity.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 { type LocalEdge, 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/**\n * The edge in front of a stage's surfaces, sites and file servers under\n * `gkm dev` and `gkm test`: the local stage's proxy, as `proxyFor` decides it\n * for `gkm compose` — one edge on this machine for every stage reconcile\n * runs, `test` included. Behind Traefik, the stage registers with the shared\n * edge under its compose project, as `gkm compose --stage <stage>` does.\n */\nexport function localEdgeFor(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\tenv: NodeJS.ProcessEnv = process.env,\n): LocalEdge {\n\tif (proxyFor(workspace.deploy?.compose, workspace.stages.local) === 'caddy') {\n\t\treturn { proxy: 'caddy' };\n\t}\n\tconst { https, http } = edgePorts(env);\n\treturn {\n\t\tproxy: 'traefik',\n\t\tports: { https, http },\n\t\tproject: composeProject(deployIdentity(workspace, stage)),\n\t};\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\tedge: localEdgeFor(workspace, stage),\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<\n\tReconcileResult & {\n\t\tmanifest: ConstructManifest;\n\t\t/** Each worker's background files, which say which app runs its work. */\n\t\tbackground: Record<string, string[]>;\n\t}\n> {\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\tedge: localEdgeFor(workspace, options.stage),\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, background };\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\tdependentsOf,\n\tEDGE_TOKEN_KEY,\n\timageOriginsFor,\n\tisPublicDeclaration,\n\tprovidedKeyFor,\n\tprovisionOrder,\n\tpublicEnvFor,\n\tpublicStageKey,\n\tpublicValues,\n\treachesServerHalf,\n\tTELEMETRY_KEYS,\n} from '@geekmidas/manifest';\nimport {\n\tProcessorsHaveNoApp,\n\tprocessorUnits,\n\tWorkerHasNoApp,\n\tWorkerNameTaken,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { publicBuildValues } from '../compose/siteBuild.js';\nimport { composeBuildPaths } from '../docker/layout.js';\nimport { findBuildRoot } from '../docker/templates.js';\nimport { isStackKey } from '../secrets/stackKeys.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, LOCAL_CA_KEY, stageEnv } 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\tstage: 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(\n\t\tdeclaration,\n\t\tmanifest,\n\t\t(key) => env[key],\n\t\t{},\n\t\t{\n\t\t\tstage,\n\t\t},\n\t);\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: `gkm compose` hands\n * every process the public ones, which one app calls another on through the\n * edge; `gkm docker`'s apps profile, which runs no edge, the compose\n * network's.\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, what each construct it has an edge to provides, and — for a\n * surface — the identity of each client with an edge to it.\n *\n * The one rule for every command and stage: `gkm dev`, `gkm exec` and `gkm\n * test` hand an app these keys (through `processEnvKeys`), `gkm compose`\n * writes them to its env file, and `gkm docker`'s apps profile to its\n * service. A key missing here is missing everywhere, so an app that reads it\n * fails on its first local request rather than in production.\n *\n * What an edge `caller.dependsOn([target])` hands each side, `<C>` and `<T>`\n * being the caller's and the target's ids (`providedKeyFor`) — keep this list and\n * `apps/docs/guide/edges.md` in step with the code below:\n *\n * - `rest-api`: the caller gets `<T>_URL`. The target gets `<C>_URL` from a\n * site caller and `<C>_SCHEME` from a mobile app caller (`callerKeys`).\n * - `websocket-api`: the caller gets `<T>_URL`, and a server process also\n * `<T>_PUBLISHER_CONNECTION_STRING`. The target gets what a `rest-api`\n * does.\n * - `queue`, `topic`: the caller gets the target's `provides` and\n * `EVENT_PUBLISHER_CONNECTION_STRING`. The target gets nothing.\n * - `objects`: the target's `provides`, its file server's, and the S3 key\n * pair (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`). A site\n * or mobile app gets `<T>_SIGNED_ORIGIN` and nothing else on its plain\n * edge, and all of it, signed origin included, on `.server`\n * (`reachesServerHalf`).\n * - `inbox`: the target's `provides`, and the local relay token.\n * - anything else (a database, cache, secret, credential, external API…):\n * the target's `provides`. The target gets nothing.\n *\n * Beside the keys, a surface's `<T>_TRUSTED_ORIGINS` lists every caller's\n * origin (a mobile app's as its scheme) and `<T>_COOKIE_DOMAIN` the parent\n * they share — values of the surface's own keys, derived from the same\n * inbound edges (`surfaceEnv`).\n *\n * A site or mobile app is a bundle: it also gets the public-prefixed name of\n * each of those its bundler inlines (`publicEnvFor`: `VITE_API_URL`,\n * `EXPO_PUBLIC_API_URL`), and never a `Telemetry` node's keys.\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.\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 [id, 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 client = isPublicDeclaration(declaration);\n\t// A frontend's plain edge to a bucket is to where the bucket's links are\n\t// signed — one of its public values, below — and to nothing that writes\n\t// to it. `.server` asks for the rest.\n\tconst edges = dependenciesOf(declaration)\n\t\t.filter(\n\t\t\t(edge) =>\n\t\t\t\tmanifest[edge.target]?.kind !== 'objects' ||\n\t\t\t\treachesServerHalf(declaration, edge),\n\t\t)\n\t\t.map((edge) => edge.target);\n\taddEdgeKeys(manifest, edges, keys, client);\n\n\t// The other direction: who calls this surface, by the identity it links\n\t// and redirects back to (`APP_SCHEME`, `WEB_URL`).\n\tif (declaration.kind === 'rest-api' || declaration.kind === 'websocket-api') {\n\t\tfor (const key of callerKeys(manifest, id)) keys.add(key);\n\t}\n\n\tif (client) {\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\t// And each unprefixed, for its server half: `<T>_SIGNED_ORIGIN` on\n\t\t// either edge to a bucket, a file server's address.\n\t\tfor (const { key } of publicValues(declaration, manifest)) keys.add(key);\n\t\t// The origins its pages load files from, for `next/image` and the like\n\t\t// (`imageRemotePatterns`) — what its image build is given too.\n\t\tconst images = imageOriginsFor(declaration, manifest);\n\t\tif (images) keys.add(images.key);\n\t\t// And the stage it is built for (`NEXT_PUBLIC_STAGE`).\n\t\tkeys.add(publicStageKey(declaration));\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/**\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\n/**\n * What one process runs: an app's surface or site, and the workers and file\n * servers' processors whose work it carries.\n *\n * The same app is a different process on different commands — under `gkm\n * dev` an API's own process runs the crons of the workers it hosts, while a\n * stack runs each worker in a container of its own — so a command names what\n * its process runs, and the keys follow from that alone.\n */\nexport interface ProcessUnits {\n\t/** The app's name, `api` or `web`. */\n\tapp?: string;\n\t/** Worker ids, `Jobs`. */\n\tworkers?: readonly string[];\n\t/** File servers' ids whose processors it runs, `AssetsServer`. */\n\tprocessors?: readonly string[];\n}\n\n/**\n * The keys the declared constructs hand to some process — each scoped to the\n * processes with an edge to it. A stage key outside this set is the stage's\n * own: one set by hand, which nothing declares a reader of.\n */\nexport function constructKeys(manifest: ConstructManifest): Set<string> {\n\tconst keys = new Set<string>();\n\tconst add = (more: Iterable<string> | undefined) => {\n\t\tfor (const key of more ?? []) keys.add(key);\n\t};\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tadd(declaration.provides);\n\t\tadd(declaration.requires);\n\t\tif (declaration.kind === 'worker') add(workerEnvKeys(manifest, id));\n\t\tif (declaration.kind === 'file-server') {\n\t\t\tadd(processorEnvKeys(manifest, id));\n\t\t}\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\tdeclaration.kind === 'mobile-app'\n\t\t) {\n\t\t\tadd(appEnvKeys(manifest, appKey(id)));\n\t\t}\n\t}\n\treturn keys;\n}\n\n/**\n * The keys one process is handed — the one rule `gkm dev`, `gkm exec` and\n * `gkm compose` all apply, so an app gets the same keys whichever runs it:\n *\n * - **What its constructs reach**, by their edges: `appEnvKeys` for its app,\n * `workerEnvKeys` for each worker it runs, `processorEnvKeys` for each\n * file server's processors. A key a construct provides reaches only a\n * process with an edge to it, a stored one included — an auth server's\n * signing secret stays with the auth server.\n * - **The stack's edge token** (`EDGE_TOKEN_KEY`), which a call to a\n * sibling through the edge carries beside the client's address.\n * - **The local CA** (`NODE_EXTRA_CA_CERTS`), where the stage's certificates\n * come from gkm's: without it Node cannot verify a sibling's https address.\n * - **Every one of the stage's own keys** (`stageKeys` no construct\n * provides): a value set with `gkm secrets:set` that the code reads with\n * `get('X')`. Nothing declares which process reads it, so every process is\n * handed it — but for what gkm keeps for the stack itself (`isStackKey`):\n * a container's login, the backups key, the server's address.\n *\n * `undefined` for an app no declaration describes, which nothing narrows.\n */\nexport function processEnvKeys(\n\tmanifest: ConstructManifest,\n\tunits: ProcessUnits,\n\tstageKeys: Iterable<string>,\n): Set<string> | undefined {\n\tconst keys = new Set<string>();\n\tif (units.app !== undefined) {\n\t\tconst own = appEnvKeys(manifest, units.app);\n\t\tif (!own && !units.workers?.length && !units.processors?.length) {\n\t\t\treturn undefined;\n\t\t}\n\t\tfor (const key of own ?? []) keys.add(key);\n\t}\n\tfor (const id of units.workers ?? []) {\n\t\tfor (const key of workerEnvKeys(manifest, id) ?? []) keys.add(key);\n\t}\n\tfor (const id of units.processors ?? []) {\n\t\tfor (const key of processorEnvKeys(manifest, id) ?? []) keys.add(key);\n\t}\n\n\t// Every process may call a sibling through the edge, with the stack's\n\t// token beside the client's address.\n\tkeys.add(EDGE_TOKEN_KEY);\n\t// And trust the certificate it answers with, where gkm's CA issued it.\n\tkeys.add(LOCAL_CA_KEY);\n\n\tconst owned = constructKeys(manifest);\n\tfor (const key of stageKeys) {\n\t\tif (!owned.has(key) && !isStackKey(key)) keys.add(key);\n\t}\n\treturn keys;\n}\n\n/**\n * One process's environment, from the stage's stored keys and every value\n * it resolved (`stageEnv`'s merge): exactly {@link processEnvKeys}.\n */\nexport function processEnv(\n\tmanifest: ConstructManifest,\n\tunits: ProcessUnits,\n\tstored: Readonly<Record<string, string>>,\n\tresolved: Readonly<Record<string, string>>,\n): Record<string, string> {\n\tconst env = stageEnv(stored, resolved);\n\tconst keys = processEnvKeys(manifest, units, Object.keys(stored));\n\tif (!keys) return env;\n\treturn Object.fromEntries(\n\t\tObject.entries(env).filter(([key]) => keys.has(key)),\n\t);\n}\n\n/**\n * What an app's own process runs locally: its surface or site, and the\n * workers and processors whose code it holds — the same choice `gkm build`\n * makes (`workerUnits`, `processorUnits`).\n *\n * A worker no app can build is left out here: `gkm build` says so, and a\n * dev loop has nothing to run it in.\n */\nexport function appProcess(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tbackground: Readonly<Record<string, readonly string[]>>,\n\tappName: string,\n): ProcessUnits {\n\tconst hosted = <T extends { id: string; app: string }>(units: () => T[]) => {\n\t\ttry {\n\t\t\treturn units()\n\t\t\t\t.filter((unit) => unit.app === appName)\n\t\t\t\t.map((unit) => unit.id);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof WorkerHasNoApp ||\n\t\t\t\terror instanceof WorkerNameTaken ||\n\t\t\t\terror instanceof ProcessorsHaveNoApp\n\t\t\t) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\treturn {\n\t\tapp: appName,\n\t\tworkers: hosted(() => workerUnits(workspace, manifest, background)),\n\t\tprocessors: hosted(() => processorUnits(workspace, manifest)),\n\t};\n}\n\n/**\n * What a surface is told about the clients that call it: the identity it\n * links and redirects back to.\n *\n * An API that finishes an OAuth callback by sending a phone back into the app\n * builds `<scheme>://…`; one that mails a link to the site builds it on the\n * site's address. Both are the caller's own key, named by the caller's id —\n * `APP_SCHEME` for `MobileApp('App')`, `WEB_URL` for `StaticSite('Web')` — so\n * two apps calling one API arrive as `APP_SCHEME` and `ADMIN_APP_SCHEME`.\n *\n * Clients only. A surface or a worker that calls this one is something it\n * answers, never somewhere it sends a user, so nothing of theirs comes back\n * along the edge. Their origins still reach the surface, folded into its\n * `<ID>_TRUSTED_ORIGINS`.\n */\nexport function callerKeys(\n\tmanifest: ConstructManifest,\n\tsurfaceId: string,\n): string[] {\n\tconst keys: string[] = [];\n\tfor (const caller of dependentsOf(manifest, surfaceId)) {\n\t\tconst declaration = manifest[caller];\n\t\tif (declaration?.kind === 'mobile-app') {\n\t\t\tkeys.push(providedKeyFor(caller, declaration.kind, 'scheme'));\n\t\t} else if (declaration?.kind === 'site') {\n\t\t\tkeys.push(providedKeyFor(caller, declaration.kind, 'url'));\n\t\t}\n\t}\n\treturn keys;\n}\n\n/**\n * What a caller gets for each construct it has an edge to — the left half of\n * the table on {@link appEnvKeys}.\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(providedKeyFor(bucket, 'objects', 'eventsConnectionString'));\n\t\t\t\tkeys.add(providedKeyFor(bucket, 'objects', '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(providedKeyFor(id, target.kind, '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(providedKeyFor(id, target.kind, 'url'));\n\t\t\tif (!client)\n\t\t\t\tkeys.add(providedKeyFor(id, target.kind, '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, plan.stage);\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","/**\n * Mail and object storage on a deployed stage: real ones, or — only when\n * someone asked — the dev services the local stage runs.\n *\n * Locally a declared `Email` is Mailpit and a declared bucket is MinIO, and\n * nobody has to configure either. Deployed, the same two containers would be\n * a stage that silently delivers no mail and keeps its files on one\n * container's disk. So a deployed stage on a server target takes both from\n * its secrets — the mail server's URL and sending address, and each bucket's\n * URL — and a stage missing any of them fails before anything is built,\n * provisioned or written, naming every key at once.\n *\n * A bucket's credentials are not checked: they are optional, and come from\n * either of two places. The bucket's URL may carry a key of its own\n * (`s3://KEY:SECRET@uploads`), which wins; otherwise the S3 client's default\n * chain applies — the stage's shared `AWS_ACCESS_KEY_ID`/\n * `AWS_SECRET_ACCESS_KEY` when it set them, or a role.\n *\n * `--allow-dev-services` is the way out for a stage that is not production —\n * a preview, a demo: every construct the stage does not account for gets the\n * dev service the local stage runs for it — a bucket MinIO, mail Mailpit —\n * and the target derives the keys from it. What the stage does account for\n * still wins: a key set in its secrets, or a provider (`deploy.objects`)\n * that backs the kind. Every run that uses one says so, loudly.\n *\n * Pure: what each target runs is decided here from declarations and the\n * stage's values, and the targets do the running.\n */\n\nimport {\n\ttype ConstructManifest,\n\tprovidedKeyFor,\n\tpublicEnvFor,\n\tsenderAddress,\n} from '@geekmidas/manifest';\nimport { SERVER_IPV4_KEY, SERVER_IPV6_KEY } from '../compose/dnsConfig.js';\nimport { GkmError } from '../errors';\nimport { appEnvKeys, workerEnvKeys } from '../reconcile/apps.js';\nimport { appKey } from '../workspace/derive.js';\nimport { fileServerLabel } from '../workspace/fileServerLabel.js';\n\n/**\n * The dev services a deployed stage can run — one per kind that has one on\n * every server target: a bucket's MinIO and mail's Mailpit. A cache or a\n * database is not here because a server stage runs its own anyway.\n */\nexport const DEV_SERVICES = ['minio', 'mailpit'] as const;\n\nexport type DevService = (typeof DEV_SERVICES)[number];\n\n/**\n * The S3 client's shared key pair. Optional: a bucket whose URL carries its own\n * key (`s3://KEY:SECRET@bucket`) signs with that, and one without signs with\n * this pair when the stage set it, or with whatever else the SDK's default\n * chain finds — a role.\n */\nexport const STORAGE_KEY_PAIR = [\n\t'AWS_ACCESS_KEY_ID',\n\t'AWS_SECRET_ACCESS_KEY',\n] as const;\n\n/** Dev services asked of a target that runs no containers. */\nexport class DevServicesNeedServerTarget extends GkmError {\n\tconstructor(readonly target: string) {\n\t\tsuper(\n\t\t\t`--allow-dev-services applies to server targets only, and '${target}' ` +\n\t\t\t\t`deploys to AWS, where a bucket is S3 and mail is the stage's own. ` +\n\t\t\t\t'Drop --allow-dev-services.',\n\t\t);\n\t\tthis.name = 'DevServicesNeedServerTarget';\n\t}\n}\n\n/**\n * `--allow-dev-services` given a value — the list it used to take. It is a\n * switch now: every construct the stage does not account for gets its dev\n * service.\n */\nexport class AllowDevServicesTakesNoValue extends GkmError {\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`--allow-dev-services takes no value (it was given '${value}'). It runs ` +\n\t\t\t\t'the dev service for every bucket and mail the stage does not account ' +\n\t\t\t\t'for — no key in its secrets, no provider in deploy.<kind>.<stage> — so ' +\n\t\t\t\t'there is nothing to list. Pass --allow-dev-services on its own.',\n\t\t);\n\t\tthis.name = 'AllowDevServicesTakesNoValue';\n\t}\n}\n\n/**\n * Refuses `--allow-dev-services <value>` and `--allow-dev-services=<value>` on\n * a command line, with the reason, before the parser calls the value an\n * excess argument. `gkm deploy` and `gkm compose` take no positional\n * argument, so whatever follows the flag and is not a flag was meant for it.\n *\n * @throws {AllowDevServicesTakesNoValue}\n */\nexport function assertDevServicesFlag(argv: readonly string[]): void {\n\tfor (let i = 0; i < argv.length; i++) {\n\t\tconst arg = argv[i]!;\n\t\tif (arg.startsWith('--allow-dev-services=')) {\n\t\t\tthrow new AllowDevServicesTakesNoValue(arg.slice(arg.indexOf('=') + 1));\n\t\t}\n\t\tconst next = argv[i + 1];\n\t\tif (arg === '--allow-dev-services' && next && !next.startsWith('-')) {\n\t\t\tthrow new AllowDevServicesTakesNoValue(next);\n\t\t}\n\t}\n}\n\n/** One key a deployed stage needs and its secrets do not hold. */\nexport interface MissingServiceKey {\n\tkey: string;\n\t/** The construct that reads it. */\n\tid: string;\n\t/** What it is, for the line that names it. */\n\twhat: string;\n\t/** A line after `what`, for what else there is to know about it. */\n\tnote?: string;\n\t/** A placeholder value to show in the `gkm secrets:set` line. */\n\texample: string;\n\t/** The dev service that would stand in for it, unless the stage accounts for it. */\n\tservice?: DevService;\n\t/** The apps that read it, where known. */\n\tapps?: readonly string[];\n\t/** What creates it, where a provider backs it on the stage. */\n\thint?: string;\n}\n\n/**\n * A deployed stage with mail or object storage that its secrets do not\n * configure — every missing key, across every app, at once.\n */\nexport class ExternalServicesNotConfigured extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly missing: readonly MissingServiceKey[],\n\t) {\n\t\tconst standIns = missing.some((m) => m.service !== undefined);\n\t\tconst lines = missing.map((m) => {\n\t\t\tconst by = m.apps?.length ? `, read by ${m.apps.join(', ')}` : '';\n\t\t\treturn (\n\t\t\t\t` gkm secrets:set ${m.key} '${m.example}' --stage ${stage}\\n` +\n\t\t\t\t` ${m.what}${by}` +\n\t\t\t\t(m.note ? `\\n ${m.note}` : '') +\n\t\t\t\t(m.hint ? `\\n ${m.hint}` : '')\n\t\t\t);\n\t\t});\n\t\tsuper(\n\t\t\t`The stage '${stage}' is deployed, and a deployed stage's mail and ` +\n\t\t\t\t`object storage are real services: gkm runs no Mailpit or MinIO for ` +\n\t\t\t\t`it. Set ${missing.length === 1 ? 'this key' : `these ${missing.length} keys`} in the stage's secrets:\\n\\n` +\n\t\t\t\t`${lines.join('\\n')}\\n\\n` +\n\t\t\t\t(standIns\n\t\t\t\t\t? `For a stage that is not production — a preview, a demo — the ` +\n\t\t\t\t\t\t`dev services can run instead, with --allow-dev-services. ` +\n\t\t\t\t\t\t`Mailpit delivers no mail, and MinIO keeps every object on one ` +\n\t\t\t\t\t\t`container's disk.\\n\\n`\n\t\t\t\t\t: '') +\n\t\t\t\t`Or run: gkm secrets:add --stage ${stage}`,\n\t\t);\n\t\tthis.name = 'ExternalServicesNotConfigured';\n\t}\n}\n\n/** A declaration that is mail or object storage. */\nexport interface ServiceDeclaration {\n\tid: string;\n\tkind: 'email' | 'objects' | 'file-server';\n\t/** A file server's bucket. */\n\tof?: string;\n\t/** Mail's local part — its declaration's `from`. */\n\tfrom?: string;\n\t/** The apps that read it, where known. */\n\tapps?: readonly string[];\n}\n\n/** The kinds a deployed stage takes from its secrets, or a dev service. */\nconst SERVICE_KINDS: Readonly<Record<string, ServiceDeclaration['kind']>> = {\n\temail: 'email',\n\tobjects: 'objects',\n\t'file-server': 'file-server',\n};\n\nexport interface StageServiceDeclarationsInput {\n\tmanifest: ConstructManifest;\n}\n\n/**\n * Every mail and storage construct a manifest declares, each with the apps\n * and workers that read it — a process's environment, a site's build args. A\n * file server's reader reads its bucket too.\n *\n * The one list a deploy's readiness check refuses a stage by, every server\n * target decides its dev services from, and `gkm secrets:add` offers — so\n * none of them can disagree.\n */\nexport function stageServiceDeclarations(\n\tinput: StageServiceDeclarationsInput,\n): ServiceDeclaration[] {\n\tconst { manifest } = input;\n\n\t// The construct each key belongs to.\n\tconst owners = new Map<string, string>();\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (!SERVICE_KINDS[declaration.kind]) continue;\n\t\towners.set(\n\t\t\tprovidedKeyFor(\n\t\t\t\tid,\n\t\t\t\tdeclaration.kind,\n\t\t\t\tdeclaration.kind === 'objects' ? 'connectionString' : 'url',\n\t\t\t),\n\t\t\tid,\n\t\t);\n\t\tif (declaration.kind === 'email')\n\t\t\towners.set(providedKeyFor(id, declaration.kind, 'from'), id);\n\t\t// Derived from the connection: a site that holds only where the\n\t\t// bucket signs its links still needs the bucket configured.\n\t\tif (declaration.kind === 'objects')\n\t\t\towners.set(providedKeyFor(id, declaration.kind, 'signedOrigin'), id);\n\t}\n\n\t// Who reads which construct.\n\tconst readers = new Map<string, Set<string>>();\n\tconst read = (process: string, keys: Iterable<string>) => {\n\t\tfor (const key of keys) {\n\t\t\tconst id = owners.get(key);\n\t\t\tif (!id) continue;\n\t\t\tconst declaration = manifest[id];\n\t\t\tconst of =\n\t\t\t\tdeclaration?.kind === 'file-server' ? declaration.of : undefined;\n\t\t\tfor (const owner of of ? [id, of] : [id]) {\n\t\t\t\tconst set = readers.get(owner) ?? new Set<string>();\n\t\t\t\tset.add(process);\n\t\t\t\treaders.set(owner, set);\n\t\t\t}\n\t\t}\n\t};\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tconst name = appKey(id);\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\tdeclaration.kind === 'mobile-app'\n\t\t) {\n\t\t\tread(name, appEnvKeys(manifest, name) ?? []);\n\t\t}\n\t\t// A site's build args, by the keys they rename.\n\t\tif (declaration.kind === 'site') {\n\t\t\tread(name, Object.values(publicEnvFor(declaration, manifest)));\n\t\t}\n\t\tif (declaration.kind === 'worker') {\n\t\t\tread(name, workerEnvKeys(manifest, id) ?? []);\n\t\t}\n\t}\n\n\treturn Object.entries(manifest).flatMap(\n\t\t([id, declaration]): ServiceDeclaration[] => {\n\t\t\tconst kind = SERVICE_KINDS[declaration.kind];\n\t\t\tif (!kind) return [];\n\t\t\tconst apps = [...(readers.get(id) ?? [])].sort();\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tid,\n\t\t\t\t\tkind,\n\t\t\t\t\t...(declaration.kind === 'file-server' && declaration.of\n\t\t\t\t\t\t? { of: declaration.of }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(declaration.kind === 'email' && declaration.from\n\t\t\t\t\t\t? { from: declaration.from }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(apps.length ? { apps } : {}),\n\t\t\t\t},\n\t\t\t];\n\t\t},\n\t);\n}\n\nexport interface ExternalServicesInput {\n\tstage: string;\n\t/** Every mail and storage construct something on the stage reads. */\n\tdeclarations: readonly ServiceDeclaration[];\n\t/** The stage's values by key — what `gkm secrets:set` stored. */\n\tsupplied: Readonly<Record<string, string>>;\n\t/**\n\t * `--allow-dev-services`: every construct the stage does not account for\n\t * gets its dev service.\n\t */\n\tallow: boolean;\n\t/** The stage's base domain, for the examples. */\n\tdomain?: string;\n\t/**\n\t * What the stage's providers say, by kind: a kind one backs is accounted\n\t * for, so no dev service stands in for it, and a missing key of it names\n\t * what creates it.\n\t */\n\tproviders?: StageProviderNotes;\n}\n\n/** The stage's providers, as a deploy's checks read them. */\nexport interface StageProviderNotes {\n\tobjects?: StageProviderNote;\n\temail?: StageProviderNote;\n}\n\n/** What the stage's provider says of one kind. */\nexport interface StageProviderNote {\n\t/** A provider (or `false`) backs the kind: no dev service for it. */\n\taccounted: boolean;\n\t/** What creates a missing key of it. */\n\thint?: string;\n}\n\n/** Where a deployed stage's mail and storage come from. */\nexport interface ExternalServices {\n\t/** Keys the stage needs and has not set. Empty when it can deploy. */\n\tmissing: MissingServiceKey[];\n\t/** The buckets the target runs MinIO for. */\n\tminio: string[];\n\t/** The mail constructs the target runs Mailpit for. */\n\tmailpit: string[];\n}\n\n/** One dev service a run uses, and for which constructs. */\nexport interface DevServiceUse {\n\tservice: DevService;\n\tids: string[];\n}\n\n/** A third party's credentials a construct reads: an external API's, or a `Credential`. */\nexport interface CredentialDeclaration {\n\tid: string;\n\tkind: 'external-api' | 'credential';\n\t/** The apps that read it, where known. */\n\tapps?: readonly string[];\n}\n\n/** What a stage-supplied key belongs to. */\nexport type StageKeyKind =\n\t| 'bucket'\n\t| 'email'\n\t| 'file-server'\n\t| 'external-api'\n\t| 'credential'\n\t/** The server a compose stage's stack runs on: `GKM_SERVER_IPV4`. */\n\t| 'server';\n\n/**\n * One key only the stage's secrets can hold — nothing derives it — whether\n * or not it is set.\n */\nexport interface StageKey {\n\tkey: string;\n\t/** The construct that reads it. */\n\tid: string;\n\tkind: StageKeyKind;\n\t/** What it is, for the line that names it. */\n\twhat: string;\n\t/** A line after `what`, for what else there is to know about it. */\n\tnote?: string;\n\t/** A placeholder value to show in the `gkm secrets:set` line. */\n\texample: string;\n\t/** The dev service that would stand in for it, where one can. */\n\tservice?: DevService;\n\t/** What creates it, where a provider backs it on the stage. */\n\thint?: string;\n\t/** A file server's bucket. */\n\tof?: string;\n\t/** The apps that read it, where known. */\n\tapps?: readonly string[];\n}\n\nexport interface StageKeysInput {\n\t/** Whether the stage is the local one, which derives its mail and storage. */\n\tlocal: boolean;\n\t/** Every mail and storage construct something on the stage reads. */\n\tservices?: readonly ServiceDeclaration[];\n\t/** Every third party's credentials something on the stage reads. */\n\tcredentials?: readonly CredentialDeclaration[];\n\t/** The stage's base domain, for the examples. */\n\tdomain?: string;\n\t/** What the stage's providers say — see {@link StageProviderNotes}. */\n\tproviders?: StageProviderNotes;\n\t/**\n\t * The stage serves a domain from a server of its own — a compose stage —\n\t * so its secrets hold the server's address, `GKM_SERVER_IPV4`.\n\t */\n\tserver?: boolean;\n}\n\n/**\n * Every key a stage must be given rather than derive — the one list both a\n * deploy's checks and `gkm secrets:add` read, so what a deploy refuses and\n * what the builder offers cannot drift.\n *\n * - Deployed, mail is its URL and its sending address, a bucket its URL, and\n * a file server its public URL. Locally all of it is Mailpit and MinIO.\n * - On every stage, a third party's credentials: nobody but the third party\n * can issue them.\n *\n * Never a derived value: a database URL, a generated secret, the seed.\n */\nexport function requiredStageKeys(input: StageKeysInput): StageKey[] {\n\tconst domain = input.domain ?? 'example.com';\n\tconst keys: StageKey[] = [];\n\tconst add = (entry: StageKey) => {\n\t\tif (!keys.some((k) => k.key === entry.key)) keys.push(entry);\n\t};\n\tconst byId = <T extends { id: string }>(list: readonly T[] | undefined) =>\n\t\t[...(list ?? [])].sort((a, b) => a.id.localeCompare(b.id));\n\tconst apps = (d: { apps?: readonly string[] }) =>\n\t\td.apps?.length ? { apps: [...d.apps].sort() } : {};\n\n\tif (!input.local) {\n\t\tconst services = byId(input.services);\n\t\t// A kind a provider backs on the stage has no dev service, and a key of\n\t\t// it names what creates it.\n\t\tconst backing = (\n\t\t\tnote: StageProviderNote | undefined,\n\t\t\tservice: DevService,\n\t\t) =>\n\t\t\tnote?.accounted ? (note.hint ? { hint: note.hint } : {}) : { service };\n\t\tconst storage = backing(input.providers?.objects, 'minio');\n\t\tconst mail = backing(input.providers?.email, 'mailpit');\n\t\tfor (const d of services.filter((d) => d.kind === 'email')) {\n\t\t\tadd({\n\t\t\t\tkey: providedKeyFor(d.id, 'email', 'url'),\n\t\t\t\tid: d.id,\n\t\t\t\tkind: 'email',\n\t\t\t\twhat: `where '${d.id}' sends mail — any SMTP server`,\n\t\t\t\texample: `smtp://user:password@smtp.${domain}:587`,\n\t\t\t\t...mail,\n\t\t\t\t...apps(d),\n\t\t\t});\n\t\t\tadd({\n\t\t\t\tkey: providedKeyFor(d.id, 'email', 'from'),\n\t\t\t\tid: d.id,\n\t\t\t\tkind: 'email',\n\t\t\t\twhat: `the address '${d.id}' sends from, on a domain the mail server has verified`,\n\t\t\t\texample: senderAddress(d, domain),\n\t\t\t\t...mail,\n\t\t\t\t...apps(d),\n\t\t\t});\n\t\t}\n\t\tfor (const d of services.filter((d) => d.kind === 'objects')) {\n\t\t\tadd({\n\t\t\t\tkey: providedKeyFor(d.id, 'objects', 'connectionString'),\n\t\t\t\tid: d.id,\n\t\t\t\tkind: 'bucket',\n\t\t\t\twhat: `the bucket '${d.id}' — S3, R2, or any S3-compatible store (add &endpoint=… for one that is not S3)`,\n\t\t\t\tnote: `credentials are optional: a key for this bucket alone in the URL (s3://KEY:SECRET@${appKey(d.id)}?…) wins; without one, the shared AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY or a role signs`,\n\t\t\t\texample: `s3://${appKey(d.id)}?region=eu-west-1`,\n\t\t\t\t...storage,\n\t\t\t\t...apps(d),\n\t\t\t});\n\t\t}\n\t\tfor (const d of services.filter((d) => d.kind === 'file-server')) {\n\t\t\tadd({\n\t\t\t\tkey: providedKeyFor(d.id, 'file-server', 'url'),\n\t\t\t\tid: d.id,\n\t\t\t\tkind: 'file-server',\n\t\t\t\twhat: `the public address '${d.id}' serves its bucket on — a CDN or the bucket's own domain`,\n\t\t\t\texample: `https://${fileServerLabel(d.id)}.${domain}`,\n\t\t\t\t...storage,\n\t\t\t\t...(d.of ? { of: d.of } : {}),\n\t\t\t\t...apps(d),\n\t\t\t});\n\t\t}\n\t}\n\n\tif (!input.local && input.server) {\n\t\tadd({\n\t\t\tkey: SERVER_IPV4_KEY,\n\t\t\tid: 'server',\n\t\t\tkind: 'server',\n\t\t\twhat: \"the public IPv4 address of the server the stage's stack runs on — its hosts' DNS records point at it, and every deploy checks they do\",\n\t\t\tnote: `${SERVER_IPV6_KEY} adds its IPv6 address (AAAA records); neither is ever handed to an app`,\n\t\t\texample: '203.0.113.10',\n\t\t});\n\t}\n\n\tfor (const d of byId(input.credentials)) {\n\t\tadd({\n\t\t\tkey: providedKeyFor(d.id, d.kind, 'credentials'),\n\t\t\tid: d.id,\n\t\t\tkind: d.kind,\n\t\t\twhat:\n\t\t\t\td.kind === 'external-api'\n\t\t\t\t\t? `the credentials '${d.id}' was issued for this stage, as its schema describes them`\n\t\t\t\t\t: `the credential '${d.id}', as its schema describes it`,\n\t\t\texample: '{\"apiKey\":\"…\"}',\n\t\t\t...apps(d),\n\t\t});\n\t}\n\n\treturn keys;\n}\n\n/**\n * Whether only the stage's secrets can supply `key` to a construct of `kind`\n * — what nothing on the stage derives.\n *\n * A third party's credentials, always. Deployed, also each generated secret\n * and keyring: the stage generated each one once, and every run reads the\n * same value back.\n */\nexport function suppliedOnly(\n\tkind: string,\n\tid: string,\n\tkey: string,\n\tlocal: boolean,\n): boolean {\n\tif (kind === 'credential') return true;\n\tif (kind === 'external-api')\n\t\treturn key === providedKeyFor(id, 'external-api', 'credentials');\n\tif (local) return false;\n\treturn kind === 'secret' || kind === 'encryption';\n}\n\n/**\n * Where a deployed stage's mail and storage come from, and what it lacks.\n *\n * - Mail is external once its URL is set, and then needs its sending\n * address too. Unset, it is Mailpit where allowed — the address derived\n * unless set — and missing otherwise.\n * - A bucket is external once its URL is set; its credentials, in the URL or\n * the shared pair, are optional. Unset, it is MinIO where allowed, and\n * missing otherwise.\n * - A file server's URL is derived where its bucket is MinIO, unless set;\n * over an external bucket the stage must set it.\n *\n * The keys themselves are {@link requiredStageKeys}'s.\n */\nexport function externalServices(\n\tinput: ExternalServicesInput,\n): ExternalServices {\n\tconst { supplied, allow } = input;\n\tconst has = (key: string) => supplied[key] !== undefined;\n\n\tconst required = requiredStageKeys({\n\t\tlocal: false,\n\t\tservices: input.declarations,\n\t\t...(input.domain ? { domain: input.domain } : {}),\n\t\t...(input.providers ? { providers: input.providers } : {}),\n\t});\n\n\t// A dev service stands in for each construct the stage does not account\n\t// for: no key in its secrets, and no provider backing its kind.\n\tconst standIn = (k: StageKey) =>\n\t\tallow && k.service !== undefined && !has(k.key);\n\tconst mailpit = required\n\t\t.filter(\n\t\t\t(k) =>\n\t\t\t\tk.kind === 'email' && k.key === providedKeyFor(k.id, 'email', 'url'),\n\t\t)\n\t\t.filter(standIn)\n\t\t.map((k) => k.id);\n\tconst minio = required\n\t\t.filter((k) => k.kind === 'bucket')\n\t\t.filter(standIn)\n\t\t.map((k) => k.id);\n\n\tconst covered = (k: StageKey) =>\n\t\t(k.kind === 'email' && mailpit.includes(k.id)) ||\n\t\t(k.kind === 'bucket' && minio.includes(k.id)) ||\n\t\t(k.kind === 'file-server' && k.of !== undefined && minio.includes(k.of));\n\n\tconst missing = required\n\t\t.filter((k) => !has(k.key) && !covered(k))\n\t\t.map(\n\t\t\t({\n\t\t\t\tkey,\n\t\t\t\tid,\n\t\t\t\twhat,\n\t\t\t\tnote,\n\t\t\t\texample,\n\t\t\t\tservice,\n\t\t\t\tapps,\n\t\t\t\thint,\n\t\t\t}): MissingServiceKey => ({\n\t\t\t\tkey,\n\t\t\t\tid,\n\t\t\t\twhat,\n\t\t\t\t...(note ? { note } : {}),\n\t\t\t\texample,\n\t\t\t\t...(service ? { service } : {}),\n\t\t\t\t...(apps ? { apps } : {}),\n\t\t\t\t...(hint ? { hint } : {}),\n\t\t\t}),\n\t\t);\n\n\treturn { missing, minio, mailpit };\n}\n\n/** The dev services a run uses, one entry per service it runs. */\nexport function devServicesUsed(services: ExternalServices): DevServiceUse[] {\n\tconst used: DevServiceUse[] = [];\n\tif (services.mailpit.length > 0) {\n\t\tused.push({ service: 'mailpit', ids: services.mailpit });\n\t}\n\tif (services.minio.length > 0) {\n\t\tused.push({ service: 'minio', ids: services.minio });\n\t}\n\treturn used;\n}\n\n/** The line a run prints for each dev service a deployed stage uses. */\nexport function devServiceWarning(stage: string, use: DevServiceUse): string {\n\tconst what =\n\t\tuse.service === 'mailpit'\n\t\t\t? `Mailpit is catching mail for ${use.ids.join(', ')}. It delivers NO mail: nobody receives a sign-in link, a receipt or a reset`\n\t\t\t: `MinIO is storing ${use.ids.join(', ')}. Every object is on one container's disk, with no replication and no backup`;\n\treturn (\n\t\t`⚠️ DEV SERVICE ON A DEPLOYED STAGE (${stage}): ${what}. It is not ` +\n\t\t`production-grade — set the stage's own keys in its secrets for that.`\n\t);\n}\n\n/**\n * Report each dev service a run uses: a loud line, and a `dev-service.used`\n * event a host can act on.\n */\nexport function reportDevServices(\n\tctx: {\n\t\tstage: string;\n\t\tlogger: { warn(message: string): void };\n\t\temit(event: {\n\t\t\ttype: 'dev-service.used';\n\t\t\tservice: DevService;\n\t\t\tstage: string;\n\t\t\tconstructs: string[];\n\t\t}): void;\n\t},\n\tuses: readonly DevServiceUse[],\n): void {\n\tfor (const use of uses) {\n\t\tctx.logger.warn(`\\n${devServiceWarning(ctx.stage, use)}`);\n\t\tctx.emit({\n\t\t\ttype: 'dev-service.used',\n\t\t\tservice: use.service,\n\t\t\tstage: ctx.stage,\n\t\t\tconstructs: use.ids,\n\t\t});\n\t}\n}\n","/**\n * An image reference, checked before it reaches `docker`.\n *\n * The parts come from the workspace — a registry in `gkm.config.ts`, an image\n * name from the project, a tag from `--tag` — and an argument array already\n * keeps them out of a shell. What it cannot do is stop `docker` reading a value\n * that starts with `-` as one of its own flags, so a ref is held to Docker's\n * own grammar (distribution/reference) and anything else is refused by name\n * before a build starts.\n */\n\nimport { GkmError } from '../errors';\n\nconst DOMAIN_COMPONENT = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])';\nconst DOMAIN = `${DOMAIN_COMPONENT}(?:\\\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;\nconst PATH_COMPONENT = '[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*';\nconst TAG = '[\\\\w][\\\\w.-]{0,127}';\nconst DIGEST =\n\t'[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}';\n\nconst REFERENCE = new RegExp(\n\t`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::${TAG})?(?:@${DIGEST})?$`,\n);\n\n/** Docker refuses a repository name longer than this. */\nconst MAX_NAME_LENGTH = 255;\n\n/** A value that is not an image reference was about to be built or pushed. */\nexport class ImageRefInvalid extends GkmError {\n\tconstructor(readonly ref: string) {\n\t\tsuper(\n\t\t\t`'${ref}' is not a valid image reference. An image is \\`[registry/]name[:tag]\\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`,\n\t\t);\n\t\tthis.name = 'ImageRefInvalid';\n\t}\n}\n\n/** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */\nexport function validateImageRef(ref: string): string {\n\tconst name = ref.split('@')[0]!.replace(/:[\\w][\\w.-]*$/, '');\n\tif (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) {\n\t\tthrow new ImageRefInvalid(ref);\n\t}\n\treturn ref;\n}\n","import type { Cron } from '@geekmidas/constructs/crons';\nimport type { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { Function } from '@geekmidas/constructs/functions';\n\nimport type { CronInfo, FunctionInfo, RouteInfo } from '../types';\n\nexport interface ProcessedEndpoint {\n\tfile: string;\n\texportName: string;\n\tendpoint: Endpoint<any, any, any, any, any, any>;\n\trouteInfo: RouteInfo;\n}\n\nexport interface ProcessedFunction {\n\tfile: string;\n\texportName: string;\n\tfn: Function<any, any, any, any, any>;\n}\n\nexport interface ProcessedCron {\n\tfile: string;\n\texportName: string;\n\tcron: Cron<any, any, any, any>;\n\tschedule?: string;\n}\n\nexport interface NormalizedTelescopeConfig {\n\tenabled: boolean;\n\t/** Path to user's telescope module (if provided) */\n\ttelescopePath?: string;\n\t/** Import pattern for telescope (e.g., '{ telescope }' or 'telescope') */\n\ttelescopeImportPattern?: string;\n\t/** UI path for telescope dashboard */\n\tpath: string;\n\tignore: string[];\n\trecordBody: boolean;\n\tmaxEntries: number;\n\twebsocket: boolean;\n}\n\n/**\n * Where `gkm dev` serves the database's read-only JSON API\n * (`@geekmidas/db/introspect`). Under `/__gkm` with the rest of what the dev\n * server adds, so it cannot collide with an application route.\n */\nexport const DEV_DATABASE_API_PATH = '/__gkm/db';\n\n/**\n * The database the dev server's JSON API reads, and where it is declared.\n *\n * The API needs a client, and a client comes from a construct — so the entry\n * imports the declaration discovery already found and resolves it there. One\n * declared database is one browsable database; a project with none gets no\n * API, which is the correct answer rather than a stub.\n */\nexport interface DevDatabaseApi {\n\tpath: string;\n\tdatabase: { specifier: string; exportName: string };\n}\n\nexport interface NormalizedHooksConfig {\n\t/** Path to server hooks module */\n\tserverHooksPath: string;\n}\n\nexport interface NormalizedProductionConfig {\n\tenabled: boolean;\n\tbundle: boolean;\n\tminify: boolean;\n\thealthCheck: string;\n\tgracefulShutdown: boolean;\n\texternal: string[];\n\tsubscribers: 'include' | 'exclude';\n\topenapi: boolean;\n}\n\nexport interface BuildContext {\n\t/**\n\t * The surface this server serves, if the app declared one.\n\t *\n\t * Carried so the generated entry can set up CORS from the graph instead of a\n\t * hand-written hook: the origins arrive as `<ID>_TRUSTED_ORIGINS`, resolved\n\t * from whatever declared an edge to this surface.\n\t */\n\tsurface?: {\n\t\tid: string;\n\t\ttrustedOriginsKey: string;\n\t\t/**\n\t\t * Where the surface is declared, so the entry can import it.\n\t\t *\n\t\t * The logger a surface was given is an *object*, and a generator can\n\t\t * print a specifier but not an object — which is why the logger used to\n\t\t * be named in config as a module path. Discovery already knows the path,\n\t\t * so the entry imports the surface and reads the logger off it, and\n\t\t * nothing is written down twice.\n\t\t */\n\t\tmodule?: { specifier: string; exportName: string };\n\t\tcors?: {\n\t\t\tmaxAge?: number;\n\t\t\tcredentials?: boolean;\n\t\t\tallowHeaders?: readonly string[];\n\t\t\texposeHeaders?: readonly string[];\n\t\t};\n\t};\n\n\ttelescope?: NormalizedTelescopeConfig;\n\t/** The dev server's database JSON API. Never set for `gkm build`. */\n\tdatabaseApi?: DevDatabaseApi;\n\thooks?: NormalizedHooksConfig;\n\t/** Production build configuration */\n\tproduction?: NormalizedProductionConfig;\n\t/**\n\t * When true, optional env vars get a `?` suffix in each construct's\n\t * environment array (e.g. `PORT?` instead of `PORT`).\n\t */\n\tmarkOptional?: boolean;\n\t/**\n\t * Storage drivers the generated entry points should register.\n\t *\n\t * The scheme in an injected URL picks the driver, so registering is the entry\n\t * point's job — see `generators/drivers.ts`.\n\t */\n\tstorageDrivers?: import('../generators/drivers.js').RuntimeDrivers;\n\t/**\n\t * The drivers one AWS handler registers, from what its own construct\n\t * reaches — so a Lambda that publishes nothing never bundles a broker.\n\t * Undefined, for a construct whose reach is unknown, means\n\t * `storageDrivers`: the app's whole set. Set only for `--provider aws`.\n\t */\n\thandlerDrivers?: (construct: {\n\t\towner?: string;\n\t\tconstructs?: readonly string[];\n\t}) => import('../generators/drivers.js').RuntimeDrivers | undefined;\n\t/**\n\t * The constructs glob, so the build can emit the manifest once the routes it\n\t * folds in are known.\n\t */\n\tconstructGlobs?: string | readonly string[];\n\t/**\n\t * The backends this build registered drivers for.\n\t *\n\t * Recorded in the emitted manifest so a deploy reads the same answer rather\n\t * than choosing its own — see `reconcile/emit.ts`.\n\t */\n\tcacheBackend?: import('../types.js').CacheBackend;\n\t/**\n\t * The events brokers this build registered drivers for — empty when the app\n\t * declares no topic or queue. What a generated file decides from when it\n\t * has broker-specific code to include, such as SNS push subscriptions.\n\t */\n\teventsBackends?: readonly import('../types.js').EventsBackend[];\n\t/**\n\t * `gkm dev` wrote `processors.ts` beside the app — this app holds file\n\t * server processors — so the dev server mounts them.\n\t */\n\tdevProcessors?: boolean;\n\temailBackend?: import('../types.js').EmailBackend;\n\t/**\n\t * Every construct that can own a runnable, by id — the surfaces and the\n\t * workers — mapped to the module that exports it.\n\t *\n\t * What lets a generated cron import the worker that runs it rather than a\n\t * logger path from config.\n\t */\n\towners?: Record<string, { specifier: string; exportName: string }>;\n\t/**\n\t * What the production entry starts OpenTelemetry with, when\n\t * `OTEL_EXPORTER_OTLP_ENDPOINT` asks for it — see `generators/telemetry.ts`.\n\t */\n\ttelemetry?: import('../generators/telemetry.js').TelemetryContext;\n}\n\nexport interface ProviderBuildResult {\n\troutes: RouteInfo[];\n\tfunctions: FunctionInfo[];\n\tcrons: CronInfo[];\n}\n","import { resolve } from 'node:path';\nimport {\n\ttype ConstructManifest,\n\tcanonicalId,\n\tdependenciesOf,\n\tprovidedKeyFor,\n} from '@geekmidas/manifest';\nimport {\n\tcacheBackendsIn,\n\tdriversFor,\n\thandlerEventsBackends,\n\topensKmsKeys,\n\tpublishesToApiGateway,\n\ttype RuntimeDrivers,\n\treadsObjects,\n} from '../generators/drivers.js';\nimport { type ConstructSource, consumedBy } from '../reconcile/discover.js';\nimport type { CacheBackend, EventsBackend } from '../types.js';\nimport { appKey } from '../workspace/derive.js';\nimport { type BuildContext, DEV_DATABASE_API_PATH } from './types';\n\n/**\n * What a generated entry imports its runtime from, read off the discovered\n * constructs: the surface it serves, every construct a runnable can be built\n * from, and the database the dev server's JSON API reads.\n *\n * `gkm build` and `gkm dev` both write entries that import the surface for its\n * logger and environment parser, so both ask here. A dev server that skipped it\n * had nothing to import them from.\n */\nexport function ownersContext(options: {\n\tdeclared: ConstructManifest;\n\tsources: Record<string, ConstructSource>;\n\tworkspaceRoot: string;\n\t/** The directory being built — the app a surface's `path` names. */\n\tappRoot: string;\n\t/**\n\t * The workspace app being built, `webhooks` — which of the surfaces in\n\t * that directory it is, when more than one names it.\n\t */\n\tapp?: string;\n\t/** Whether to serve the database's JSON API — `gkm dev` only. */\n\tdatabaseApi?: boolean;\n}): Pick<BuildContext, 'owners' | 'surface' | 'databaseApi'> {\n\tconst { declared, sources, workspaceRoot, appRoot, app, databaseApi } =\n\t\toptions;\n\n\t// Which surface this server answers on, so the entry can derive its CORS.\n\t//\n\t// The app's own API, not the auth server it may also mount: an auth surface\n\t// serves itself, and the origins that may call *it* are a different list\n\t// from the ones that may call the API.\n\tconst surfaces = restApis(declared);\n\tconst served = servedSurface(declared, workspaceRoot, appRoot, app);\n\tconst primary =\n\t\tserved ?? surfaces.find((d) => !d.servesItself) ?? surfaces[0];\n\n\t// Which database the JSON API reads: the one the app declared. A reader is\n\t// not a candidate — it is the same data through a role that cannot write,\n\t// so browsing it would be the same rows under a second name.\n\tconst browsable = Object.entries(declared).find(\n\t\t([, d]) => d.kind === 'database',\n\t);\n\tconst browsableSource = browsable ? sources[browsable[0]] : undefined;\n\n\t// Every construct something can be built from, by id. A generated cron\n\t// imports the worker that owns it; a generated handler imports its surface.\n\tconst owners: Record<string, { specifier: string; exportName: string }> = {};\n\tfor (const [id, declaration] of Object.entries(declared)) {\n\t\tif (declaration.kind !== 'rest-api' && declaration.kind !== 'worker')\n\t\t\tcontinue;\n\t\tconst source = sources[id];\n\t\tif (!source) continue;\n\t\towners[id] = { specifier: source.file, exportName: source.exportName };\n\t}\n\n\tconst primarySource = primary ? sources[primary.id] : undefined;\n\n\treturn {\n\t\towners,\n\t\t...(primary\n\t\t\t? {\n\t\t\t\t\tsurface: {\n\t\t\t\t\t\tid: primary.id,\n\t\t\t\t\t\ttrustedOriginsKey: providedKeyFor(\n\t\t\t\t\t\t\tprimary.id,\n\t\t\t\t\t\t\t'rest-api',\n\t\t\t\t\t\t\t'trustedOrigins',\n\t\t\t\t\t\t),\n\t\t\t\t\t\t...(primary.cors ? { cors: primary.cors } : {}),\n\t\t\t\t\t\t...(primarySource\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tmodule: {\n\t\t\t\t\t\t\t\t\t\tspecifier: primarySource.file,\n\t\t\t\t\t\t\t\t\t\texportName: primarySource.exportName,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(databaseApi && browsableSource\n\t\t\t? {\n\t\t\t\t\tdatabaseApi: {\n\t\t\t\t\t\tpath: DEV_DATABASE_API_PATH,\n\t\t\t\t\t\tdatabase: {\n\t\t\t\t\t\t\tspecifier: browsableSource.file,\n\t\t\t\t\t\t\texportName: browsableSource.exportName,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * The endpoints one surface serves.\n *\n * One glob finds every surface's endpoints, wherever their files live. A build\n * keeps the ones built from the surface it serves; one built from no surface at\n * all has nowhere else to go.\n */\nexport function servedBy<T extends { construct: { surface?: { id: string } } }>(\n\tendpoints: T[],\n\tsurface: BuildContext['surface'],\n): T[] {\n\tif (!surface) return endpoints;\n\n\treturn endpoints.filter(\n\t\t({ construct }) =>\n\t\t\t!construct.surface || construct.surface.id === surface.id,\n\t);\n}\n\ntype RestApiDeclaration = Extract<\n\tConstructManifest[string],\n\t{ kind: 'rest-api' }\n>;\n\nfunction restApis(declared: ConstructManifest): RestApiDeclaration[] {\n\treturn Object.values(declared).filter(\n\t\t(d): d is RestApiDeclaration => d.kind === 'rest-api',\n\t);\n}\n\n/**\n * The surface whose declared `path` is the directory being built — asked of\n * every surface, because a workspace has several and each app's build serves\n * exactly one.\n *\n * Two surfaces can share a directory — an API and its webhooks, both\n * `apps/api` — so the folder alone does not say which is being built. The app\n * does: each surface is the app its id names, `Webhooks` is `webhooks`. A\n * directory holding one surface needs no name, and a build that gives none\n * gets the first, as it always did.\n *\n * Undefined when the named app is another kind of surface in the same\n * directory — a WebSocket API beside a RestApi is not the RestApi.\n */\nexport function servedSurface(\n\tdeclared: ConstructManifest,\n\tworkspaceRoot: string,\n\tappRoot: string,\n\tapp?: string,\n): RestApiDeclaration | undefined {\n\tconst served = surfaceAt(declared, workspaceRoot, appRoot, app);\n\treturn served?.kind === 'rest-api' ? served : undefined;\n}\n\ntype SurfaceDeclaration = Extract<\n\tConstructManifest[string],\n\t{ kind: 'rest-api' | 'websocket-api' }\n>;\n\n/**\n * The surface — a RestApi, or a WebSocket API — an app's build serves: the\n * one in its directory that the app is named for, else the first RestApi\n * there, else the first WebSocket API.\n */\nexport function surfaceAt(\n\tdeclared: ConstructManifest,\n\tworkspaceRoot: string,\n\tappRoot: string,\n\tapp?: string,\n): SurfaceDeclaration | undefined {\n\tconst here = Object.values(declared).filter(\n\t\t(d): d is SurfaceDeclaration =>\n\t\t\t(d.kind === 'rest-api' || d.kind === 'websocket-api') &&\n\t\t\tresolve(workspaceRoot, d.path) === resolve(appRoot),\n\t);\n\tconst named =\n\t\tapp !== undefined ? here.find((d) => appKey(d.id) === app) : undefined;\n\n\treturn (\n\t\tnamed ??\n\t\there.find((d) => d.kind === 'rest-api') ??\n\t\there.find((d) => d.kind === 'websocket-api')\n\t);\n}\n\n/**\n * The declarations one process reaches: the constructs it runs as — a surface,\n * a worker — what each declared an edge to, and what each runnable it runs\n * depends on or consumes.\n *\n * What decides which drivers its entry registers: a process that reaches no\n * cache never resolves a cache client because another process in the\n * workspace does.\n */\nexport function reachedBy(\n\tdeclared: ConstructManifest,\n\tprocesses: readonly string[],\n\trunnables: readonly { construct: { constructs?: readonly string[] } }[],\n): ConstructManifest {\n\tconst reached = new Set<string>();\n\tfor (const id of processes) {\n\t\tconst declaration = declared[id];\n\t\tif (!declaration) continue;\n\t\treached.add(id);\n\t\tfor (const edge of dependenciesOf(declaration)) reached.add(edge.target);\n\t}\n\tfor (const { construct } of runnables) {\n\t\tfor (const id of construct.constructs ?? []) reached.add(canonicalId(id));\n\t\tfor (const id of consumedBy(construct)) reached.add(id);\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(declared).filter(([id]) => reached.has(id)),\n\t);\n}\n\n/**\n * The declarations one Lambda handler reaches: its owner — the surface or\n * worker it was built from — with that owner's own edges, and what the\n * runnable itself depends on or consumes. The same reach `reachedBy` gives a\n * process, for a process that runs exactly one construct.\n *\n * A surface's own edges, not its routes': `dependenciesOf` folds every\n * endpoint's edges into its surface's, which is right for a server running\n * them all and wrong for a Lambda running one — a handler that reaches no\n * topic would register a broker because a sibling route publishes.\n *\n * Undefined where the owner is unknown — a construct from a free-standing\n * builder, or one whose owner was not discovered — so the caller can fall\n * back to the drivers of the whole app rather than guess.\n */\nexport function reachedByHandler(\n\tdeclared: ConstructManifest,\n\tconstruct: { owner?: string; constructs?: readonly string[] },\n): ConstructManifest | undefined {\n\tif (!construct.owner) return undefined;\n\tconst ownerId = declared[construct.owner]\n\t\t? construct.owner\n\t\t: canonicalId(construct.owner);\n\tconst owner = declared[ownerId];\n\tif (!owner) return undefined;\n\n\tconst own =\n\t\towner.kind === 'rest-api'\n\t\t\t? { ...owner, endpoints: [] }\n\t\t\t: owner.kind === 'websocket-api'\n\t\t\t\t? { ...owner, routes: [] }\n\t\t\t\t: owner;\n\t// A processor reads its file server's bucket, as it does under `gkm dev`.\n\tconst processes =\n\t\towner.kind === 'file-server' ? [ownerId, owner.of] : [ownerId];\n\n\treturn reachedBy({ ...declared, [ownerId]: own }, processes, [{ construct }]);\n}\n\n/**\n * The drivers each AWS handler registers, from {@link reachedByHandler}: the\n * cache's, the broker's, the KMS cipher, the API Gateway sink and S3, each\n * only where the construct reaches what needs it.\n *\n * Undefined for a construct whose reach is unknown, so the generator falls\n * back to the app's whole set — the safe answer, and the old one.\n */\nexport function handlerDriversFor(options: {\n\tdeclared: ConstructManifest;\n\tappRoot: string;\n\tcacheBackend: CacheBackend;\n\teventsBackend: EventsBackend;\n}): (construct: {\n\towner?: string;\n\tconstructs?: readonly string[];\n}) => RuntimeDrivers | undefined {\n\treturn (construct) => {\n\t\tconst reach = reachedByHandler(options.declared, construct);\n\t\tif (!reach) return undefined;\n\t\treturn driversFor({\n\t\t\tappRoot: options.appRoot,\n\t\t\tcache: cacheBackendsIn(reach, options.cacheBackend),\n\t\t\tevents: handlerEventsBackends(reach, options.eventsBackend),\n\t\t\tkms: opensKmsKeys(reach, 'aws'),\n\t\t\tapiGatewayWebSockets: publishesToApiGateway(reach, 'aws'),\n\t\t\tstorage: readsObjects(reach),\n\t\t});\n\t};\n}\n","import { join, resolve } from 'node:path';\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport type { MainProvider } from '../types';\nimport { appKey } from '../workspace/derive.js';\nimport { surfaceAt } from './owners';\n\n/**\n * The name of the tree an app's build writes under, when its directory holds\n * more than one surface — the app key of the surface it serves, `webhooks` —\n * or undefined for a directory with one.\n *\n * Two surfaces can name one folder — an API and its webhooks, `path:\n * 'apps/api'` both — and each is an app of its own, with its own endpoints.\n * Their builds cannot share one output tree: an AWS build empties its tree\n * first, so the second app's would delete the first's handlers, and a server\n * build would overwrite the first's entry with its own.\n *\n * Counted from the declared surfaces rather than the workspace's apps: a\n * single-app config's `api` sits at `.` beside the app its surface derives, and\n * that is one app, not two.\n */\nexport function sharedDirectoryTree(\n\tdeclared: ConstructManifest,\n\tworkspaceRoot: string,\n\tappRoot: string,\n\t/** The workspace app being built, when it is known. */\n\tapp?: string,\n): string | undefined {\n\tconst here = Object.values(declared).filter(\n\t\t(d) =>\n\t\t\t(d.kind === 'rest-api' || d.kind === 'websocket-api') &&\n\t\t\tresolve(workspaceRoot, d.path) === resolve(appRoot),\n\t);\n\tif (here.length < 2) return undefined;\n\n\tconst served = surfaceAt(declared, workspaceRoot, appRoot, app);\n\treturn served ? appKey(served.id) : undefined;\n}\n\n/**\n * Where one app's build writes for a target: `<app>/.gkm/<target>`.\n *\n * An app that shares its directory gets a tree of its own under that,\n * `<app>/.gkm/<target>/<tree>`, so its build replaces nothing another app\n * wrote. An app alone in its directory — nearly every one — keeps the path it\n * always had, so no handler a deploy already points at moves.\n */\nexport function appOutputDir(\n\tappRoot: string,\n\ttarget: MainProvider,\n\t/** See `sharedDirectoryTree`. */\n\ttree?: string,\n): string {\n\tconst base = join(appRoot, '.gkm', target);\n\treturn tree ? join(base, tree) : base;\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Processor } from '@geekmidas/constructs/processors';\nimport type { ProcessorInfo } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport { processorUnitName } from '../build/workers';\nimport {\n\tORIGIN_VERIFY_HEADER,\n\tPROCESSOR_ORIGIN_SECRET_ENV,\n} from '../providers/processorOrigin';\nimport { driversOf } from './drivers';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport { PROCESSORS_DEV_PREFIX } from './processorRoute';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\ntype AnyProcessor = Processor<string, any, any, any>;\n\n/** Where a file server's processor entry lives, under an app's `.gkm/server`. */\nexport function processorEntryDir(\n\tserverDir: string,\n\tfileServerId: string,\n): string {\n\treturn join(serverDir, 'processors', processorUnitName(fileServerId));\n}\n\n/** The file its bundle is written to, beside the server's. */\nexport function processorBundleName(fileServerId: string): string {\n\treturn `${processorUnitName(fileServerId)}.mjs`;\n}\n\n/**\n * A file server's processors, as the build generates them.\n *\n * On AWS each is a Lambda behind a function URL — the CDN's origin for its\n * pattern. On a server they are one process per file server, the processor\n * unit (see {@link ProcessorGenerator.buildEntry}), so the `server` target\n * generates nothing per processor here.\n */\nexport class ProcessorGenerator extends ConstructGenerator<\n\tAnyProcessor,\n\tProcessorInfo[]\n> {\n\tisConstruct(value: unknown): value is AnyProcessor {\n\t\treturn Processor.isProcessor(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<AnyProcessor>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<ProcessorInfo[]> {\n\t\tif ((options?.target ?? 'aws') !== 'aws' || constructs.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst dir = join(outputDir, 'processors');\n\t\tawait mkdir(dir, { recursive: true });\n\n\t\tconst infos: ProcessorInfo[] = [];\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst file = join(dir, `${key}.ts`);\n\t\t\tconst importPath = relative(dirname(file), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tconst drivers = driversOf(context, construct);\n\t\t\tawait writeFile(\n\t\t\t\tfile,\n\t\t\t\t`import { AWSLambdaProcessor } from '@geekmidas/constructs/processors';\nimport { ${key} } from '${importPath}';\n${drivers?.imports ?? ''}\n${drivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${drivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaProcessor(${key});\n\nexport const handler = adapter.handler;\n`,\n\t\t\t);\n\t\t\tinfos.push(\n\t\t\t\tawait processorInfo(\n\t\t\t\t\tkey,\n\t\t\t\t\tconstruct,\n\t\t\t\t\trelative(options?.root ?? process.cwd(), file).replace(\n\t\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t\t'.handler',\n\t\t\t\t\t),\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn infos;\n\t}\n\n\t/**\n\t * `gkm dev`'s half: `processors.ts` beside the dev server's app, mounting\n\t * each file server's processors under `/__gkm/processors/<FileServer>`.\n\t * The local edge sends each pattern on the file server's host there, so\n\t * `processedUrl()` answers locally as it does deployed.\n\t *\n\t * In the dev server's own process rather than a unit of its own: locally\n\t * there is no CPU to protect, and the dev server already reloads on change.\n\t */\n\tasync buildDev(\n\t\toutputDir: string,\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst file = join(outputDir, 'processors.ts');\n\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\t\tconst byServer = new Map<string, string[]>();\n\t\tfor (const { key, construct } of processors) {\n\t\t\tbyServer.set(construct.surfaceId, [\n\t\t\t\t...(byServer.get(construct.surfaceId) ?? []),\n\t\t\t\tkey,\n\t\t\t]);\n\t\t}\n\t\tconst units = [...byServer.entries()]\n\t\t\t.map(([id, keys]) => ` ${JSON.stringify(id)}: [${keys.join(', ')}],`)\n\t\t\t.join('\\n');\n\n\t\tawait writeFile(\n\t\t\tfile,\n\t\t\t`/**\n * Generated processors setup for \\`gkm dev\\`.\n *\n * Each file server's processors, under ${PROCESSORS_DEV_PREFIX}<FileServer>: the\n * local edge rewrites each processor pattern on the file server's host here.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${imports}\n\nexport function setupProcessors(\n app: { all: (path: string, handler: (c: any) => unknown) => unknown },\n envParser: EnvironmentParser<any>,\n): void {\n const units: Record<string, ReturnType<typeof processorServer>> = Object.fromEntries(\n Object.entries({\n${units}\n }).map(([id, processors]) => [id, processorServer(processors, envParser)]),\n );\n\n app.all('${PROCESSORS_DEV_PREFIX}:server/*', async (c: any) => {\n const server = c.req.param('server') as string;\n const serve = units[server];\n if (!serve) return c.notFound();\n const path = c.req.path.slice(\\`${PROCESSORS_DEV_PREFIX}\\${server}\\`.length) || '/';\n const response = await serve({ method: c.req.method, path });\n if (!response) {\n return new Response(null, {\n status: 404,\n headers: { 'cache-control': 'public, max-age=60' },\n });\n }\n return new Response(c.req.method === 'HEAD' ? null : response.body, {\n status: response.status,\n headers: response.headers,\n });\n });\n}\n`,\n\t\t);\n\t\treturn file;\n\t}\n\n\t/**\n\t * A file server's processor unit: one process answering each of its\n\t * processors' patterns, and `/health`. Returns its entry, `processors.ts`.\n\t *\n\t * Its own process because making a derivative is CPU-bound — a resize\n\t * spike in the API's process would be every request's latency.\n\t */\n\tasync buildEntry(input: {\n\t\tcontext: BuildContext;\n\t\tfileServerId: string;\n\t\toutputDir: string;\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[];\n\t\t/** From the file server's edge to a `Telemetry` node, when it has one. */\n\t\ttelemetry?: TelemetryContext;\n\t}): Promise<string> {\n\t\tconst { context, outputDir, processors } = input;\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\t// The file server's own edge decides; without one the module loads\n\t\t// nothing, and the entry's start-up is the same shape either way.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst healthCheck = context.production?.healthCheck ?? '/health';\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\n\t\tconst entry = join(outputDir, 'processors.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\t`#!/usr/bin/env node\n/**\n * Production entry for ${input.fileServerId}'s processors.\n * Generated by 'gkm build --production'.\n *\n * Answers each processor's pattern, and ${healthCheck} on PORT. The edge\n * routes only those patterns here; everything else on the file server's\n * domain is the bucket.\n */\nimport { timingSafeEqual } from 'node:crypto';\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${context.storageDrivers?.imports ?? ''}\n${imports}\n\n${startTelemetryCode([healthCheck])}\n${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(processorUnitName(input.fileServerId))};\n\nconst processors = [${processors.map(({ key }) => key).join(', ')}];\nconst serve = processorServer(processors);\nconst port = Number(process.env.PORT) || 3000;\nlet stopping = false;\n\n${input.telemetry ? REQUEST_SPANS : NO_REQUEST_SPANS}\n// Where the CDN fronts this unit, the secret it adds to every request: one\n// without it is refused here, whatever the edge in front did or could not.\nconst originSecret = process.env.${PROCESSOR_ORIGIN_SECRET_ENV}\n ? Buffer.from(process.env.${PROCESSOR_ORIGIN_SECRET_ENV})\n : undefined;\nconst fromOrigin = (header: string | string[] | undefined) => {\n if (!originSecret) return true;\n const given = Buffer.from(typeof header === 'string' ? header : '');\n return given.length === originSecret.length && timingSafeEqual(given, originSecret);\n};\n\nconst server = createServer(async (req, res) => {\n const method = req.method ?? 'GET';\n const path = (req.url ?? '/').split('?')[0] ?? '/';\n if (path === ${JSON.stringify(healthCheck)}) {\n res.writeHead(stopping ? 503 : 200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({ status: stopping ? 'stopping' : 'ok' }));\n return;\n }\n if (!fromOrigin(req.headers[${JSON.stringify(ORIGIN_VERIFY_HEADER.toLowerCase())}])) {\n res.writeHead(403, { 'cache-control': 'no-store' }).end();\n return;\n }\n await traced(method, path, async () => {\n try {\n const response = await serve({ method, path });\n if (!response) {\n res.writeHead(404, { 'cache-control': 'public, max-age=60' }).end();\n return 404;\n }\n res.writeHead(response.status, response.headers);\n res.end(method === 'HEAD' ? undefined : response.body);\n return response.status;\n } catch (error) {\n console.error(error);\n res.writeHead(500, { 'cache-control': 'no-store' }).end();\n return 500;\n }\n });\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n setTimeout(() => process.exit(1), Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000).unref();\n server.close();\n await runShutdownHooks((error) => console.error(error));\n process.exit(0);\n};\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n`,\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * A SERVER span per request, once telemetry has started — opened by the unit\n * rather than by hooking node:http, which sees nothing inside a bundle. Named\n * after the processor's pattern, never the key, which has no bound.\n *\n * Only in an entry whose file server has a `Telemetry` node: the bundle\n * follows the import, and an app without one need not install the API.\n */\nconst REQUEST_SPANS = `const tracing = requestSpans ? await import('@opentelemetry/api') : undefined;\nconst routeOf = (path: string) =>\n processors.find((processor) => path.startsWith(processor.prefix))?.pattern;\n\nasync function traced(\n method: string,\n path: string,\n run: () => Promise<number>,\n): Promise<void> {\n if (!tracing) {\n await run();\n return;\n }\n const route = routeOf(path);\n await tracing.trace.getTracer('@geekmidas/processors').startActiveSpan(\n route ? \\`\\${method} \\${route}\\` : method,\n {\n kind: tracing.SpanKind.SERVER,\n attributes: {\n 'http.request.method': method,\n 'url.path': path,\n ...(route ? { 'http.route': route } : {}),\n },\n },\n async (span) => {\n try {\n const status = await run();\n span.setAttribute('http.response.status_code', status);\n if (status >= 500) span.setStatus({ code: tracing.SpanStatusCode.ERROR });\n } finally {\n span.end();\n }\n },\n );\n}\n`;\n\n/** The same shape without telemetry: each request just runs. */\nconst NO_REQUEST_SPANS = `async function traced(\n _method: string,\n _path: string,\n run: () => Promise<number>,\n): Promise<void> {\n await run();\n}\n`;\n\n/** What the manifest records of one processor. */\nexport async function processorInfo(\n\tname: string,\n\tprocessor: AnyProcessor,\n\thandler: string,\n\tcontext: Pick<BuildContext, 'markOptional'>,\n): Promise<ProcessorInfo> {\n\treturn {\n\t\tname,\n\t\thandler,\n\t\tfileServer: processor.surfaceId,\n\t\tpath: processor.pattern,\n\t\tprefix: processor.prefix,\n\t\t...(processor.native.length ? { native: [...processor.native] } : {}),\n\t\t...(processor.timeout !== undefined ? { timeout: processor.timeout } : {}),\n\t\t...(processor.memorySize !== undefined\n\t\t\t? { memorySize: processor.memorySize }\n\t\t\t: {}),\n\t\tenvironment: await processor.getEnvironment({\n\t\t\tmarkOptional: context.markOptional,\n\t\t}),\n\t\tdependencies: processor.constructs,\n\t};\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Cron } from '@geekmidas/constructs/crons';\nimport type { BuildContext } from '../build/types';\nimport type { CronInfo } from '../types';\nimport { driversOf } from './drivers.js';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\nexport class CronGenerator extends ConstructGenerator<\n\tCron<any, any, any, any, any, any>,\n\tCronInfo[]\n> {\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<CronInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst cronInfos: CronInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// A server runs its crons itself, the way it already runs its\n\t\t\t// subscribers: one file, wired into the generated entry. Written even\n\t\t\t// when there are none, so the entry can import it unconditionally.\n\t\t\tawait this.generateServerCronsFile(outputDir, constructs);\n\n\t\t\tlogger.log(`Generated server crons file with ${constructs.length} crons`);\n\n\t\t\t// A server cron has no individual handler to point infra at — the\n\t\t\t// process schedules it.\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\t// Create crons subdirectory\n\t\tconst cronsDir = join(outputDir, 'crons');\n\t\tawait mkdir(cronsDir, { recursive: true });\n\n\t\t// Generate cron handlers\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateCronHandler(\n\t\t\t\tcronsDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\t{ ...context, storageDrivers: driversOf(context, construct) },\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tcronInfos.push({\n\t\t\t\tname: key,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tschedule: construct.schedule || 'rate(1 hour)',\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated cron handler: ${key}`);\n\t\t}\n\n\t\treturn cronInfos;\n\t}\n\n\tisConstruct(value: any): value is Cron<any, any, any, any, any, any> {\n\t\treturn Cron.isCron(value);\n\t}\n\n\t/**\n\t * The crons file a server entry imports.\n\t *\n\t * Shaped after `generateServerSubscribersFile`: one module, every cron, a\n\t * `setupCrons` the generated entry calls beside `setupSubscribers`.\n\t *\n\t * It picks its scheduler from what the process can reach. With a Postgres it\n\t * uses pg-boss, whose schedules live in the database — so a deployment\n\t * running four replicas fires each job once, which is the thing a timer in\n\t * every process gets wrong and does not report. With no database it falls\n\t * back to timers and says plainly that it is doing so.\n\t */\n\tprivate async generateServerCronsFile(\n\t\toutputDir: string,\n\t\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst cronsPath = join(outputDir, 'crons.ts');\n\n\t\t// Nothing to schedule, so nothing to import — the entry imports this file\n\t\t// whatever the app declares, and a project with no events must not have\n\t\t// to resolve `@geekmidas/events`.\n\t\tif (crons.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tcronsPath,\n\t\t\t\t`/**\n * Generated cron setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupCrons(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function cronsStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopCrons(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn cronsPath;\n\t\t}\n\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of crons) {\n\t\t\tconst relativePath = relative(dirname(cronsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) importsByFile.set(importPath, []);\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst entries = crons\n\t\t\t.map(({ key }) => ` { name: '${key}', cron: ${key} }`)\n\t\t\t.join(',\\n');\n\n\t\tconst content = `/**\n * Generated cron setup.\n *\n * Schedules every cron this app declares, in the process that serves it.\n *\n * The schedule lives in Postgres, through pg-boss, in the database the worker\n * named with \\`.database(db)\\`. That is what makes running several replicas\n * safe: each job fires once, where a timer in every process fires it once per\n * replica and reports nothing.\n *\n * No connection string appears here. The construct that owns the database is\n * the only thing that knows its key, and it is resolved through service\n * discovery like any other dependency.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runCron, scheduleInProcess, toCronExpression } from '@geekmidas/constructs/crons';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst crons = [\n${entries}\n];\n\ntype Stoppable = { stop: () => Promise<void> | void };\nconst running: Stoppable[] = [];\n// What a worker's health check reads: the crons that cannot be scheduled, and\n// the broker connection the schedule is kept through.\nconst failed: string[] = [];\nconst connections: import('@geekmidas/events').EventConnection[] = [];\n\nexport async function setupCrons(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n if (crons.length === 0) {\n return;\n }\n\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Resolved once per cron rather than per firing: registering services on\n // every tick would reconnect a database every minute.\n const prepared = [];\n for (const { name, cron } of crons) {\n try {\n const schedule = toCronExpression(cron.schedule);\n const services = cron.services.length > 0\n ? await serviceDiscovery.register(cron.services)\n : {};\n\n prepared.push({ name, cron, schedule, services });\n } catch (error) {\n // An unrepresentable schedule is a build-time mistake, and failing the\n // process for it would take the HTTP server down with it.\n logger.error({ err: error, cron: name }, 'Cron has no runnable schedule, skipping');\n failed.push(name);\n }\n }\n\n const run = async (entry: (typeof prepared)[number]) => {\n try {\n // The cron's own function, the way its Lambda would run it — services,\n // the worker's database as \\`db\\`, its events. It used to call a\n // \\`handler\\` a Cron does not have, so every firing logged a failure.\n await runCron(entry.cron, serviceDiscovery, entry.name);\n } catch (error) {\n logger.error({ err: error, cron: entry.name }, 'Cron failed');\n }\n };\n\n // The app's one pg-boss: the events broker's, as the broker's role, in the\n // broker's schema. A server fires its own crons, and a process scheduling in\n // memory fires each job once per replica — so the schedule lives in\n // Postgres. It used to be a second pg-boss on the worker's database, as the\n // runtime role, which can neither create a schema nor use the broker's.\n const { url, devPid } = envParser\n .create((get) => ({\n url: get('EVENT_PUBLISHER_CONNECTION_STRING').string().optional(),\n // Set by \\`gkm dev\\` on the server it starts, and by nothing deployed.\n devPid: get('GKM_DEV_PID').string().optional(),\n }))\n .parse();\n\n if (!url?.startsWith('pgboss://')) {\n // \\`gkm dev\\` on a target whose crons are infrastructure once deployed —\n // EventBridge rules on AWS — has no broker to keep a schedule in. It is one\n // process, so a timer fires each job once, which is all pg-boss is for\n // here. Only there: a deployed server firing by timer fires once per\n // replica, so outside dev this stays the error below.\n if (devPid) {\n for (const entry of prepared) {\n running.push(scheduleInProcess(entry.schedule, () => run(entry)));\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled in this process');\n }\n return;\n }\n\n logger.error(\n { crons: prepared.map(({ name }) => name) },\n 'These crons have nowhere to keep their schedule. On a server they are ' +\n 'scheduled through the pg-boss events broker ' +\n '(EVENT_PUBLISHER_CONNECTION_STRING), and ' +\n (url ? 'the broker configured is not pg-boss.' : 'none is configured.'),\n );\n failed.push(...prepared.map(({ name }) => name));\n return;\n }\n\n // Through the registered pg-boss driver, which the entry registers for a\n // server whose broker is pg-boss. Naming \\`@geekmidas/events/pgboss\\` here\n // made every bundle with a cron resolve pg-boss, whatever its broker.\n const { EventConnectionFactory } = await import('@geekmidas/events');\n const connection = (await EventConnectionFactory.fromConnectionString(\n url,\n )) as import('@geekmidas/events').EventConnection & { instance?: any };\n const boss = connection.instance!;\n\n // What this app declares now. Anything else under the prefix belonged to a\n // cron since renamed or deleted, and would keep firing at a handler that has\n // gone.\n //\n // The prefix is \\`cron.\\` rather than \\`cron:\\`: pg-boss accepts\n // alphanumerics, underscores, hyphens, periods and slashes in a queue name,\n // and rejects a colon outright.\n const declared = new Set(prepared.map(({ name }) => \\`cron.\\${name}\\`));\n for (const existing of await boss.getSchedules()) {\n if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {\n await boss.unschedule(existing.name);\n logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');\n }\n }\n\n for (const entry of prepared) {\n const queue = \\`cron.\\${entry.name}\\`;\n await boss.createQueue(queue);\n // UTC, so this agrees with the schedule a deploy target would have made.\n await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });\n await boss.work(queue, () => run(entry));\n\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');\n }\n\n running.push({ stop: () => connection.close() });\n connections.push(connection);\n logger.info({ count: prepared.length }, 'Crons scheduled');\n}\n\n/** The crons that cannot be scheduled, and the connection that schedules the rest. */\nexport function cronsStatus(): {\n failed: string[];\n connections: import('@geekmidas/events').EventConnection[];\n} {\n return { failed: [...failed], connections: [...connections] };\n}\n\n/**\n * Stop scheduling, let a firing in flight finish, and close the broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopCrons(): Promise<void> {\n const open = [...running];\n running.length = 0;\n connections.length = 0;\n await Promise.all(open.map((r) => r.stop()));\n}\n`;\n\n\t\tawait writeFile(cronsPath, content);\n\n\t\treturn cronsPath;\n\t}\n\n\tprivate async generateCronHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerFileName = `${exportName}.ts`;\n\t\tconst handlerPath = join(outputDir, handlerFileName);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSScheduledFunction(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Queue } from '@geekmidas/constructs/queue';\nimport { providedKeyFor } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport type { QueueInfo } from '../types';\nimport { driversOf } from './drivers.js';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\n/**\n * Generates the runtime for queue consumers (`worker.queue(…)`).\n *\n * - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that\n * polls each queue in-process, alongside the Hono server, through the queue's\n * own connection string — pg-boss by default, SQS on the AWS emulator.\n * - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed\n * by an SQS event-source mapping.\n */\nexport class QueueGenerator extends ConstructGenerator<\n\tQueue<any, any, any, any, any, any>,\n\tQueueInfo[]\n> {\n\tisConstruct(value: any): value is Queue<any, any, any, any, any, any> {\n\t\treturn Queue.isQueue(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<QueueInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst queueInfos: QueueInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// Generate queues.ts for in-process polling (even if empty, so the\n\t\t\t// server entry can always import setupQueues).\n\t\t\tawait this.generateServerQueuesFile(outputDir, constructs);\n\t\t\tlogger.log(\n\t\t\t\t`Generated server queues file with ${constructs.length} queues (polling mode)`,\n\t\t\t);\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tconst queuesDir = join(outputDir, 'queues');\n\t\tawait mkdir(queuesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateQueueHandler(\n\t\t\t\tqueuesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\t{ ...context, storageDrivers: driversOf(context, construct) },\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tqueueInfos.push({\n\t\t\t\tname: construct.name,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tbatchSize: construct.batchSize,\n\t\t\t\tfifo: construct.fifo,\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated queue handler: ${key}`);\n\t\t}\n\n\t\treturn queueInfos;\n\t}\n\n\tprivate async generateQueueHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\t\tconst importPath = relative(dirname(handlerPath), sourceFile).replace(\n\t\t\t/\\.ts$/,\n\t\t\t'.js',\n\t\t);\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaQueue(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateServerQueuesFile(\n\t\toutputDir: string,\n\t\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst queuesPath = join(outputDir, 'queues.ts');\n\n\t\t// Nothing to poll, so nothing to import. Every app gets this file, and\n\t\t// `@geekmidas/events` is only installed by one that declared a Topic or\n\t\t// a Queue — importing it here crashed every dev server that had not.\n\t\tif (queues.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tqueuesPath,\n\t\t\t\t`/**\n * Generated queues setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupQueues(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function queuesStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopQueues(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn queuesPath;\n\t\t}\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of queues) {\n\t\t\tconst importPath = relative(dirname(queuesPath), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\t// Each queue's consumer reaches its own queue, by the queue's own key.\n\t\tconst entries = queues\n\t\t\t.map(\n\t\t\t\t({ key, construct }) =>\n\t\t\t\t\t` { queue: ${key}, connectionKey: '${providedKeyFor(\n\t\t\t\t\t\tconstruct.id,\n\t\t\t\t\t\t'queue',\n\t\t\t\t\t\t'publisherConnectionString',\n\t\t\t\t\t)}' },`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst content = `/**\n * Generated queue consumers setup.\n *\n * Each queue's one consumer polls its own queue, through the queue's own\n * connection string — the one its producers publish on. SQS cannot push, so\n * this is a poller on every transport: pg-boss locally by default, the SQS\n * queue on the AWS emulator.\n *\n * Deployed on Lambda, a queue's consumer is an SQS event source instead.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { EventConnectionFactory, Subscriber } from '@geekmidas/events';\nimport type { EventConnection } from '@geekmidas/events';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst queues = [\n${entries}\n];\n\n// What was opened, and what could not be: a worker's health check reads both,\n// and its shutdown closes what was opened.\nconst connections = new Map<string, EventConnection>();\nconst failed: string[] = [];\n\nexport async function setupQueues(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n for (const { queue, connectionKey } of queues) {\n const connectionString = process.env[connectionKey];\n if (!connectionString) {\n logger.error({ queue: queue.name, connectionKey }, 'No connection string for this queue');\n failed.push(queue.name);\n continue;\n }\n\n try {\n let connection = connections.get(connectionString);\n if (!connection) {\n connection = await EventConnectionFactory.fromConnectionString(connectionString);\n connections.set(connectionString, connection);\n }\n const eventSubscriber = await Subscriber.fromConnection(connection);\n const services = queue.services.length > 0\n ? await serviceDiscovery.register(queue.services)\n : {};\n // The queue's database — the worker's, or its own — handed over as \\`db\\`.\n const db = queue.databaseService\n ? (await serviceDiscovery.register([queue.databaseService]))[\n queue.databaseService.serviceName\n ]\n : undefined;\n\n // A queue's messages carry one type — its own name.\n await eventSubscriber.subscribe([queue.name], async (message) => {\n try {\n const validation = await queue.messageSchema['~standard'].validate(message.payload);\n if (validation.issues) {\n logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');\n return;\n }\n\n await queue.handler({\n messages: [validation.value],\n services: services,\n logger: queue.logger,\n db,\n } as any);\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to process queue message');\n // Rethrown so the transport keeps the message for a retry.\n throw error;\n }\n });\n logger.info({ queue: queue.name }, 'Queue consumer started polling');\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to set up queue consumer');\n failed.push(queue.name);\n }\n }\n}\n\n/** The consumers that could not start, and the connections that did. */\nexport function queuesStatus(): { failed: string[]; connections: EventConnection[] } {\n return { failed: [...failed], connections: [...connections.values()] };\n}\n\n/**\n * Stop polling, let the messages in flight finish, and close each broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopQueues(): Promise<void> {\n const open = [...connections.values()];\n connections.clear();\n await Promise.all(open.map((connection) => connection.close()));\n}\n`;\n\n\t\tawait writeFile(queuesPath, content);\n\t\treturn queuesPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Cron } from '@geekmidas/constructs/crons';\nimport type { Queue } from '@geekmidas/constructs/queue';\nimport type { Subscriber } from '@geekmidas/constructs/subscribers';\nimport type { BuildContext } from '../build/types';\nimport { GkmError } from '../errors';\nimport { appKey } from '../workspace/derive.js';\nimport { CronGenerator } from './CronGenerator';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport type { GeneratedConstruct } from './Generator';\nimport { QueueGenerator } from './QueueGenerator';\nimport { SubscriberGenerator } from './SubscriberGenerator';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * A worker whose topic subscribers would have to be pushed to over HTTP.\n *\n * On SNS a subscriber is an HTTP endpoint SNS delivers to, and a worker's\n * process serves nothing but its health check. A server target's broker is\n * pg-boss, where each subscriber polls a queue of its own, so this is only\n * reached by building server images for a project that deploys to AWS — where\n * a subscriber is a Lambda instead.\n */\nexport class WorkerSubscribersNeedPush extends GkmError {\n\tconstructor(\n\t\treadonly worker: string,\n\t\treadonly subscribers: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' runs topic subscribers (${subscribers.join(', ')}), ` +\n\t\t\t\t`and this build's broker is SNS, which pushes each event to its ` +\n\t\t\t\t`subscriber over HTTP. A worker image serves only its health check. ` +\n\t\t\t\t`Deploy to a server target, whose broker is pg-boss and whose ` +\n\t\t\t\t`subscribers poll, or to AWS, where each subscriber is a Lambda.`,\n\t\t);\n\t\tthis.name = 'WorkerSubscribersNeedPush';\n\t}\n}\n\n/** Where a worker's generated entry lives, under an app's `.gkm/server`. */\nexport function workerEntryDir(serverDir: string, workerId: string): string {\n\treturn join(serverDir, 'workers', appKey(workerId));\n}\n\n/** The file a worker's bundle is written to, beside the server's. */\nexport function workerBundleName(workerId: string): string {\n\treturn `worker-${appKey(workerId)}.mjs`;\n}\n\nexport interface WorkerEntryInput {\n\tcontext: BuildContext;\n\t/** The worker's construct id, `Jobs`. */\n\tworkerId: string;\n\t/** The worker's own directory — see `workerEntryDir`. */\n\toutputDir: string;\n\t/** Everything built from this worker, and nothing built from another. */\n\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[];\n\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[];\n\tsubscribers: GeneratedConstruct<\n\t\tSubscriber<any, any, any, any, any, any, any>\n\t>[];\n\t/** What its process starts OpenTelemetry with — none without an edge. */\n\ttelemetry?: TelemetryContext;\n}\n\n/**\n * A Worker's production entry: the process that runs its crons, its queue\n * consumers and its topic subscribers, and answers nothing but a health check.\n *\n * It is the server's runtime without the server. The `crons.ts`, `queues.ts`\n * and `subscribers.ts` it starts are the files `gkm dev` starts — written by\n * the same generators, given only this worker's constructs — so a consumer\n * runs the same code in development and in the image. What it adds is the\n * process around them: drivers, a health check that says when a consumer or\n * the broker is down, and a shutdown that drains.\n */\nexport class WorkerGenerator {\n\tconstructor(\n\t\tprivate readonly generators = {\n\t\t\tcron: new CronGenerator(),\n\t\t\tqueue: new QueueGenerator(),\n\t\t\tsubscriber: new SubscriberGenerator(),\n\t\t},\n\t) {}\n\n\t/** Write the worker's files; returns its entry, `worker.ts`. */\n\tasync build(input: WorkerEntryInput): Promise<string> {\n\t\tconst { context, workerId, outputDir } = input;\n\n\t\tif (\n\t\t\tinput.subscribers.length > 0 &&\n\t\t\tcontext.eventsBackends?.includes('sns')\n\t\t) {\n\t\t\tthrow new WorkerSubscribersNeedPush(\n\t\t\t\tworkerId,\n\t\t\t\tinput.subscribers.map(({ key }) => key),\n\t\t\t);\n\t\t}\n\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst options = { target: 'server' as const };\n\t\tawait Promise.all([\n\t\t\tthis.generators.cron.build(context, input.crons, outputDir, options),\n\t\t\tthis.generators.queue.build(context, input.queues, outputDir, options),\n\t\t\tthis.generators.subscriber.build(\n\t\t\t\tcontext,\n\t\t\t\tinput.subscribers,\n\t\t\t\toutputDir,\n\t\t\t\toptions,\n\t\t\t),\n\t\t]);\n\n\t\tawait writeFile(\n\t\t\tjoin(outputDir, 'app.ts'),\n\t\t\tworkerApp(context, workerId, outputDir),\n\t\t);\n\t\t// The worker's own edge decides, not the app's that carries it.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst entry = join(outputDir, 'worker.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\tworkerEntry(context.production?.healthCheck ?? '/health'),\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * `app.ts`: the worker's runtime — its logger and environment parser off the\n * Worker construct, the drivers its target needs, and a `startWorker` that\n * starts every cron, consumer and subscriber it owns.\n */\nfunction workerApp(\n\tcontext: BuildContext,\n\tworkerId: string,\n\toutputDir: string,\n): string {\n\tconst runtime = runtimeFor(context, outputDir, workerId);\n\n\treturn `/**\n * Generated worker runtime for ${workerId}.\n * Generated by 'gkm build --production'.\n */\nimport { setupCrons, cronsStatus, stopCrons } from './crons.js';\nimport { setupQueues, queuesStatus, stopQueues } from './queues.js';\nimport { setupSubscribers, subscribersStatus, stopSubscribers } from './subscribers.js';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n// Who this worker is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(workerId)};\n\nexport { logger };\n\n/** What the health check answers, and why. */\nexport interface WorkerHealth {\n healthy: boolean;\n /** The crons, queues and subscribers that could not start. */\n failed: string[];\n /** How many broker connections did not answer. */\n down: number;\n}\n\n/** Whether one broker connection answers: open, and — on pg-boss — a query. */\nasync function answers(connection: unknown): Promise<boolean> {\n const c = connection as {\n isConnected?: () => boolean;\n instance?: { getDb?: () => { executeSql: (sql: string) => Promise<unknown> } };\n };\n if (c.isConnected && !c.isConnected()) return false;\n const db = c.instance?.getDb?.();\n if (!db) return true;\n try {\n await Promise.race([\n db.executeSql('select 1'),\n new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 2000).unref()),\n ]);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A request to a route this worker mounted, and what it answered. */\nexport interface WorkerRequest {\n headers: Record<string, string | string[] | undefined>;\n body: string;\n /** The request's query — Mailpit's webhook carries its token there. */\n query?: URLSearchParams;\n}\nexport interface WorkerAnswer {\n status: number;\n body: unknown;\n}\n\n// The routes something pushes to: an SNS subscriber's, and the one a local\n// object store posts a bucket's events to. Mounted by the subscribers, served\n// by the entry's HTTP server beside the health check.\nconst routes = new Map<string, (c: any) => unknown>();\nconst app = {\n post: (path: string, handler: (c: any) => unknown) => {\n routes.set(path, handler);\n },\n};\n\n/** Run one mounted route, as the subscribers' handlers expect to be called. */\nasync function route(path: string, request: WorkerRequest): Promise<WorkerAnswer | undefined> {\n const handler = routes.get(path);\n if (!handler) return undefined;\n let answer: WorkerAnswer | undefined;\n const c = {\n req: {\n text: async () => request.body,\n query: (name: string) => request.query?.get(name) ?? undefined,\n header: (name: string) => {\n const value = request.headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n },\n },\n json: (body: unknown, status = 200) => {\n answer = { status, body };\n return answer;\n },\n };\n await handler(c);\n return answer ?? { status: 204, body: null };\n}\n\n/** Start everything this worker runs. */\nexport async function startWorker(): Promise<{\n health: () => Promise<WorkerHealth>;\n stop: () => Promise<void>;\n route: typeof route;\n /** Subscribe the pushed routes, once the server answers on \\`port\\`. */\n subscribeForPush: (port: number) => Promise<void>;\n}> {\n const subscribeForPush = await setupSubscribers(app, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue consumers');\n });\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n const statuses = () => [subscribersStatus(), queuesStatus(), cronsStatus()];\n\n return {\n route,\n subscribeForPush,\n async health() {\n const all = statuses();\n const failed = all.flatMap((s) => s.failed);\n const alive = await Promise.all(\n all.flatMap((s) => s.connections as unknown[]).map(answers),\n );\n const down = alive.filter((ok) => !ok).length;\n return { healthy: failed.length === 0 && down === 0, failed, down };\n },\n // Each stops pulling, waits for what it has in flight, and closes its\n // broker connection. Together, so one slow handler does not hold the\n // others' connections open.\n async stop() {\n await Promise.all([stopSubscribers(), stopQueues(), stopCrons()]);\n },\n };\n}\n`;\n}\n\n/**\n * `worker.ts`: the process. Health first, so the container answers while the\n * consumers connect; then the worker; then a shutdown that drains.\n */\nfunction workerEntry(healthCheck: string): string {\n\treturn `#!/usr/bin/env node\n/**\n * Production worker entry point.\n * Generated by 'gkm build --production'.\n *\n * Runs this worker's crons, queue consumers and topic subscribers, and serves\n * its health check: ${healthCheck}, on PORT — 200 when every consumer started\n * and every broker connection answers, 503 otherwise. Beside it, on the same\n * port, the POST routes its subscribers mounted: where a local object store\n * posts a bucket's events.\n *\n * On SIGTERM it stops pulling messages and scheduling crons, lets the handlers\n * in flight finish, closes its broker connections and database pools, and\n * exits 0 — or 1, at GKM_SHUTDOWN_TIMEOUT_MS (8s by default, under Docker's\n * 10s stop timeout).\n */\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\n\n${startTelemetryCode([healthCheck])}\nconst { startWorker, logger } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nlet worker: Awaited<ReturnType<typeof startWorker>> | undefined;\nlet stopping = false;\n\nconst server = createServer((req, res) => {\n // Parsed once: the path routes, the query goes to the route.\n const url = new URL(req.url ?? '/', 'http://localhost');\n const path = url.pathname;\n const answer = (status: number, body: unknown) => {\n res.writeHead(status, { 'content-type': 'application/json' });\n res.end(JSON.stringify(body));\n };\n\n // A route a subscriber mounted: what SNS pushes to, or what a local object\n // store posts a bucket's events to. Refused while starting or stopping, so\n // the sender keeps the message and sends it again.\n if (req.method === 'POST') {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk) => {\n body += chunk;\n });\n req.on('end', () => {\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.route(path, { headers: req.headers, body, query: url.searchParams }).then(\n (routed) => (routed ? answer(routed.status, routed.body) : answer(404, { status: 'not found' })),\n (error) => {\n logger.error({ err: error, path }, 'Route failed');\n answer(500, { status: 'failed' });\n },\n );\n });\n return;\n }\n\n if (path !== ${JSON.stringify(healthCheck)} || (req.method !== 'GET' && req.method !== 'HEAD')) {\n res.writeHead(404).end();\n return;\n }\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.health().then(\n (health) => answer(health.healthy ? 200 : 503, { status: health.healthy ? 'ok' : 'unhealthy', ...health }),\n (error) => answer(503, { status: 'unhealthy', error: String(error) }),\n );\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n\n // Nothing new is pulled or scheduled; what is in flight finishes.\n await worker?.stop().catch((error) => logger.error({ err: error }, 'Failed to stop the worker'));\n // Then what the handlers used: database pools.\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n server.close();\n logger.info('Worker stopped');\n process.exit(0);\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nworker = await startWorker();\nlogger.info({ port }, 'Worker started');\nawait worker.subscribeForPush(port).catch((error) => {\n logger.error({ err: error }, 'Failed to subscribe for push');\n});\n`;\n}\n","import { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport {\n\ttype ConstructManifest,\n\timageOriginsFor,\n\tprovidedKeyFor,\n\tpublicEnvFor,\n\tpublicStageKey,\n} from '@geekmidas/manifest';\nimport { sharedDirectoryTree } from '../build/outputDir.js';\nimport {\n\ttype ProcessorUnit,\n\tprocessorUnits,\n\ttype WorkerUnit,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { loadWorkspaceConfig } from '../config';\nimport { GkmError } from '../errors';\nimport { processorBundleName } from '../generators/ProcessorGenerator.js';\nimport { workerBundleName } from '../generators/WorkerGenerator.js';\nimport { output } from '../output';\nimport { dockerfileOf } from '../reconcile/apps.js';\nimport { COMPOSE_PATH } from '../reconcile/index.js';\nimport { reconcileWorkspace } from '../reconcile/workspace.js';\nimport { run } from '../run';\nimport { getPublicUrlArgNames } from '../target/dokploy/domain.js';\nimport { siteClientTelemetry } from '../telemetry/edges.js';\nimport type { CacheBackend, GkmConfig } from '../types';\nimport { appKey } from '../workspace/derive.js';\nimport type {\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport { validateImageRef } from './imageRef';\nimport { appImageOptions, type ImageLayout, imageLayout } from './layout';\nimport {\n\tgenerateBackendDockerfile,\n\tgenerateDockerignore,\n\tgenerateEntryDockerfile,\n\tgenerateNextjsDockerfile,\n\tgenerateNodeWebDockerfile,\n\tgenerateProcessorDockerfile,\n\tgenerateViteStaticDockerfile,\n\tgenerateWorkerDockerfile,\n\tPROCESSOR_PORT,\n\tresolveDockerConfig,\n\tWORKER_PORT,\n} from './templates';\n\nexport { ImageRefInvalid, validateImageRef } from './imageRef';\nexport {\n\tappImageOptions,\n\tcomposeBuildPaths,\n\tfromBuildRoot,\n\ttype ImageLayout,\n\timageLayout,\n\tMonorepoNeedsTurbo,\n} from './layout';\nexport {\n\tdetectPackageManager,\n\tfindBuildRoot,\n\tfindLockfilePath,\n\thasTurboConfig,\n\tisMonorepo,\n} from './templates';\n\n// Through `output`, so a deploy run that generates a Dockerfile hears it.\nconst logger = output;\n\n/** `docker build` failed; what docker printed above says why. */\nexport class DockerBuildFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerBuildFailed';\n\t}\n}\n\n/** `docker push` failed — usually the registry login or its permissions. */\nexport class DockerPushFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerPushFailed';\n\t}\n}\n\n/** `gkm docker --push` was asked for with nowhere to push to. */\nexport class PushNeedsRegistry extends GkmError {\n\tconstructor(readonly imageName: string) {\n\t\tsuper(\n\t\t\t`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`,\n\t\t);\n\t\tthis.name = 'PushNeedsRegistry';\n\t}\n}\n\nexport interface DockerOptions {\n\t/** Build each app's image after generating files */\n\tbuild?: boolean;\n\t/** Push the images to the registry after building */\n\tpush?: boolean;\n\t/** Image tag (default: 'latest') */\n\ttag?: string;\n\t/** Container registry URL */\n\tregistry?: string;\n\t/**\n\t * The directory to generate for — an app's own, when a deploy builds it.\n\t * Defaults to the process's working directory.\n\t */\n\tcwd?: string;\n\t/**\n\t * The stage the images are for: a site's clients trace at its sample\n\t * rate. The local stage when absent.\n\t */\n\tstage?: string;\n}\n\n/**\n * Docker command implementation: one Dockerfile per deployable app, each\n * building its image inside Docker from a turbo-pruned slice of the build\n * root — nothing is built on the host — plus the build root's\n * `.dockerignore` and `docker-compose.constructs.yml`.\n */\nexport async function dockerCommand(\n\toptions: DockerOptions,\n): Promise<WorkspaceDockerResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst loaded = await loadWorkspaceConfig(cwd);\n\n\t// A single-app config is a workspace of one app at its root; the image is\n\t// named the way its `docker` block says.\n\tconst names: Record<string, string> =\n\t\tloaded.type === 'single'\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.keys(loaded.workspace.apps).map((name) => [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tresolveDockerConfig(loaded.raw as GkmConfig).imageName,\n\t\t\t\t\t]),\n\t\t\t\t)\n\t\t\t: {};\n\n\tconst result = await workspaceDockerCommand(\n\t\tloaded.workspace,\n\t\tloaded.manifest,\n\t\tnames,\n\t\tloaded.background,\n\t\toptions.stage,\n\t);\n\n\tif (options.build) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait buildDockerImage(app, result.buildRoot, options);\n\t\t}\n\t}\n\tif (options.push) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait pushDockerImage(app.imageName, options, result.buildRoot);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Build one app's image, from the build root.\n * Uses BuildKit for cache mount support\n */\nasync function buildDockerImage(\n\tapp: AppDockerResult,\n\tbuildRoot: string,\n\toptions: DockerOptions,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\t// Before anything runs: a ref docker would misread is refused by name.\n\tconst fullImageName = validateImageRef(\n\t\tregistry\n\t\t\t? `${registry}/${app.imageName}:${tag}`\n\t\t\t: `${app.imageName}:${tag}`,\n\t);\n\n\tlogger.log(`\\n🐳 Building Docker image: ${fullImageName}`);\n\n\ttry {\n\t\t// An argument array, so nothing in the ref is read by a shell, and\n\t\t// `--tag=` so it cannot be read as a flag.\n\t\tawait run(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'build',\n\t\t\t\t`--file=${relative(buildRoot, app.dockerfile)}`,\n\t\t\t\t`--tag=${fullImageName}`,\n\t\t\t\t'.',\n\t\t\t],\n\t\t\t{\n\t\t\t\tcwd: buildRoot,\n\t\t\t\t// BuildKit, for the templates' `RUN --mount=type=cache`.\n\t\t\t\tenv: { ...process.env, DOCKER_BUILDKIT: '1' },\n\t\t\t},\n\t\t);\n\t\tlogger.log(`✅ Docker image built: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerBuildFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Push Docker image to registry\n */\nasync function pushDockerImage(\n\timageName: string,\n\toptions: DockerOptions,\n\tcwd: string,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\tif (!registry) {\n\t\tthrow new PushNeedsRegistry(imageName);\n\t}\n\n\tconst fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);\n\n\tlogger.log(`\\n🚀 Pushing Docker image: ${fullImageName}`);\n\n\ttry {\n\t\tawait run('docker', ['push', fullImageName], { cwd });\n\t\tlogger.log(`✅ Docker image pushed: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerPushFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Result of generating Docker files for a single app in a workspace.\n */\nexport interface AppDockerResult {\n\tappName: string;\n\ttype: 'backend' | 'web' | 'mobile';\n\t/** The Dockerfile, absolute. */\n\tdockerfile: string;\n\timageName: string;\n}\n\n/**\n * Result of workspace docker command.\n */\nexport interface WorkspaceDockerResult {\n\tapps: AppDockerResult[];\n\tdockerCompose: string;\n\tdockerignore: string;\n\t/** Every image's build context, absolute. */\n\tbuildRoot: string;\n}\n\n/**\n * Generate Dockerfiles for all apps in a workspace.\n * @internal Exported for testing\n */\nexport async function workspaceDockerCommand(\n\tworkspace: NormalizedWorkspace,\n\t/** What the workspace declares — where a site's public keys come from. */\n\tmanifest?: ConstructManifest,\n\t/** Image names other than the app's own. */\n\timageNames: Readonly<Record<string, string>> = {},\n\t/** Each Worker's files, from discovery — which app each is built from. */\n\tbackground: Readonly<Record<string, readonly string[]>> = {},\n\t/** The stage a site's clients trace at the rate of — local when absent. */\n\tstage?: string,\n): Promise<WorkspaceDockerResult> {\n\tconst results: AppDockerResult[] = [];\n\tconst layout = imageLayout(workspace);\n\n\tlogger.log(`\\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);\n\tlogger.log(` Build root: ${layout.buildRoot}`);\n\tlogger.log(\n\t\t` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ''}, turbo@${layout.tools.turboVersion}`,\n\t);\n\n\tfor (const [appName, app] of Object.entries(workspace.apps)) {\n\t\t// Mobile apps deploy via their own toolchain (e.g. EAS Build for Expo)\n\t\t// — no Docker image is produced.\n\t\tif (app.type === 'mobile') {\n\t\t\tlogger.log(\n\t\t\t\t`\\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst buildType = app.entry ? 'entry' : app.type;\n\t\tlogger.log(`\\n 📄 Generating Dockerfile for ${appName} (${buildType})`);\n\n\t\tconst dockerfile = appDockerfile(appName, app, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tapps: workspace.apps,\n\t\t\t...(manifest ? { manifest } : {}),\n\t\t\tworkspace,\n\t\t\t...(stage ? { stage } : {}),\n\t\t});\n\n\t\tconst path = dockerfileOf(appName, app.path);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName,\n\t\t\ttype: app.type,\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[appName] ?? appName,\n\t\t});\n\t}\n\n\t// Each Worker with background work: an image of its own, built from the\n\t// app whose build writes its entry.\n\tfor (const worker of manifest\n\t\t? workerUnits(workspace, manifest, background)\n\t\t: []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`,\n\t\t);\n\t\tconst dockerfile = workerDockerfile(worker, workspace.apps[worker.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\t...(manifest ? { manifest } : {}),\n\t\t});\n\t\t// Always named for the worker: an app at the root has the bare\n\t\t// `Dockerfile`, which this must not overwrite.\n\t\tconst path = workerDockerfileOf(worker.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: worker.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[worker.name] ?? worker.name,\n\t\t});\n\t}\n\n\t// Each file server's processors: an image of their own, built from the\n\t// app whose build writes their entry.\n\tfor (const unit of manifest ? processorUnits(workspace, manifest) : []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${unit.name} (processors of ${unit.id}, built from ${unit.app})`,\n\t\t);\n\t\tconst dockerfile = processorDockerfile(unit, workspace.apps[unit.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\t...(manifest ? { manifest } : {}),\n\t\t});\n\t\tconst path = workerDockerfileOf(unit.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: unit.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[unit.name] ?? unit.name,\n\t\t});\n\t}\n\n\tconst dockerignorePath = await ensureDockerignore(layout.buildRoot);\n\tlogger.log(`\\n Ensured: ${dockerignorePath}`);\n\n\tconst composePath = await writeConstructsCompose(workspace);\n\n\t// Summary\n\tlogger.log(\n\t\t`\\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`,\n\t);\n\tlogger.log(`\\n📋 Build commands (from ${layout.buildRoot}):`);\n\tfor (const result of results) {\n\t\tconst icon =\n\t\t\tresult.type === 'backend' ? '⚙️' : result.type === 'mobile' ? '📱' : '🌐';\n\t\tlogger.log(\n\t\t\t` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`,\n\t\t);\n\t}\n\tprintRunInstructions(workspace);\n\n\treturn {\n\t\tapps: results,\n\t\tdockerCompose: composePath,\n\t\tdockerignore: dockerignorePath,\n\t\tbuildRoot: layout.buildRoot,\n\t};\n}\n\n/**\n * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,\n * a backend with its own entry bundled by esbuild, or a site by its\n * framework. The one choice every builder of images makes.\n */\nexport function appDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/**\n\t\t * Every app in the workspace, so a site's image knows the backends whose\n\t\t * clients it generates.\n\t\t */\n\t\tapps?: Readonly<Record<string, NormalizedAppConfig>>;\n\t\tmanifest?: ConstructManifest;\n\t\t/** The workspace's stages and `deploy.telemetry`, for a site's clients. */\n\t\tworkspace?: Pick<NormalizedWorkspace, 'stages' | 'deploy'>;\n\t\t/** A site's public keys, when the caller resolved them itself. */\n\t\tpublicUrlArgs?: string[];\n\t\t/**\n\t\t * The cache backend a gkm backend's entry registers, where it is not the\n\t\t * deploy target's — the compose stack's own Redis.\n\t\t */\n\t\tcache?: CacheBackend;\n\t\t/**\n\t\t * The stage whose sample rate a site's clients trace at — the local\n\t\t * stage when absent.\n\t\t */\n\t\tstage?: string;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tappName,\n\t\tapp,\n\t\toptions.workspaceRoot,\n\t\toptions.apps,\n\t\tapp.type === 'web' && options.manifest && options.workspace\n\t\t\t? siteClientTelemetry(\n\t\t\t\t\toptions.manifest,\n\t\t\t\t\tappName,\n\t\t\t\t\toptions.workspace,\n\t\t\t\t\toptions.stage,\n\t\t\t\t)\n\t\t\t: undefined,\n\t);\n\n\tif (app.type === 'web') {\n\t\treturn siteDockerfile(appName, app, {\n\t\t\timage,\n\t\t\t...(options.manifest ? { manifest: options.manifest } : {}),\n\t\t\t...(options.publicUrlArgs\n\t\t\t\t? { publicUrlArgs: options.publicUrlArgs }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\tif (app.entry) {\n\t\treturn generateEntryDockerfile({\n\t\t\t...image,\n\t\t\tentry: app.entry,\n\t\t\thealthCheckPath: '/health',\n\t\t});\n\t}\n\treturn generateBackendDockerfile({\n\t\t...image,\n\t\t...sharedDirectory(options, appName, app),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * For a gkm backend whose directory holds another surface: the app its image's\n * build is for, which is also the tree under `.gkm/server` it writes — see\n * `sharedDirectoryTree`. Nothing for an app alone in its directory.\n */\nfunction sharedDirectory(\n\toptions: { manifest?: ConstructManifest; workspaceRoot: string },\n\tappName: string,\n\tapp: NormalizedAppConfig,\n): { sharedDirectoryApp?: string } {\n\tif (!options.manifest) return {};\n\tconst tree = sharedDirectoryTree(\n\t\toptions.manifest,\n\t\toptions.workspaceRoot,\n\t\tresolve(options.workspaceRoot, app.path),\n\t\tappName,\n\t);\n\treturn tree ? { sharedDirectoryApp: tree } : {};\n}\n\n/** Where `gkm docker` writes a worker's Dockerfile. */\nexport function workerDockerfileOf(worker: string): string {\n\treturn `.gkm/docker/Dockerfile.${worker}`;\n}\n\n/**\n * A Worker's Dockerfile: its host app's build, and the worker's bundle as the\n * runner — see `generateWorkerDockerfile`.\n */\nexport function workerDockerfile(\n\tworker: WorkerUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/**\n\t\t * What the workspace declares, so the host's build knows whether its\n\t\t * directory holds another surface.\n\t\t */\n\t\tmanifest?: ConstructManifest;\n\t\t/** As {@link appDockerfile}'s: the cache backend its entry registers. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = {\n\t\t...appImageOptions(options.layout, worker.app, host, options.workspaceRoot),\n\t\t...sharedDirectory(options, worker.app, host),\n\t};\n\treturn generateWorkerDockerfile({\n\t\t...image,\n\t\timageName: worker.name,\n\t\tport: WORKER_PORT,\n\t\tworker: worker.id,\n\t\tbundle: workerBundleName(worker.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A file server's processor unit's Dockerfile: its host app's build, and the\n * unit's bundle as the runner, with its processors' native packages\n * installed beside it — see `generateProcessorDockerfile`.\n */\nexport function processorDockerfile(\n\tunit: ProcessorUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/** As {@link workerDockerfile}'s. */\n\t\tmanifest?: ConstructManifest;\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = {\n\t\t...appImageOptions(options.layout, unit.app, host, options.workspaceRoot),\n\t\t...sharedDirectory(options, unit.app, host),\n\t};\n\treturn generateProcessorDockerfile({\n\t\t...image,\n\t\timageName: unit.name,\n\t\tport: PROCESSOR_PORT,\n\t\tfileServer: unit.id,\n\t\tbundle: processorBundleName(unit.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A site's Dockerfile, with an `ARG` for every key its bundler inlines.\n *\n * The keys come from the site's declaration where there is one — every\n * public key its edges give it, `VITE_UPLOADS_URL` included — and an\n * `ARG` the Dockerfile does not declare is a build argument the build drops,\n * leaving the bundle with an empty URL.\n */\nexport function siteDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\timage: ReturnType<typeof appImageOptions>;\n\t\tmanifest?: ConstructManifest;\n\t\tpublicUrlArgs?: string[];\n\t},\n): string {\n\tconst declared = options.manifest\n\t\t? Object.entries(options.manifest).find(\n\t\t\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t\t\t)?.[1]\n\t\t: undefined;\n\tconst publicUrlArgs =\n\t\toptions.publicUrlArgs ??\n\t\t(declared?.kind === 'site' && options.manifest\n\t\t\t? [\n\t\t\t\t\t// Its own address under its own name, for server code that runs\n\t\t\t\t\t// at build — what `publicBuildValues` hands every image build.\n\t\t\t\t\tprovidedKeyFor(declared.id, declared.kind, 'url'),\n\t\t\t\t\t...Object.keys(publicEnvFor(declared, options.manifest)),\n\t\t\t\t\t// The origins its pages load files from, where it has any.\n\t\t\t\t\t...[imageOriginsFor(declared, options.manifest)?.key].filter(\n\t\t\t\t\t\t(key) => key !== undefined,\n\t\t\t\t\t),\n\t\t\t\t\t// The stage it is built for (`NEXT_PUBLIC_STAGE`).\n\t\t\t\t\tpublicStageKey(declared),\n\t\t\t\t]\n\t\t\t: getPublicUrlArgNames(app));\n\n\tconst webOpts = {\n\t\t...options.image,\n\t\tpublicUrlArgs,\n\t\t// Built against its stage's running APIs, so not offline.\n\t\t...(declared?.kind === 'site' && declared.prerender === 'stage'\n\t\t\t? { prerender: true }\n\t\t\t: {}),\n\t};\n\n\tswitch (app.framework) {\n\t\tcase 'vite':\n\t\t\treturn generateViteStaticDockerfile(webOpts);\n\t\tcase 'tanstack-start':\n\t\tcase 'remix':\n\t\t\treturn generateNodeWebDockerfile(webOpts);\n\t\tdefault:\n\t\t\t// nextjs (and any unspecified web framework — schema requires a valid\n\t\t\t// framework, so this is just a default).\n\t\t\treturn generateNextjsDockerfile(webOpts);\n\t}\n}\n\n/**\n * What a build root's `.dockerignore` must leave out of every image's\n * context: dependencies installed for another platform, anything built on the\n * host (every image builds from source), git, and gkm's own output —\n * `.gkm/compose`'s env files hold a stage's secrets.\n */\nconst REQUIRED_IGNORES = [\n\t'**/node_modules',\n\t'.git',\n\t'**/dist',\n\t'**/.next',\n\t'**/.turbo',\n\t'**/.gkm',\n\t'**/.gkm/compose',\n];\n\n/**\n * Make sure the build root's `.dockerignore` leaves out what no image may\n * hold: written whole where there is none, and each missing line appended to\n * one the project keeps.\n */\nexport async function ensureDockerignore(buildRoot: string): Promise<string> {\n\tconst path = join(buildRoot, '.dockerignore');\n\tif (!existsSync(path)) {\n\t\tawait writeFile(path, generateDockerignore());\n\t\treturn path;\n\t}\n\n\tconst current = await readFile(path, 'utf-8');\n\tconst lines = new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n\tconst missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));\n\tif (missing.length === 0) return path;\n\n\tawait appendFile(\n\t\tpath,\n\t\t`${current.endsWith('\\n') || current === '' ? '' : '\\n'}\\n# gkm: images build from source, and a stack's env files hold its secrets\\n${missing.join('\\n')}\\n`,\n\t);\n\treturn path;\n}\n\n/**\n * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with\n * the apps beside the containers their constructs derive.\n *\n * Through reconcile rather than a second generator, so what `gkm docker`\n * describes and what `gkm dev` runs cannot disagree. Nothing is started.\n */\nasync function writeConstructsCompose(\n\tworkspace: NormalizedWorkspace,\n): Promise<string> {\n\tawait reconcileWorkspace(workspace, {\n\t\tstage: workspace.stages.local,\n\t\tstart: false,\n\t});\n\tlogger.log(` Generated: ${COMPOSE_PATH} (project root)`);\n\treturn join(workspace.root, COMPOSE_PATH);\n}\n\nfunction printRunInstructions(workspace: NormalizedWorkspace): void {\n\tconst project = existsSync(join(workspace.root, 'docker-compose.yml'))\n\t\t? ' -f docker-compose.yml'\n\t\t: '';\n\tlogger.log('\\n📋 Run everything (the apps sit behind the \"apps\" profile):');\n\tlogger.log(\n\t\t' gkm setup # starts the containers and creates what they hold',\n\t);\n\tlogger.log(\n\t\t` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`,\n\t);\n}\n","/**\n * Providers: what creates the thing a construct is backed by, on a stage.\n *\n * The manifest says a bucket exists (`ObjectStorage`); `deploy.<kind>.<stage>`\n * says what backs it there. A stage that names a provider has gkm *create*\n * the backing resource — when it holds the account's provisioning\n * credentials — and write the connection value into the stage's secrets,\n * where every deploy reads it as if it had been set by hand. A stage that\n * names none is `external`: the value is yours to set, as it always was.\n *\n * | Part | What it is |\n * | ------------------------ | ------------------------------------------------------- |\n * | provisioning credentials | What creates the resource. Never given to an app. |\n * | `ensure()` | Idempotent find-or-create. Records in state. Never deletes. |\n * | runtime credentials | The keys it writes into the stage's secrets. |\n * | `verify()` | The cheap check every deploy runs. |\n *\n * The key under `deploy` is the manifest kind — `objects`, which\n * `ObjectStorage` and `FileServer` produce, `inbox`, `email` — so a kind\n * such as `deploy.cache` slots in beside them with providers of its own.\n */\n\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport type { DeployIdentity } from '../deploy/identity.js';\nimport type { ResourceRecord } from '../deploy/StateStore.js';\nimport type { BoundSubscriber } from '../reconcile/discover.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/** The manifest kinds a stage can name a provider for. */\nexport const PROVIDER_KINDS = ['objects', 'inbox', 'email'] as const;\n\nexport type ProviderKind = (typeof PROVIDER_KINDS)[number];\n\n/** A provider's own entry: `{ provider: 's3', … }`. */\nexport interface ProviderConfig {\n\tprovider: string;\n}\n\n/**\n * One stage's entry under `deploy.<kind>`:\n *\n * - `'external'` — the default: the stage's secrets hold the key, set by you.\n * - `{ provider, … }` — that provider creates the resource and writes the key.\n * - `false` — the stage has none of this kind; a construct of it is refused.\n */\nexport type StageProviderEntry<C extends ProviderConfig = ProviderConfig> =\n\t| 'external'\n\t| C\n\t| false;\n\n/** One change `ensure()` makes, or — in a dry run — would make. */\nexport interface ProvisionAction {\n\t/** The construct it is for. */\n\tconstruct: string;\n\t/** What it acts on: `bucket acme-shop-prod-uploads`. */\n\tresource: string;\n\t/** What it does: `create`, `set CORS (2 origins)`. */\n\tchange: string;\n}\n\n/** The stage's provisioning record, as `ensure()` reads and writes it. */\nexport interface ProvisionState {\n\t/** A resource recorded by an earlier run. */\n\trecord(key: string): ResourceRecord | undefined;\n\t/** About to be created — written before the call that creates it. */\n\tpending(entry: StateEntry): Promise<void>;\n\t/** Exists, as `id`. */\n\tready(entry: StateEntry, id: string): Promise<void>;\n\t/** When the stage was last deployed, for a rotation to know it was. */\n\treadonly lastDeployedAt?: string;\n}\n\nexport interface StateEntry {\n\t/** `<type>:<name>`, unique within the stage. */\n\tkey: string;\n\ttype: string;\n\tdata?: Record<string, unknown>;\n}\n\n/** What `ensure()` is handed. */\nexport interface EnsureContext<C extends ProviderConfig, K> {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\t/**\n\t * Each Worker's subscribers, from discovery — by export and the key its\n\t * deliveries come from. What a provider subscribes on a worker's behalf.\n\t */\n\tsubscribers?: Readonly<Record<string, readonly BoundSubscriber[]>>;\n\tstage: string;\n\tidentity: DeployIdentity;\n\tconfig: C;\n\t/** The provisioning credentials {@link ResourceProvider.credentials} found. */\n\tcredential: K;\n\t/** The stage's secrets as they are now, by key. */\n\tsecrets: Readonly<Record<string, string>>;\n\tstate: ProvisionState;\n\tdryRun: boolean;\n\t/** `--rotate-keys`: issue each runtime key a successor. */\n\trotateKeys: boolean;\n\t/** `--retire-old-keys`: delete a rotated-out key without waiting for a deploy. */\n\tretireOldKeys: boolean;\n\t/**\n\t * Runs `apply` and records `action` — or, in a dry run, only records it.\n\t * Every write to the provider's account goes through here.\n\t */\n\tchange(action: ProvisionAction, apply: () => Promise<void>): Promise<void>;\n\t/**\n\t * Writes keys into the stage's secrets now — not at the end of the run, so\n\t * a secret the account shows only once is kept the moment it exists. A dry\n\t * run writes nothing.\n\t */\n\twriteSecrets(values: Record<string, string>): Promise<void>;\n\t/**\n\t * Writes DNS records through the stage's DNS providers (`dns`), as the\n\t * deploy's own DNS step does — what a certificate's validation record and\n\t * a CDN's name, a domain's inbound mail (MX) need. A dry run prints them\n\t * and writes nothing.\n\t */\n\twriteDns(records: readonly ProviderDnsRecord[]): Promise<ProviderDnsResult>;\n\tlog(line: string): void;\n}\n\n/** One record a provider asks the stage's DNS for. */\nexport type ProviderDnsRecord =\n\t| {\n\t\t\t/** The full name: `_abc.files.example.com`. */\n\t\t\thost: string;\n\t\t\ttype: 'CNAME';\n\t\t\tvalue: string;\n\t }\n\t| {\n\t\t\t/** The full name: `example.com`, `*.example.com`. */\n\t\t\thost: string;\n\t\t\ttype: 'MX';\n\t\t\t/** The mail server: `inbound-smtp.eu-west-1.amazonaws.com`. */\n\t\t\tvalue: string;\n\t\t\t/** Lower is preferred: `10`. */\n\t\t\tpriority: number;\n\t };\n\n/** What writing a provider's records came to. */\nexport interface ProviderDnsResult {\n\t/**\n\t * Hosts no DNS provider wrote — under no domain in `dns`, or a `manual`\n\t * one — printed for the person to create.\n\t */\n\tmanual: string[];\n}\n\n/** What `verify()` is handed. */\nexport interface VerifyContext<C extends ProviderConfig> {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tstage: string;\n\tconfig: C;\n\t/** The stage's secrets, by key. */\n\tsecrets: Readonly<Record<string, string>>;\n\t/**\n\t * What the stage's state records, by key — how a provider knows a key it\n\t * checks was issued moments ago. Absent when nothing was read.\n\t */\n\tresources?: Readonly<Record<string, ResourceRecord>>;\n\t/** Progress worth printing: waiting on something. */\n\tlog?: (line: string) => void;\n}\n\n/** Where a provider's provisioning credentials are looked for. */\nexport interface CredentialLookup {\n\tstage: string;\n\t/** `--profile`, when given. */\n\tprofile?: string;\n\tenv: NodeJS.ProcessEnv;\n\t/** The CLI's home, for stored logins. */\n\thome?: string;\n}\n\n/**\n * A provider. `C` is its config entry, `K` its provisioning credential.\n *\n * Built-ins are registered in `providers/registry.ts`, the way a deploy\n * target's built-ins are.\n */\nexport interface ResourceProvider<\n\tC extends ProviderConfig = ProviderConfig,\n\tK = unknown,\n> {\n\treadonly kind: ProviderKind;\n\t/** What `provider:` names it. */\n\treadonly name: string;\n\t/**\n\t * Its config entry checked: returns it, or throws a named error saying\n\t * what is wrong — what the workspace schema runs.\n\t */\n\tcheck(stage: string, config: ProviderConfig): C;\n\t/** How its provisioning credentials are supplied, for messages. */\n\treadonly provisioning: {\n\t\t/** The environment variables it reads. */\n\t\tenv: readonly string[];\n\t\t/** A `gkm login --provider` name, where it has one. */\n\t\tlogin?: string;\n\t\t/** One line saying how to supply them. */\n\t\tdescribe: string;\n\t};\n\t/** Its provisioning credentials, or `undefined` when there are none. */\n\tcredentials(lookup: CredentialLookup): Promise<K | undefined>;\n\t/** The keys it writes into the stage's secrets for these constructs. */\n\truntimeKeys(manifest: ConstructManifest): string[];\n\tensure(ctx: EnsureContext<C, K>): Promise<void>;\n\tverify(ctx: VerifyContext<C>): Promise<void>;\n}\n","/**\n * What a deploy's checks read off `deploy.<kind>.<stage>`, without loading a\n * provider: which kinds the stage accounts for, what creates a missing key,\n * and a kind the stage has none of.\n */\n\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport type { StageProviderNotes } from '../deploy/devServices.js';\nimport { GkmError } from '../errors';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { provisioningOf, stageProvider } from './config.js';\nimport { PROVIDER_KINDS, type ProviderKind } from './types.js';\n\n/** The constructs of a kind: `objects` is every bucket. */\nexport function constructsOf(manifest: ConstructManifest, kind: ProviderKind) {\n\treturn Object.entries(manifest)\n\t\t.filter(([, d]) => d.kind === kind)\n\t\t.map(([id]) => id)\n\t\t.sort();\n}\n\n/** A stage that names `false` for a kind, and declares constructs of it. */\nexport class StageProviderDisabled extends GkmError {\n\tconstructor(\n\t\treadonly kind: ProviderKind,\n\t\treadonly stage: string,\n\t\treadonly ids: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`deploy.${kind}.${stage} is false — the stage has no ${kind} — and ` +\n\t\t\t\t`${ids.join(', ')} ${ids.length === 1 ? 'is' : 'are'} declared. ` +\n\t\t\t\t`Name what backs ${ids.length === 1 ? 'it' : 'them'} on '${stage}' ` +\n\t\t\t\t`(deploy.${kind}.${stage}: 'external', or a provider), or remove ` +\n\t\t\t\t`the ${ids.length === 1 ? 'construct' : 'constructs'}.`,\n\t\t);\n\t\tthis.name = 'StageProviderDisabled';\n\t}\n}\n\n/** The command a stage's providers are run with: every deploy runs them. */\nexport function provisionCommand(stage: string): string {\n\treturn `gkm deploy --stage ${stage}`;\n}\n\n/**\n * The line a stage missing a key a provider would write is given: what\n * creates it, and with which credentials. Undefined when no provider backs\n * the kind on the stage.\n */\nexport function provisionHint(\n\tworkspace: Pick<NormalizedWorkspace, 'deploy' | 'stages'>,\n\tkind: ProviderKind,\n\tstage: string,\n): string | undefined {\n\tconst choice = stageProvider(workspace as never, kind, stage);\n\tif (choice.mode !== 'provider') return undefined;\n\tconst provisioning = provisioningOf(kind, choice.name);\n\tif (!provisioning) return undefined;\n\treturn (\n\t\t`deploy.${kind}.${stage} is ${choice.name}: the deploy ` +\n\t\t`(${provisionCommand(stage)}) creates it and writes this key, with ` +\n\t\t`${provisioning.describe}` +\n\t\t(provisioning.login\n\t\t\t? `, or gkm login --provider ${provisioning.login}`\n\t\t\t: '')\n\t);\n}\n\n/**\n * What a deploy's checks read off the stage's providers: whether each kind is\n * accounted for — a provider, or `false` — so no dev service stands in for\n * it, and what creates a missing key of it.\n */\nexport function stageProviderNotes(\n\tworkspace: Pick<NormalizedWorkspace, 'deploy' | 'stages'>,\n\tstage: string,\n): StageProviderNotes {\n\tconst notes: StageProviderNotes = {};\n\tfor (const kind of ['objects', 'email'] as const) {\n\t\tif (stageProvider(workspace as never, kind, stage).mode === 'external') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst hint = provisionHint(workspace, kind, stage);\n\t\tnotes[kind] = { accounted: true, ...(hint ? { hint } : {}) };\n\t}\n\treturn notes;\n}\n\n/**\n * A kind the stage set to `false`, declared anyway — refused before anything\n * else is checked. Pure: what a stack is composed from.\n *\n * @throws {StageProviderDisabled}\n */\nexport function assertStageProvidersEnabled(\n\tworkspace: Pick<NormalizedWorkspace, 'deploy' | 'stages'>,\n\tmanifest: ConstructManifest,\n\tstage: string,\n): void {\n\tfor (const kind of PROVIDER_KINDS) {\n\t\tconst ids = constructsOf(manifest, kind);\n\t\tif (ids.length === 0) continue;\n\t\tif (stageProvider(workspace as never, kind, stage).mode === 'none') {\n\t\t\tthrow new StageProviderDisabled(kind, stage, ids);\n\t\t}\n\t}\n}\n","/**\n * The AWS account a provider provisions in — the stage's, found the way the\n * SSM and Secrets Manager stores find it.\n *\n * 1. `--profile`, resolved on its own: exported keys left over from another\n * account never win over a profile someone named.\n * 2. `AWS_PROFILE`, else `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` — the\n * deploy's own `aws` credential kind (`storedCredentials`).\n * 3. The SDK's default chain: `~/.aws` default profile, SSO, a role. In CI,\n * whatever `aws-actions/configure-aws-credentials` exported.\n *\n * None of them: the provider has no provisioning credentials, and the stage\n * is treated as `external`.\n */\n\nimport {\n\ttype AwsCredential,\n\tstoredCredentials,\n} from '../deploy/credentials.js';\nimport type { CredentialLookup } from './types.js';\n\n/** An AWS credential, or the default chain the SDK resolves itself. */\nexport type AwsProvisioning =\n\t| AwsCredential\n\t| {\n\t\t\tchain: true;\n\t\t\tregion?: string;\n\t };\n\nexport async function awsProvisioningCredentials(\n\tlookup: CredentialLookup,\n): Promise<AwsProvisioning | undefined> {\n\tconst region = lookup.env.AWS_REGION ?? lookup.env.AWS_DEFAULT_REGION;\n\tconst where = region ? { region } : {};\n\tif (lookup.profile) return { profile: lookup.profile, ...where };\n\n\tconst stored = await storedCredentials({\n\t\tenv: lookup.env,\n\t\t...(lookup.home ? { home: lookup.home } : {}),\n\t}).get({ kind: 'aws', stage: lookup.stage });\n\tif (stored) return stored;\n\n\ttry {\n\t\tconst { fromNodeProviderChain } = await import(\n\t\t\t'@aws-sdk/credential-providers'\n\t\t);\n\t\tawait fromNodeProviderChain({ timeout: 1000, maxRetries: 0 })();\n\t\treturn { chain: true, ...where };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * An S3-compatible endpoint the environment points the SDK at — the AWS\n * emulator in tests. The SDK reads it itself; it is read here too, because\n * an emulator takes path-style requests, and a key written for one has to\n * say where it is.\n */\nexport function awsEndpoint(\n\tenv: NodeJS.ProcessEnv,\n\tservice: 'S3' | 'IAM' | 'CLOUDFRONT' | 'ACM' | 'SNS' | 'SQS' | 'STS' | 'SES',\n): string | undefined {\n\treturn env[`AWS_ENDPOINT_URL_${service}`] ?? env.AWS_ENDPOINT_URL;\n}\n\n/** An SDK client's config for a provisioning credential. */\nexport async function awsClientConfig(\n\tcredential: AwsProvisioning,\n\tregion: string,\n): Promise<{\n\tregion: string;\n\tcredentials?:\n\t\t| ReturnType<typeof import('@aws-sdk/credential-providers').fromIni>\n\t\t| { accessKeyId: string; secretAccessKey: string; sessionToken?: string };\n}> {\n\tif ('profile' in credential) {\n\t\tconst { fromIni } = await import('@aws-sdk/credential-providers');\n\t\treturn { region, credentials: fromIni({ profile: credential.profile }) };\n\t}\n\tif ('accessKeyId' in credential) {\n\t\treturn {\n\t\t\tregion,\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: credential.accessKeyId,\n\t\t\t\tsecretAccessKey: credential.secretAccessKey,\n\t\t\t\t...(credential.sessionToken\n\t\t\t\t\t? { sessionToken: credential.sessionToken }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn { region };\n}\n","/**\n * Where a bucket the `s3` provider is to create signs its links, before it\n * has: the origin of the name and region its first deploy gives it.\n *\n * A site's image inlines its buckets' signed origins, and a protected stage's\n * images are built on every push to the default branch, long before the\n * release that first deploys the stage. The connection the origin is\n * otherwise derived from (`signedOrigins`) is written by that deploy, so\n * without this a stage that has never been deployed cannot be built, and a\n * stage that cannot be built is never deployed.\n */\n\nimport * as s3Url from '@geekmidas/storage/s3-url';\nimport { appKey } from '../../workspace/derive.js';\nimport type {\n\tNormalizedWorkspace,\n\tS3ObjectsConfig,\n} from '../../workspace/types.js';\nimport { awsEndpoint } from '../aws.js';\nimport { s3Region } from './config.js';\nimport { bucketName } from './naming.js';\n\nexport interface PlannedOriginInput {\n\tworkspace: Pick<NormalizedWorkspace, 'secrets'>;\n\tstage: string;\n\t/** The deploy identity's scope, which every bucket name starts with. */\n\tscope: string;\n\tconfig: S3ObjectsConfig;\n\t/** The `ObjectStorage` construct's id. */\n\tbucket: string;\n}\n\n/**\n * `https://<bucket>.s3.<region>.amazonaws.com` for the bucket's good name.\n *\n * Nothing when it cannot be known ahead: against an S3 emulator\n * (`AWS_ENDPOINT_URL`), or with no region to name. The first deploy names a\n * bucket otherwise only when another account already holds the good name —\n * a suffixed one, which it reports, and whose origin the next build inlines.\n */\nexport function plannedSignedOrigin(\n\tinput: PlannedOriginInput,\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\tif (awsEndpoint(env, 'S3')) return undefined;\n\tlet region: string;\n\ttry {\n\t\tregion = s3Region(input, env);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tconst bucket = bucketName({\n\t\tscope: input.scope,\n\t\tstage: input.stage,\n\t\tid: appKey(input.bucket),\n\t});\n\treturn s3Url.signedOrigin({ bucket, region });\n}\n","/**\n * A stage's deploy state.\n *\n * Every target records the same core — when the stage was last deployed, by\n * which identity, and each app's releases — and a target that keeps ids of\n * its own adds them in a shape of its own, told apart by `provider`:\n *\n * - `dokploy`: the project, applications, services and credentials Dokploy\n * gave the stage, so a later deploy updates them rather than making more.\n * - `compose`: nothing beyond the core. A compose stage is one stack on one\n * server; what it created elsewhere (DNS records) is a resource record.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { output } from '../output';\nimport type { Actor } from './actor';\n\n/**\n * Per-app database credentials\n */\nexport interface AppDbCredentials {\n\tdbUser: string;\n\tdbPassword: string;\n}\n\n/**\n * DNS verification record for a hostname\n */\nexport interface DnsVerificationRecord {\n\tserverIp: string;\n\tverifiedAt: string;\n}\n\n/**\n * A DNS record that was created during deploy\n */\nexport interface CreatedDnsRecord {\n\t/** The domain this record belongs to (e.g., 'example.com') */\n\tdomain: string;\n\t/** Record name/subdomain (e.g., 'api' or '@' for root) */\n\tname: string;\n\t/** Record type (A, CNAME, etc.) */\n\ttype: string;\n\t/** Record value (IP address, hostname, etc.) */\n\tvalue: string;\n\t/** TTL in seconds */\n\tttl: number;\n\t/** When this record was created */\n\tcreatedAt: string;\n}\n\n/**\n * Backup destination state\n */\nexport interface BackupState {\n\t/** S3 bucket name for backups */\n\tbucketName: string;\n\t/** S3 bucket ARN */\n\tbucketArn: string;\n\t/** IAM user name created for backup access */\n\tiamUserName: string;\n\t/** IAM access key ID */\n\tiamAccessKeyId: string;\n\t/** IAM secret access key */\n\tiamSecretAccessKey: string;\n\t/** Dokploy destination ID */\n\tdestinationId: string;\n\t/** Dokploy backup schedule ID for postgres (if configured) */\n\tpostgresBackupId?: string;\n\t/** AWS region where bucket was created */\n\tregion: string;\n\t/** Timestamp when backup was configured */\n\tcreatedAt: string;\n}\n\n/** What every target's state for a stage holds. */\nexport interface StageStateCore {\n\tstage: string;\n\tlastDeployedAt: string;\n\t/**\n\t * The deploy identity's key (`<namespace>/<project>`) that last deployed\n\t * this stage — what the project's ownership marker says.\n\t */\n\tidentity?: string;\n\t/**\n\t * Each app's releases, keyed by app name: what runs now, what ran before\n\t * it — which `gkm deploy:rollback` restores — and the history behind both.\n\t */\n\treleases?: Record<string, AppReleases>;\n}\n\n/** A compose stage's state: the core, and nothing Dokploy-specific. */\nexport interface ComposeStageState extends StageStateCore {\n\tprovider: 'compose';\n}\n\n/**\n * State for a single stage deployment\n */\nexport interface DokployStageState extends StageStateCore {\n\tprovider: 'dokploy';\n\t/** Dokploy project ID - created on first deploy */\n\tprojectId: string;\n\tenvironmentId: string;\n\tapplications: Record<string, string>; // appName -> applicationId\n\tservices: {\n\t\tpostgresId?: string;\n\t\tredisId?: string;\n\t};\n\t/** Per-app database credentials for reuse on subsequent deploys */\n\tappCredentials?: Record<string, AppDbCredentials>;\n\t/** Auto-generated secrets per app (e.g., BETTER_AUTH_SECRET) */\n\tgeneratedSecrets?: Record<string, Record<string, string>>;\n\t/** DNS verification state per hostname */\n\tdnsVerified?: Record<string, DnsVerificationRecord>;\n\t/** DNS records created during deploy (keyed by \"name:type\", e.g., \"api:A\") */\n\tdnsRecords?: Record<string, CreatedDnsRecord>;\n\t/** Backup destination state */\n\tbackups?: BackupState;\n\t/**\n\t * The Dokploy registry the stage's images are pulled through. Kept per\n\t * stage rather than once per machine, so a stage keeps the registry it was\n\t * deployed with whoever deploys it next.\n\t */\n\tregistryId?: string;\n}\n\n/** A stage's state, whichever target wrote it. */\nexport type StageState = DokployStageState | ComposeStageState;\n\n/** An image a stage runs: the ref it was pushed as, and what it resolved to. */\nexport interface DeployedImage {\n\tref: string;\n\t/**\n\t * The tag it was released under — a site's carries its stage\n\t * (`v1.4.0-production`). Recorded by targets that pull a release by tag.\n\t */\n\ttag?: string;\n\t/** The registry's digest, `sha256:…` — absent if it could not be read. */\n\tdigest?: string;\n}\n\n/**\n * Get the state file path for a stage\n */\nfunction getStateFilePath(workspaceRoot: string, stage: string): string {\n\treturn join(workspaceRoot, '.gkm', `deploy-${stage}.json`);\n}\n\n/**\n * Read the deploy state for a stage\n * Returns null if state file doesn't exist\n */\nexport async function readStageState(\n\tworkspaceRoot: string,\n\tstage: string,\n): Promise<StageState | null> {\n\tconst filePath = getStateFilePath(workspaceRoot, stage);\n\n\ttry {\n\t\tconst content = await readFile(filePath, 'utf-8');\n\t\treturn JSON.parse(content) as StageState;\n\t} catch (error) {\n\t\t// File doesn't exist or is invalid - return null\n\t\tif ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\treturn null;\n\t\t}\n\t\t// Log other errors but don't fail\n\t\toutput.warn(`Warning: Could not read deploy state: ${error}`);\n\t\treturn null;\n\t}\n}\n\n/**\n * Write the deploy state for a stage\n */\nexport async function writeStageState(\n\tworkspaceRoot: string,\n\tstage: string,\n\tstate: StageState,\n): Promise<void> {\n\tconst filePath = getStateFilePath(workspaceRoot, stage);\n\tconst dir = join(workspaceRoot, '.gkm');\n\n\t// Ensure .gkm directory exists\n\tawait mkdir(dir, { recursive: true });\n\n\t// Update last deployed timestamp\n\tstate.lastDeployedAt = new Date().toISOString();\n\n\tawait writeFile(filePath, JSON.stringify(state, null, 2));\n}\n\n/**\n * Create a new empty state for a stage\n */\nexport function createEmptyState(\n\tstage: string,\n\tprojectId: string,\n\tenvironmentId: string,\n): DokployStageState {\n\treturn {\n\t\tprovider: 'dokploy',\n\t\tstage,\n\t\tprojectId,\n\t\tenvironmentId,\n\t\tapplications: {},\n\t\tservices: {},\n\t\tlastDeployedAt: new Date().toISOString(),\n\t};\n}\n\n/** A new compose stage's state. */\nexport function createComposeState(stage: string): ComposeStageState {\n\treturn {\n\t\tprovider: 'compose',\n\t\tstage,\n\t\tlastDeployedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * `state` as the Dokploy target keeps it. A stage whose state another target\n * wrote — one moved from compose to Dokploy — keeps its core (releases,\n * identity) and starts with no Dokploy ids, as a first deploy would.\n */\nexport function asDokployState(state: StageState): DokployStageState {\n\tif (state.provider === 'dokploy') return state;\n\tconst { provider: _provider, ...core } = state;\n\treturn {\n\t\t...core,\n\t\tprovider: 'dokploy',\n\t\tprojectId: '',\n\t\tenvironmentId: '',\n\t\tapplications: {},\n\t\tservices: {},\n\t};\n}\n\n/**\n * Get application ID from state\n */\nexport function getApplicationId(\n\tstate: DokployStageState | null,\n\tappName: string,\n): string | undefined {\n\treturn state?.applications[appName];\n}\n\n/**\n * Set application ID in state (mutates state)\n */\nexport function setApplicationId(\n\tstate: DokployStageState,\n\tappName: string,\n\tapplicationId: string,\n): void {\n\tstate.applications[appName] = applicationId;\n}\n\n/** An image that went live, and when. */\nexport interface ReleasedImage extends DeployedImage {\n\t/** The image tag the deploy released under. */\n\ttag?: string;\n\treleasedAt: string;\n\t/** Who released it — absent on a release recorded before it was kept. */\n\treleasedBy?: Actor;\n\t/** Set when a rollback replaced it: it is never rolled back *to*. */\n\trolledBack?: true;\n}\n\n/** An app's releases: what runs, what ran before it, and what ran before that. */\nexport interface AppReleases {\n\tcurrent: ReleasedImage;\n\t/** What a rollback restores; absent until a second release. */\n\tprevious?: ReleasedImage;\n\t/** Every release, newest first, at most {@link RELEASE_HISTORY} of them. */\n\thistory: ReleasedImage[];\n}\n\n/** How many releases an app's history keeps. */\nexport const RELEASE_HISTORY = 10;\n\n/** Two records naming the same image: by digest when both have one. */\nfunction sameImage(a: DeployedImage, b: DeployedImage): boolean {\n\treturn a.digest && b.digest ? a.digest === b.digest : a.ref === b.ref;\n}\n\n/** The newest release in `history` after `index` that a rollback may restore. */\nfunction restorable(\n\thistory: readonly ReleasedImage[],\n\tindex: number,\n\tcurrent: DeployedImage,\n): ReleasedImage | undefined {\n\treturn history\n\t\t.slice(index + 1)\n\t\t.find((entry) => !entry.rolledBack && !sameImage(entry, current));\n}\n\n/**\n * Record that `image` went live for `appName` (mutates state): it becomes\n * `current`, and what was current becomes `previous`. Releasing what already\n * runs — a redeploy of the same digest — changes nothing.\n */\nexport function recordRelease(\n\tstate: StageStateCore,\n\tappName: string,\n\timage: Omit<ReleasedImage, 'releasedAt' | 'releasedBy' | 'rolledBack'>,\n\tby: Actor,\n\treleasedAt: Date = new Date(),\n): void {\n\tconst releases = state.releases?.[appName];\n\tif (releases && sameImage(releases.current, image)) return;\n\n\tconst entry: ReleasedImage = {\n\t\t...image,\n\t\treleasedAt: releasedAt.toISOString(),\n\t\treleasedBy: by,\n\t};\n\tconst history = [entry, ...(releases?.history ?? [])].slice(\n\t\t0,\n\t\tRELEASE_HISTORY,\n\t);\n\tconst previous = releases?.current;\n\tstate.releases = {\n\t\t...state.releases,\n\t\t[appName]: { current: entry, ...(previous ? { previous } : {}), history },\n\t};\n}\n\n/**\n * Record that `appName` was rolled back to `to` (mutates state): every\n * release newer than it is marked rolled back, so neither this rollback nor\n * a later one restores it, and `previous` moves to the release before `to`.\n */\nexport function recordRollback(\n\tstate: StageStateCore,\n\tappName: string,\n\tto: DeployedImage,\n): void {\n\tconst releases = state.releases?.[appName];\n\tif (!releases) return;\n\n\tconst index = releases.history.findIndex(\n\t\t(entry) => !entry.rolledBack && sameImage(entry, to),\n\t);\n\tif (index === -1) return;\n\n\tconst history = releases.history.map((entry, i) =>\n\t\ti < index ? { ...entry, rolledBack: true as const } : entry,\n\t);\n\tconst current = history[index]!;\n\tconst previous = restorable(history, index, current);\n\tstate.releases = {\n\t\t...state.releases,\n\t\t[appName]: { current, ...(previous ? { previous } : {}), history },\n\t};\n}\n\n/**\n * Get postgres ID from state\n */\nexport function getPostgresId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.services.postgresId;\n}\n\n/**\n * Set postgres ID in state (mutates state)\n */\nexport function setPostgresId(\n\tstate: DokployStageState,\n\tpostgresId: string,\n): void {\n\tstate.services.postgresId = postgresId;\n}\n\n/**\n * Get redis ID from state\n */\nexport function getRedisId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.services.redisId;\n}\n\n/**\n * Set redis ID in state (mutates state)\n */\nexport function setRedisId(state: DokployStageState, redisId: string): void {\n\tstate.services.redisId = redisId;\n}\n\n/**\n * Get app credentials from state\n */\nexport function getAppCredentials(\n\tstate: DokployStageState | null,\n\tappName: string,\n): AppDbCredentials | undefined {\n\treturn state?.appCredentials?.[appName];\n}\n\n/**\n * Set app credentials in state (mutates state)\n */\nexport function setAppCredentials(\n\tstate: DokployStageState,\n\tappName: string,\n\tcredentials: AppDbCredentials,\n): void {\n\tif (!state.appCredentials) {\n\t\tstate.appCredentials = {};\n\t}\n\tstate.appCredentials[appName] = credentials;\n}\n\n/**\n * Get all app credentials from state\n */\nexport function getAllAppCredentials(\n\tstate: DokployStageState | null,\n): Record<string, AppDbCredentials> {\n\treturn state?.appCredentials ?? {};\n}\n\n// ============================================================================\n// Generated Secrets\n// ============================================================================\n\n/**\n * Get a generated secret for an app\n */\nexport function getGeneratedSecret(\n\tstate: DokployStageState | null,\n\tappName: string,\n\tsecretName: string,\n): string | undefined {\n\treturn state?.generatedSecrets?.[appName]?.[secretName];\n}\n\n/**\n * Set a generated secret for an app (mutates state)\n */\nexport function setGeneratedSecret(\n\tstate: DokployStageState,\n\tappName: string,\n\tsecretName: string,\n\tvalue: string,\n): void {\n\tif (!state.generatedSecrets) {\n\t\tstate.generatedSecrets = {};\n\t}\n\tif (!state.generatedSecrets[appName]) {\n\t\tstate.generatedSecrets[appName] = {};\n\t}\n\tstate.generatedSecrets[appName][secretName] = value;\n}\n\n/**\n * Get all generated secrets for an app\n */\nexport function getAppGeneratedSecrets(\n\tstate: DokployStageState | null,\n\tappName: string,\n): Record<string, string> {\n\treturn state?.generatedSecrets?.[appName] ?? {};\n}\n\n/**\n * Get all generated secrets from state\n */\nexport function getAllGeneratedSecrets(\n\tstate: DokployStageState | null,\n): Record<string, Record<string, string>> {\n\treturn state?.generatedSecrets ?? {};\n}\n\n// ============================================================================\n// DNS Verification\n// ============================================================================\n\n/**\n * Get DNS verification record for a hostname\n */\nexport function getDnsVerification(\n\tstate: DokployStageState | null,\n\thostname: string,\n): DnsVerificationRecord | undefined {\n\treturn state?.dnsVerified?.[hostname];\n}\n\n/**\n * Set DNS verification record for a hostname (mutates state)\n */\nexport function setDnsVerification(\n\tstate: DokployStageState,\n\thostname: string,\n\tserverIp: string,\n): void {\n\tif (!state.dnsVerified) {\n\t\tstate.dnsVerified = {};\n\t}\n\tstate.dnsVerified[hostname] = {\n\t\tserverIp,\n\t\tverifiedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * Check if a hostname is already verified with the given IP\n */\nexport function isDnsVerified(\n\tstate: DokployStageState | null,\n\thostname: string,\n\tserverIp: string,\n): boolean {\n\tconst record = state?.dnsVerified?.[hostname];\n\treturn record?.serverIp === serverIp;\n}\n\n/**\n * Get all DNS verification records from state\n */\nexport function getAllDnsVerifications(\n\tstate: DokployStageState | null,\n): Record<string, DnsVerificationRecord> {\n\treturn state?.dnsVerified ?? {};\n}\n\n// ============================================================================\n// DNS Records\n// ============================================================================\n\n/**\n * Get the key for a DNS record in state\n */\nfunction getDnsRecordKey(name: string, type: string): string {\n\treturn `${name}:${type}`;\n}\n\n/**\n * Get a created DNS record from state\n */\nexport function getDnsRecord(\n\tstate: DokployStageState | null,\n\tname: string,\n\ttype: string,\n): CreatedDnsRecord | undefined {\n\treturn state?.dnsRecords?.[getDnsRecordKey(name, type)];\n}\n\n/**\n * Set a created DNS record in state (mutates state)\n */\nexport function setDnsRecord(\n\tstate: DokployStageState,\n\trecord: Omit<CreatedDnsRecord, 'createdAt'>,\n): void {\n\tif (!state.dnsRecords) {\n\t\tstate.dnsRecords = {};\n\t}\n\tconst key = getDnsRecordKey(record.name, record.type);\n\tstate.dnsRecords[key] = {\n\t\t...record,\n\t\tcreatedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * Remove a DNS record from state (mutates state)\n */\nexport function removeDnsRecord(\n\tstate: DokployStageState,\n\tname: string,\n\ttype: string,\n): void {\n\tif (state.dnsRecords) {\n\t\tdelete state.dnsRecords[getDnsRecordKey(name, type)];\n\t}\n}\n\n/**\n * Get all created DNS records from state\n */\nexport function getAllDnsRecords(\n\tstate: DokployStageState | null,\n): CreatedDnsRecord[] {\n\tif (!state?.dnsRecords) {\n\t\treturn [];\n\t}\n\treturn Object.values(state.dnsRecords);\n}\n\n/**\n * Clear all DNS records from state (mutates state)\n */\nexport function clearDnsRecords(state: DokployStageState): void {\n\tstate.dnsRecords = {};\n\tstate.dnsVerified = {};\n}\n\n// ============================================================================\n// Backup State\n// ============================================================================\n\n/**\n * Get backup state from state\n */\nexport function getBackupState(\n\tstate: DokployStageState | null,\n): BackupState | undefined {\n\treturn state?.backups;\n}\n\n/**\n * Set backup state (mutates state)\n */\nexport function setBackupState(\n\tstate: DokployStageState,\n\tbackupState: BackupState,\n): void {\n\tstate.backups = backupState;\n}\n\n/**\n * Get backup destination ID from state\n */\nexport function getBackupDestinationId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.backups?.destinationId;\n}\n\n/**\n * Get postgres backup ID from state\n */\nexport function getPostgresBackupId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.backups?.postgresBackupId;\n}\n\n/**\n * Set postgres backup ID in state (mutates state)\n */\nexport function setPostgresBackupId(\n\tstate: DokployStageState,\n\tbackupId: string,\n): void {\n\tif (state.backups) {\n\t\tstate.backups.postgresBackupId = backupId;\n\t}\n}\n","/**\n * The DNS provider a `dns` domain names, built from the workspace's config.\n *\n * The providers themselves are `@geekmidas/edge`'s and take their credentials\n * as given. Where a credential comes from (a stored login, the environment)\n * and what to say when there is none are the CLI's, and are decided here.\n */\n\nimport { type DnsProvider, isDnsProvider } from '@geekmidas/edge/dns';\nimport type { CloudflareCredential } from '@geekmidas/edge/dns/cloudflare';\nimport type {\n\tGoDaddyCredential,\n\tGoDaddyProviderOptions,\n} from '@geekmidas/edge/dns/godaddy';\nimport type { HostingerCredential } from '@geekmidas/edge/dns/hostinger';\nimport type { z } from 'zod/v4';\nimport { getHostingerToken } from '../auth/credentials';\nimport { MissingCredential, storedCredentials } from '../deploy/credentials';\nimport { GkmError } from '../errors';\nimport type {\n\tCloudflareDnsProviderSchema,\n\tCustomDnsProviderSchema,\n\tDnsProviderSchema,\n\tGoDaddyDnsProviderSchema,\n\tHostingerDnsProviderSchema,\n\tManualDnsProviderSchema,\n\tRoute53DnsProviderSchema,\n} from '../workspace/schema';\n\nexport type HostingerDnsConfig = z.infer<typeof HostingerDnsProviderSchema>;\nexport type Route53DnsConfig = z.infer<typeof Route53DnsProviderSchema>;\nexport type GoDaddyDnsConfig = z.infer<typeof GoDaddyDnsProviderSchema>;\nexport type CloudflareDnsConfig = z.infer<typeof CloudflareDnsProviderSchema>;\nexport type ManualDnsConfig = z.infer<typeof ManualDnsProviderSchema>;\nexport type CustomDnsConfig = z.infer<typeof CustomDnsProviderSchema>;\n/** Single DNS provider config (for one domain) */\nexport type DnsConfig = z.infer<typeof DnsProviderSchema>;\n\n/**\n * The GoDaddy provider's options as the CLI takes them: its token as given,\n * or else read from the environment (`env`) or the CLI's home (`home`).\n */\nexport type GoDaddyOptions = Omit<GoDaddyProviderOptions, 'credential'> & {\n\tcredential?: GoDaddyCredential;\n\tenv?: NodeJS.ProcessEnv;\n\thome?: string;\n};\n\nexport interface CreateDnsProviderOptions {\n\t/** DNS config from workspace */\n\tconfig: DnsConfig;\n\t/**\n\t * The GoDaddy provider's options. Its token is the one given, or else the\n\t * one stored or in the environment (`env`, the CLI's `home`), read the\n\t * first time the API is called.\n\t */\n\tgodaddy?: GoDaddyOptions;\n\t/** The Hostinger token, when the caller already has it. */\n\thostinger?: HostingerCredential;\n\t/**\n\t * The Cloudflare token, when the caller already has it; otherwise the one\n\t * in the environment or stored (`cloudflareFrom`), read the first time\n\t * the API is called.\n\t */\n\tcloudflare?: CloudflareCredential;\n\t/** Where an absent Cloudflare token is looked for. */\n\tcloudflareFrom?: { env?: NodeJS.ProcessEnv; home?: string };\n\t/** Cloudflare's API base URL, for tests. */\n\tcloudflareBaseUrl?: string;\n}\n\n/**\n * Create a DNS provider based on configuration.\n *\n * - 'hostinger': HostingerProvider\n * - 'route53': Route53Provider\n * - 'godaddy': GoDaddyProvider\n * - 'cloudflare': CloudflareProvider\n * - 'manual': Returns null (user handles DNS)\n * - Custom: Use provided DnsProvider implementation\n */\nexport async function createDnsProvider(\n\toptions: CreateDnsProviderOptions,\n): Promise<DnsProvider | null> {\n\tconst { config } = options;\n\n\t// Manual mode - no provider needed\n\tif (config.provider === 'manual') {\n\t\treturn null;\n\t}\n\n\t// Custom provider implementation\n\tif (isDnsProvider(config.provider)) {\n\t\treturn config.provider;\n\t}\n\n\t// Built-in providers\n\tconst provider = config.provider;\n\n\tif (provider === 'hostinger') {\n\t\tconst { HostingerProvider } = await import('@geekmidas/edge/dns/hostinger');\n\t\treturn new HostingerProvider(async () => {\n\t\t\tconst token = options.hostinger?.token ?? (await getHostingerToken());\n\t\t\tif (!token) throw new MissingCredential('hostinger', undefined);\n\t\t\treturn { token };\n\t\t});\n\t}\n\n\tif (provider === 'route53') {\n\t\tconst { Route53Provider } = await import('@geekmidas/edge/dns/route53');\n\t\tconst route53Config = config as Route53DnsConfig;\n\t\treturn new Route53Provider({\n\t\t\tregion: route53Config.region,\n\t\t\tprofile: route53Config.profile,\n\t\t\thostedZoneId: route53Config.hostedZoneId,\n\t\t});\n\t}\n\n\tif (provider === 'godaddy') {\n\t\tconst { GoDaddyProvider } = await import('@geekmidas/edge/dns/godaddy');\n\t\tconst { credential, env, home, ...rest } = options.godaddy ?? {};\n\t\treturn new GoDaddyProvider({\n\t\t\t...rest,\n\t\t\tcredential: async () => {\n\t\t\t\tconst found =\n\t\t\t\t\tcredential ??\n\t\t\t\t\t(await storedCredentials({\n\t\t\t\t\t\tenv: env ?? process.env,\n\t\t\t\t\t\t...(home ? { home } : {}),\n\t\t\t\t\t}).get({ kind: 'godaddy' }));\n\t\t\t\tif (!found) throw new MissingCredential('godaddy', undefined);\n\t\t\t\treturn found;\n\t\t\t},\n\t\t});\n\t}\n\n\tif (provider === 'cloudflare') {\n\t\tconst { CloudflareProvider } = await import(\n\t\t\t'@geekmidas/edge/dns/cloudflare'\n\t\t);\n\t\tconst from = options.cloudflareFrom ?? {};\n\t\treturn new CloudflareProvider({\n\t\t\t...(options.cloudflareBaseUrl\n\t\t\t\t? { baseUrl: options.cloudflareBaseUrl }\n\t\t\t\t: {}),\n\t\t\tcredential: async () => {\n\t\t\t\tconst found =\n\t\t\t\t\toptions.cloudflare ??\n\t\t\t\t\t(await storedCredentials({\n\t\t\t\t\t\tenv: from.env ?? process.env,\n\t\t\t\t\t\t...(from.home ? { home: from.home } : {}),\n\t\t\t\t\t}).get({ kind: 'cloudflare' }));\n\t\t\t\tif (!found) throw new MissingCredential('cloudflare', undefined);\n\t\t\t\treturn found;\n\t\t\t},\n\t\t});\n\t}\n\n\tthrow new DnsProviderUnknown(config);\n}\n\n/** A `provider:` that is none of the built-ins, nor a DnsProvider object. */\nexport class DnsProviderUnknown extends GkmError {\n\tconstructor(readonly config: unknown) {\n\t\tsuper(\n\t\t\t`Unknown DNS provider: ${JSON.stringify(config)}. dns takes ` +\n\t\t\t\t\"'route53', 'godaddy', 'hostinger', 'cloudflare', 'manual', or an object implementing DnsProvider.\",\n\t\t);\n\t\tthis.name = 'DnsProviderUnknown';\n\t}\n}\n","/**\n * DNS orchestration for deployments\n *\n * Handles automatic DNS record creation for deployed applications.\n */\n\nimport { lookup } from 'node:dns/promises';\nimport type { DnsProvider, UpsertDnsRecord } from '@geekmidas/edge/dns';\nimport {\n\ttype DokployStageState,\n\tisDnsVerified,\n\tsetDnsRecord,\n\tsetDnsVerification,\n} from '../deploy/state';\nimport { output } from '../output';\nimport type {\n\tDnsConfig,\n\tDnsProvider as DnsProviderConfig,\n} from '../workspace/types';\nimport {\n\tcreateDnsProvider,\n\ttype DnsConfig as SchemaDnsConfig,\n} from './providers';\n\nconst logger = output;\n\n/**\n * Check if DNS config is legacy format (single domain with `domain` property)\n */\nexport function isLegacyDnsConfig(\n\tconfig: DnsConfig,\n): config is SchemaDnsConfig & { domain: string } {\n\treturn (\n\t\ttypeof config === 'object' &&\n\t\tconfig !== null &&\n\t\t'provider' in config &&\n\t\t'domain' in config\n\t);\n}\n\n/**\n * Normalize DNS config to new multi-domain format\n */\nexport function normalizeDnsConfig(\n\tconfig: DnsConfig,\n): Record<string, DnsProviderConfig> {\n\tif (isLegacyDnsConfig(config)) {\n\t\t// Convert legacy format to new format\n\t\tconst { domain, ...providerConfig } = config;\n\t\treturn { [domain]: providerConfig as DnsProviderConfig };\n\t}\n\treturn config as Record<string, DnsProviderConfig>;\n}\n\n/**\n * Find the root domain for a hostname from available DNS configs\n *\n * @example\n * findRootDomain('api.geekmidas.com', { 'geekmidas.com': {...}, 'geekmidas.dev': {...} })\n * // Returns 'geekmidas.com'\n */\nexport function findRootDomain(\n\thostname: string,\n\tdnsConfig: Record<string, DnsProviderConfig>,\n): string | null {\n\t// Sort domains by length descending to match most specific first\n\tconst domains = Object.keys(dnsConfig).sort((a, b) => b.length - a.length);\n\n\tfor (const domain of domains) {\n\t\tif (hostname === domain || hostname.endsWith(`.${domain}`)) {\n\t\t\treturn domain;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Group hostnames by their root domain\n */\nexport function groupHostnamesByDomain(\n\tappHostnames: Map<string, string>,\n\tdnsConfig: Record<string, DnsProviderConfig>,\n): Map<string, Map<string, string>> {\n\tconst grouped = new Map<string, Map<string, string>>();\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\tconst rootDomain = findRootDomain(hostname, dnsConfig);\n\t\tif (!rootDomain) {\n\t\t\tlogger.log(` ⚠ No DNS config found for hostname: ${hostname}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!grouped.has(rootDomain)) {\n\t\t\tgrouped.set(rootDomain, new Map());\n\t\t}\n\t\tgrouped.get(rootDomain)!.set(appName, hostname);\n\t}\n\n\treturn grouped;\n}\n\n/**\n * Required DNS record for an app\n */\nexport interface RequiredDnsRecord {\n\t/** Full hostname (e.g., 'api.joemoer.traflabs.io') */\n\thostname: string;\n\t/** Subdomain part for the DNS provider (e.g., 'api.joemoer') */\n\tsubdomain: string;\n\t/** Record type */\n\ttype: 'A' | 'CNAME';\n\t/** Target value (IP or hostname) */\n\tvalue: string;\n\t/** App name */\n\tappName: string;\n\t/** Whether the record was created */\n\tcreated?: boolean;\n\t/** Whether the record already existed */\n\texisted?: boolean;\n\t/** Error if creation failed */\n\terror?: string;\n}\n\n/**\n * Result of DNS record creation\n */\nexport interface DnsCreationResult {\n\trecords: RequiredDnsRecord[];\n\tsuccess: boolean;\n\tserverIp: string;\n}\n\n/**\n * Resolve IP address from a hostname\n */\nexport async function resolveHostnameToIp(hostname: string): Promise<string> {\n\ttry {\n\t\tconst addresses = await lookup(hostname, { family: 4 });\n\t\treturn addresses.address;\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Failed to resolve IP for ${hostname}: ${error instanceof Error ? error.message : 'Unknown error'}`,\n\t\t);\n\t}\n}\n\n/**\n * Extract subdomain from full hostname relative to root domain\n *\n * @example\n * extractSubdomain('api.joemoer.traflabs.io', 'traflabs.io') => 'api.joemoer'\n * extractSubdomain('joemoer.traflabs.io', 'traflabs.io') => 'joemoer'\n */\nexport function extractSubdomain(hostname: string, rootDomain: string): string {\n\tif (!hostname.endsWith(rootDomain)) {\n\t\tthrow new Error(\n\t\t\t`Hostname ${hostname} is not under root domain ${rootDomain}`,\n\t\t);\n\t}\n\n\tconst subdomain = hostname.slice(0, -(rootDomain.length + 1)); // +1 for the dot\n\treturn subdomain || '@'; // '@' represents the root domain itself\n}\n\n/**\n * Generate required DNS records for a deployment\n */\nexport function generateRequiredRecords(\n\tappHostnames: Map<string, string>, // appName -> hostname\n\trootDomain: string,\n\tserverIp: string,\n): RequiredDnsRecord[] {\n\tconst records: RequiredDnsRecord[] = [];\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\tconst subdomain = extractSubdomain(hostname, rootDomain);\n\t\trecords.push({\n\t\t\thostname,\n\t\t\tsubdomain,\n\t\t\ttype: 'A',\n\t\t\tvalue: serverIp,\n\t\t\tappName,\n\t\t});\n\t}\n\n\treturn records;\n}\n\n/**\n * Print DNS records table\n */\nexport function printDnsRecordsTable(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n): void {\n\tlogger.log(`\\n 📋 DNS Records for ${rootDomain}:`);\n\tlogger.log(\n\t\t' ┌─────────────────────────────────────┬──────┬─────────────────┬────────┐',\n\t);\n\tlogger.log(\n\t\t' │ Subdomain │ Type │ Value │ Status │',\n\t);\n\tlogger.log(\n\t\t' ├─────────────────────────────────────┼──────┼─────────────────┼────────┤',\n\t);\n\n\tfor (const record of records) {\n\t\tconst subdomain = record.subdomain.padEnd(35);\n\t\tconst type = record.type.padEnd(4);\n\t\tconst value = record.value.padEnd(15);\n\t\tlet status: string;\n\n\t\tif (record.error) {\n\t\t\tstatus = '✗';\n\t\t} else if (record.created) {\n\t\t\tstatus = '✓ new';\n\t\t} else if (record.existed) {\n\t\t\tstatus = '✓';\n\t\t} else {\n\t\t\tstatus = '?';\n\t\t}\n\n\t\tlogger.log(\n\t\t\t` │ ${subdomain} │ ${type} │ ${value} │ ${status.padEnd(6)} │`,\n\t\t);\n\t}\n\n\tlogger.log(\n\t\t' └─────────────────────────────────────┴──────┴─────────────────┴────────┘',\n\t);\n}\n\n/**\n * Print DNS records in a simple format for manual setup\n */\nexport function printDnsRecordsSimple(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n): void {\n\tlogger.log('\\n 📋 Required DNS Records:');\n\tlogger.log(` Add these A records to your DNS provider (${rootDomain}):\\n`);\n\n\tfor (const record of records) {\n\t\tlogger.log(` ${record.subdomain} → ${record.value} (A record)`);\n\t}\n\n\tlogger.log('');\n}\n\n/**\n * Create DNS records for a single domain using its configured provider\n */\nexport async function createDnsRecordsForDomain(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n\tproviderConfig: DnsProviderConfig,\n): Promise<RequiredDnsRecord[]> {\n\t// Get TTL from config, default to 300. Manual mode doesn't have ttl property.\n\tconst ttl =\n\t\t'ttl' in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300;\n\n\t// Get DNS provider from factory\n\tlet provider: DnsProvider | null;\n\ttry {\n\t\t// Cast to schema-derived DnsConfig for provider factory\n\t\tprovider = await createDnsProvider({\n\t\t\tconfig: providerConfig as SchemaDnsConfig,\n\t\t});\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(\n\t\t\t` ⚠ Failed to create DNS provider for ${rootDomain}: ${message}`,\n\t\t);\n\t\treturn records.map((r) => ({ ...r, error: message }));\n\t}\n\n\t// Manual mode - no provider, just mark records as needing manual creation\n\tif (!provider) {\n\t\treturn records.map((r) => ({ ...r, created: false, existed: false }));\n\t}\n\n\tconst results: RequiredDnsRecord[] = [];\n\n\t// Convert RequiredDnsRecord to UpsertDnsRecord format\n\tconst upsertRecords: UpsertDnsRecord[] = records.map((r) => ({\n\t\tname: r.subdomain,\n\t\ttype: r.type,\n\t\tttl,\n\t\tvalue: r.value,\n\t}));\n\n\ttry {\n\t\t// Use provider to upsert records\n\t\tconst upsertResults = await provider.upsertRecords(\n\t\t\trootDomain,\n\t\t\tupsertRecords,\n\t\t);\n\n\t\t// Map results back to RequiredDnsRecord format\n\t\tfor (const [i, record] of records.entries()) {\n\t\t\tconst result = upsertResults[i];\n\n\t\t\t// Handle case where upsertResults has fewer items (shouldn't happen but be safe)\n\t\t\tif (!result) {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\terror: 'No result returned from provider',\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (result.unchanged) {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\texisted: true,\n\t\t\t\t\tcreated: false,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\tcreated: result.created,\n\t\t\t\t\texisted: !result.created,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(\n\t\t\t` ⚠ Failed to create DNS records for ${rootDomain}: ${message}`,\n\t\t);\n\t\treturn records.map((r) => ({\n\t\t\thostname: r.hostname,\n\t\t\tsubdomain: r.subdomain,\n\t\t\ttype: r.type,\n\t\t\tvalue: r.value,\n\t\t\tappName: r.appName,\n\t\t\terror: message,\n\t\t}));\n\t}\n\n\treturn results;\n}\n\n/**\n * Create DNS records using the configured provider\n * @deprecated Use createDnsRecordsForDomain for multi-domain support\n */\nexport async function createDnsRecords(\n\trecords: RequiredDnsRecord[],\n\tdnsConfig: DnsConfig,\n): Promise<RequiredDnsRecord[]> {\n\t// Handle legacy config format\n\tif (!isLegacyDnsConfig(dnsConfig)) {\n\t\tthrow new Error(\n\t\t\t'createDnsRecords requires legacy DnsConfig with domain property. Use createDnsRecordsForDomain instead.',\n\t\t);\n\t}\n\tconst { domain: rootDomain, ...providerConfig } = dnsConfig;\n\treturn createDnsRecordsForDomain(\n\t\trecords,\n\t\trootDomain,\n\t\tproviderConfig as DnsProviderConfig,\n\t);\n}\n\n/**\n * Main DNS orchestration function for deployments\n *\n * Supports both legacy single-domain format and new multi-domain format:\n * - Legacy: { provider: 'hostinger', domain: 'example.com' }\n * - Multi: { 'example.com': { provider: 'hostinger' }, 'example.dev': { provider: 'route53' } }\n *\n * @param appHostnames - Map of app names to hostnames\n * @param dnsConfig - DNS configuration (legacy or multi-domain)\n * @param dokployEndpoint - Dokploy server endpoint to resolve IP from\n * @param state - Optional state to save created records for later deletion\n */\nexport async function orchestrateDns(\n\tappHostnames: Map<string, string>, // appName -> hostname\n\tdnsConfig: DnsConfig | undefined,\n\tdokployEndpoint: string,\n\tstate?: DokployStageState,\n): Promise<DnsCreationResult | null> {\n\tif (!dnsConfig) {\n\t\treturn null;\n\t}\n\n\t// Normalize config to multi-domain format\n\tconst normalizedConfig = normalizeDnsConfig(dnsConfig);\n\n\t// Resolve Dokploy server IP from endpoint\n\tlogger.log('\\n🌐 Setting up DNS records...');\n\tlet serverIp: string;\n\n\ttry {\n\t\tconst endpointUrl = new URL(dokployEndpoint);\n\t\tserverIp = await resolveHostnameToIp(endpointUrl.hostname);\n\t\tlogger.log(` Server IP: ${serverIp} (from ${endpointUrl.hostname})`);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(` ⚠ Failed to resolve server IP: ${message}`);\n\t\treturn null;\n\t}\n\n\t// Group hostnames by their root domain\n\tconst groupedHostnames = groupHostnamesByDomain(\n\t\tappHostnames,\n\t\tnormalizedConfig,\n\t);\n\n\tif (groupedHostnames.size === 0) {\n\t\tlogger.log(\n\t\t\t' No DNS records needed (no hostnames match configured domains)',\n\t\t);\n\t\treturn { records: [], success: true, serverIp };\n\t}\n\n\tconst allRecords: RequiredDnsRecord[] = [];\n\tlet hasFailures = false;\n\n\t// Process each domain group with its specific provider\n\tfor (const [rootDomain, domainHostnames] of groupedHostnames) {\n\t\tconst providerConfig = normalizedConfig[rootDomain];\n\t\tif (!providerConfig) {\n\t\t\tlogger.log(` ⚠ No provider config for ${rootDomain}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst providerName =\n\t\t\ttypeof providerConfig.provider === 'string'\n\t\t\t\t? providerConfig.provider\n\t\t\t\t: 'custom';\n\n\t\t// Generate required records for this domain\n\t\tconst requiredRecords = generateRequiredRecords(\n\t\t\tdomainHostnames,\n\t\t\trootDomain,\n\t\t\tserverIp,\n\t\t);\n\n\t\tif (requiredRecords.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Create records for this domain\n\t\tlogger.log(\n\t\t\t` Creating DNS records for ${rootDomain} (${providerName})...`,\n\t\t);\n\t\tconst domainRecords = await createDnsRecordsForDomain(\n\t\t\trequiredRecords,\n\t\t\trootDomain,\n\t\t\tproviderConfig,\n\t\t);\n\n\t\tallRecords.push(...domainRecords);\n\n\t\tconst created = domainRecords.filter((r) => r.created).length;\n\t\tconst existed = domainRecords.filter((r) => r.existed).length;\n\t\tconst failed = domainRecords.filter((r) => r.error).length;\n\n\t\tif (created > 0) {\n\t\t\tlogger.log(` ✓ Created ${created} DNS record(s) for ${rootDomain}`);\n\t\t}\n\t\tif (existed > 0) {\n\t\t\tlogger.log(` ✓ ${existed} record(s) already exist for ${rootDomain}`);\n\t\t}\n\t\tif (failed > 0) {\n\t\t\tlogger.log(` ⚠ ${failed} record(s) failed for ${rootDomain}`);\n\t\t\thasFailures = true;\n\t\t}\n\n\t\t// Save created/existing records to state for later deletion during undeploy\n\t\tif (state) {\n\t\t\tfor (const record of domainRecords) {\n\t\t\t\tif (record.created || record.existed) {\n\t\t\t\t\tsetDnsRecord(state, {\n\t\t\t\t\t\tdomain: rootDomain,\n\t\t\t\t\t\tname: record.subdomain,\n\t\t\t\t\t\ttype: record.type,\n\t\t\t\t\t\tvalue: record.value,\n\t\t\t\t\t\tttl:\n\t\t\t\t\t\t\t'ttl' in providerConfig && providerConfig.ttl\n\t\t\t\t\t\t\t\t? providerConfig.ttl\n\t\t\t\t\t\t\t\t: 300,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Print summary table for this domain\n\t\tprintDnsRecordsTable(domainRecords, rootDomain);\n\n\t\t// If manual mode or some failed, print simple instructions\n\t\tif (providerConfig.provider === 'manual' || failed > 0) {\n\t\t\tprintDnsRecordsSimple(\n\t\t\t\tdomainRecords.filter((r) => !r.created && !r.existed),\n\t\t\t\trootDomain,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn {\n\t\trecords: allRecords,\n\t\tsuccess: !hasFailures,\n\t\tserverIp,\n\t};\n}\n\n/**\n * Result of DNS verification for a single hostname\n */\nexport interface DnsVerificationResult {\n\thostname: string;\n\tappName: string;\n\tverified: boolean;\n\tresolvedIp?: string;\n\texpectedIp: string;\n\terror?: string;\n\tskipped?: boolean; // True if already verified in state\n}\n\n/**\n * Verify DNS records resolve correctly after deployment.\n *\n * This function:\n * 1. Checks state for previously verified hostnames (skips if already verified with same IP)\n * 2. Attempts to resolve each hostname to an IP\n * 3. Compares resolved IP with expected server IP\n * 4. Updates state with verification results\n *\n * @param appHostnames - Map of app names to hostnames\n * @param serverIp - Expected IP address the hostnames should resolve to\n * @param state - Deploy state for caching verification results\n * @returns Array of verification results\n */\nexport async function verifyDnsRecords(\n\tappHostnames: Map<string, string>,\n\tserverIp: string,\n\tstate: DokployStageState,\n): Promise<DnsVerificationResult[]> {\n\tconst results: DnsVerificationResult[] = [];\n\n\tlogger.log('\\n🔍 Verifying DNS records...');\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\t// Check if already verified with same IP\n\t\tif (isDnsVerified(state, hostname, serverIp)) {\n\t\t\tlogger.log(` ✓ ${hostname} (previously verified)`);\n\t\t\tresults.push({\n\t\t\t\thostname,\n\t\t\t\tappName,\n\t\t\t\tverified: true,\n\t\t\t\texpectedIp: serverIp,\n\t\t\t\tskipped: true,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Attempt to resolve hostname\n\t\ttry {\n\t\t\tconst resolvedIp = await resolveHostnameToIp(hostname);\n\n\t\t\tif (resolvedIp === serverIp) {\n\t\t\t\t// DNS verified successfully\n\t\t\t\tsetDnsVerification(state, hostname, serverIp);\n\t\t\t\tlogger.log(` ✓ ${hostname} → ${resolvedIp}`);\n\t\t\t\tresults.push({\n\t\t\t\t\thostname,\n\t\t\t\t\tappName,\n\t\t\t\t\tverified: true,\n\t\t\t\t\tresolvedIp,\n\t\t\t\t\texpectedIp: serverIp,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// DNS resolves but to wrong IP\n\t\t\t\tlogger.log(\n\t\t\t\t\t` ⚠ ${hostname} resolves to ${resolvedIp}, expected ${serverIp}`,\n\t\t\t\t);\n\t\t\t\tresults.push({\n\t\t\t\t\thostname,\n\t\t\t\t\tappName,\n\t\t\t\t\tverified: false,\n\t\t\t\t\tresolvedIp,\n\t\t\t\t\texpectedIp: serverIp,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// DNS resolution failed\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\t\tlogger.log(` ⚠ ${hostname} DNS not propagated (${message})`);\n\t\t\tresults.push({\n\t\t\t\thostname,\n\t\t\t\tappName,\n\t\t\t\tverified: false,\n\t\t\t\texpectedIp: serverIp,\n\t\t\t\terror: message,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Summary\n\tconst verified = results.filter((r) => r.verified).length;\n\tconst skipped = results.filter((r) => r.skipped).length;\n\tconst pending = results.filter((r) => !r.verified).length;\n\n\tif (pending > 0) {\n\t\tlogger.log(`\\n ${verified} verified, ${pending} pending propagation`);\n\t\tlogger.log(' DNS changes may take 5-30 minutes to propagate');\n\t} else if (skipped > 0) {\n\t\tlogger.log(` ${verified} verified (${skipped} from cache)`);\n\t}\n\n\treturn results;\n}\n","/**\n * What the server's shared Traefik edge answers Let's Encrypt's DNS\n * challenge with, for a stage with a wildcard site: which provider holds the\n * stage's domain, and the edge's key for it.\n *\n * Every provider but Route 53 is handed the stage's own secrets\n * (`ACME_DNS_CHALLENGES` in `@geekmidas/edge/proxy/traefik` names them):\n * each is written into its own file in the edge's container, `0600`, and\n * rewritten — the edge restarted to read it — when the stage's value\n * changes. Route 53's is issued here, through IAM:\n *\n * A wildcard certificate is issued only over the DNS challenge: the edge\n * proves it holds `<domain>` by writing a TXT record at\n * `_acme-challenge.<domain>`. So it needs a key that can write that record —\n * and nothing else, because it lives on the server.\n *\n * - **The user**: one per server, under `/gkm/`, tagged with the server it\n * is for. One that exists without that tag is someone else's, and is\n * refused rather than taken over.\n * - **Its policies**: one per stack on the server, named for its compose\n * project, allowing `ChangeResourceRecordSets` on the stage's hosted zone\n * for TXT records named `_acme-challenge.<domain>` alone — plus what\n * finding the zone and waiting for the change take, which read and write\n * nothing. Put back on every deploy.\n * - **Its key**: written into the edge's container, never into the stage's\n * secrets or onto the machine running the deploy. Issued when the edge\n * has none, or holds one IAM no longer knows — and then the edge is\n * restarted, since it keeps the key it first read.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { IAMClient } from '@aws-sdk/client-iam';\nimport type { Route53Client } from '@aws-sdk/client-route-53';\nimport {\n\tACME_DNS_CHALLENGES,\n\ttype AcmeDnsProvider,\n\tEDGE_AWS_CREDENTIALS,\n\tEDGE_PROJECT,\n\tedgeDnsSecretPath,\n\tisAcmeDnsProvider,\n} from '@geekmidas/edge/proxy/traefik';\nimport { findRootDomain, normalizeDnsConfig } from '../dns/index';\nimport { GkmError } from '../errors';\nimport type {\n\tDnsProvider as DnsProviderConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types';\nimport type { ComposeDocker, StackRef } from './docker.js';\nimport { readEdgeFile, restartEdge, writeEdgeSecret } from './edge.js';\n\n/**\n * Where a stage's wildcard certificate is challenged: its domain, the root\n * domain in `dns` that holds it, and that entry — for a provider the edge\n * can answer the DNS challenge through.\n */\nexport interface AcmeDnsZone {\n\tdomain: string;\n\tzone: string;\n\tprovider: AcmeDnsProvider;\n\tconfig: DnsProviderConfig;\n}\n\n/**\n * The stage's DNS-challenge zone, or undefined where its domain has no `dns`\n * entry the edge can answer the challenge through. The one answer the stack\n * (which resolver its wildcard router names) and the deploy (which key it\n * gives the edge) both read.\n */\nexport function acmeDnsZone(\n\tworkspace: Pick<NormalizedWorkspace, 'domains' | 'dns'>,\n\tstage: string,\n): AcmeDnsZone | undefined {\n\tconst domain = workspace.domains?.[stage];\n\tif (!domain) return undefined;\n\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\tconst zone = findRootDomain(domain, dns);\n\tconst config = zone ? dns[zone] : undefined;\n\tif (!zone || !config || !isAcmeDnsProvider(config.provider)) {\n\t\treturn undefined;\n\t}\n\treturn { domain, zone, provider: config.provider, config };\n}\n\n/** A stage whose DNS provider's keys the edge needs, and its secrets lack. */\nexport class AcmeDnsSecretsMissing extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly provider: AcmeDnsProvider,\n\t\treadonly domain: string,\n\t\treadonly keys: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' has a wildcard site on ${domain}, whose certificate the ` +\n\t\t\t\t`shared edge gets over the DNS challenge through ${provider}, and ` +\n\t\t\t\t`its secrets lack ${keys.join(' and ')}. Set ${keys.length > 1 ? 'them' : 'it'}:\\n` +\n\t\t\t\tkeys\n\t\t\t\t\t.map((key) => ` gkm secrets:set ${key} '<value>' --stage ${stage}`)\n\t\t\t\t\t.join('\\n') +\n\t\t\t\t`\\nThey are written into the edge alone, never handed to an app.`,\n\t\t);\n\t\tthis.name = 'AcmeDnsSecretsMissing';\n\t}\n}\n\n/**\n * The stage's values for what `provider`'s DNS challenge reads.\n *\n * @throws {AcmeDnsSecretsMissing} when the stage lacks any of them\n */\nexport function acmeDnsSecrets(\n\tzone: Pick<AcmeDnsZone, 'provider' | 'domain'>,\n\tstage: string,\n\tcustom: Readonly<Record<string, string>> = {},\n): Record<string, string> {\n\tconst keys: readonly string[] = ACME_DNS_CHALLENGES[zone.provider].secrets;\n\tconst missing = keys.filter((key) => !custom[key]);\n\tif (missing.length > 0) {\n\t\tthrow new AcmeDnsSecretsMissing(stage, zone.provider, zone.domain, missing);\n\t}\n\treturn Object.fromEntries(keys.map((key) => [key, custom[key]!]));\n}\n\nexport interface EnsureEdgeDnsSecretsOptions {\n\t/** The edge's compose project, as docker is asked about it. */\n\tedge: StackRef;\n\tzone: Pick<AcmeDnsZone, 'provider' | 'domain'>;\n\tstage: string;\n\t/** The stage's own secrets. */\n\tcustom: Readonly<Record<string, string>> | undefined;\n\tdryRun?: boolean;\n\tlog?: (line: string) => void;\n}\n\n/**\n * The stage's keys for its DNS provider, in the edge: each written to its\n * own file where the edge reads it (`<KEY>_FILE`), and the edge restarted\n * when one it may already have read is replaced. A key the edge holds as it\n * is, is left alone.\n *\n * @throws {AcmeDnsSecretsMissing} when the stage lacks one\n * @returns whether anything was written\n */\nexport async function ensureEdgeDnsSecrets(\n\tdocker: ComposeDocker,\n\toptions: EnsureEdgeDnsSecretsOptions,\n): Promise<boolean> {\n\tconst { edge, zone, stage } = options;\n\tconst log = options.log ?? ((line: string) => console.log(line));\n\tconst values = acmeDnsSecrets(zone, stage, options.custom);\n\tconst keys = Object.keys(values);\n\tif (keys.length === 0) return false;\n\n\tif (options.dryRun) {\n\t\tlog(\n\t\t\t`🔑 Would give ${EDGE_PROJECT} ${keys.join(', ')} for _acme-challenge.${zone.domain} through ${zone.provider} (dry run — nothing is written)`,\n\t\t);\n\t\treturn false;\n\t}\n\n\tlet written = false;\n\tlet replaced = false;\n\tfor (const [key, value] of Object.entries(values)) {\n\t\tconst path = edgeDnsSecretPath(key);\n\t\tconst held = await readEdgeFile(docker, edge, path);\n\t\tif (held === value) continue;\n\t\tawait writeEdgeSecret(docker, edge, path, value);\n\t\twritten = true;\n\t\tif (held !== undefined) replaced = true;\n\t}\n\tif (written) {\n\t\tlog(\n\t\t\t`🔑 Wrote ${keys.join(', ')} to ${EDGE_PROJECT}, for _acme-challenge.${zone.domain} through ${zone.provider}`,\n\t\t);\n\t}\n\t// The edge reads a provider's keys once, the first time it asks for a\n\t// certificate through it, and keeps them.\n\tif (replaced) await restartEdge(docker, edge);\n\treturn written;\n}\n\n/** Where gkm's IAM users live. */\nconst USER_PATH = '/gkm/';\n\n/** The tag a server's edge user is found by. */\nexport const TAG_EDGE = 'gkm:edge';\n\n/** What the key is issued and its zone found through. */\nexport interface AcmeDnsClients {\n\tiam: IAMClient;\n\troute53: Route53Client;\n}\n\n/** The edge user's name for a server: stable, and safe for IAM. */\nexport function edgeAcmeUser(server: string): string {\n\tconst hash = createHash('sha256').update(server).digest('hex').slice(0, 12);\n\treturn `gkm-edge-acme-${hash}`;\n}\n\n/**\n * What one stage's wildcard certificate needs: its challenge record written\n * in its zone, the change waited on, and the zone found by name — which is\n * how the edge's ACME client finds it.\n */\nexport function acmeDnsPolicy(zoneId: string, domain: string): string {\n\treturn JSON.stringify({\n\t\tVersion: '2012-10-17',\n\t\tStatement: [\n\t\t\t{\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: 'route53:ChangeResourceRecordSets',\n\t\t\t\tResource: `arn:aws:route53:::hostedzone/${zoneId}`,\n\t\t\t\tCondition: {\n\t\t\t\t\t'ForAllValues:StringEquals': {\n\t\t\t\t\t\t'route53:ChangeResourceRecordSetsNormalizedRecordNames': [\n\t\t\t\t\t\t\t`_acme-challenge.${domain.toLowerCase()}`,\n\t\t\t\t\t\t],\n\t\t\t\t\t\t'route53:ChangeResourceRecordSetsRecordTypes': ['TXT'],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: 'route53:ListResourceRecordSets',\n\t\t\t\tResource: `arn:aws:route53:::hostedzone/${zoneId}`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: 'route53:GetChange',\n\t\t\t\tResource: 'arn:aws:route53:::change/*',\n\t\t\t},\n\t\t\t{\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: 'route53:ListHostedZonesByName',\n\t\t\t\tResource: '*',\n\t\t\t},\n\t\t],\n\t});\n}\n\n/** An IAM user by the edge user's name that gkm did not create for this server. */\nexport class EdgeAcmeUserNotOwned extends GkmError {\n\tconstructor(\n\t\treadonly user: string,\n\t\treadonly server: string,\n\t) {\n\t\tsuper(\n\t\t\t`The IAM user ${user} exists but is not tagged ${TAG_EDGE}=${server}, ` +\n\t\t\t\t`so gkm will not take it over to write the shared edge's DNS ` +\n\t\t\t\t`challenge records. Delete it, or tag it ${TAG_EDGE}=${server} if it ` +\n\t\t\t\t`is the one gkm created for this server.`,\n\t\t);\n\t\tthis.name = 'EdgeAcmeUserNotOwned';\n\t}\n}\n\n/** A wildcard site's domain with no Route 53 hosted zone to answer it in. */\nexport class AcmeHostedZoneMissing extends GkmError {\n\tconstructor(readonly domain: string) {\n\t\tsuper(\n\t\t\t`No Route 53 hosted zone holds ${domain}, so the shared edge cannot ` +\n\t\t\t\t`answer the DNS challenge for its wildcard certificate. Create the ` +\n\t\t\t\t`zone, or set hostedZoneId in its dns entry.`,\n\t\t);\n\t\tthis.name = 'AcmeHostedZoneMissing';\n\t}\n}\n\nexport interface EnsureEdgeAcmeKeyOptions {\n\tclients: AcmeDnsClients;\n\t/** The edge's compose project, as docker is asked about it. */\n\tedge: StackRef;\n\t/** What identifies the server: its public IPv4 address, or its SSH host. */\n\tserver: string;\n\t/** The stack's compose project: what its policy is named. */\n\tproject: string;\n\t/** The stage's domain, under which its tenants' hosts sit. */\n\tdomain: string;\n\t/** The root domain in `dns` — the zone's name. */\n\tzone: string;\n\t/** The zone's id, where its `dns` entry names one. */\n\thostedZoneId?: string;\n\tdryRun?: boolean;\n\tlog?: (line: string) => void;\n}\n\nexport interface EdgeAcmeKey {\n\tuser: string;\n\tzoneId: string;\n\t/** Whether a key was issued and written to the edge on this run. */\n\tissued: boolean;\n}\n\n/**\n * The edge's key for `domain`'s challenge record: its user, this stack's\n * policy on it, and a key in the edge that IAM knows.\n *\n * @throws {EdgeAcmeUserNotOwned} when the user is someone else's\n * @throws {AcmeHostedZoneMissing} when no hosted zone holds the domain\n */\nexport async function ensureEdgeAcmeKey(\n\tdocker: ComposeDocker,\n\toptions: EnsureEdgeAcmeKeyOptions,\n): Promise<EdgeAcmeKey> {\n\tconst { clients, edge, server, project, domain } = options;\n\tconst log = options.log ?? ((line: string) => console.log(line));\n\tconst IAM = await import('@aws-sdk/client-iam');\n\tconst user = edgeAcmeUser(server);\n\tconst zoneId =\n\t\toptions.hostedZoneId ?? (await hostedZoneId(clients.route53, options.zone));\n\tif (!zoneId) throw new AcmeHostedZoneMissing(domain);\n\n\tif (options.dryRun) {\n\t\tlog(\n\t\t\t`🔑 Would let ${EDGE_PROJECT} write _acme-challenge.${domain} TXT records in ${zoneId}, as IAM user ${user} (dry run — nothing is written)`,\n\t\t);\n\t\treturn { user, zoneId, issued: false };\n\t}\n\n\tconst existing = await clients.iam\n\t\t.send(new IAM.GetUserCommand({ UserName: user }))\n\t\t.catch((error: { name?: string }) => {\n\t\t\tif (\n\t\t\t\terror?.name === 'NoSuchEntity' ||\n\t\t\t\terror?.name === 'NoSuchEntityException'\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\tif (!existing?.User) {\n\t\tawait clients.iam.send(\n\t\t\tnew IAM.CreateUserCommand({\n\t\t\t\tUserName: user,\n\t\t\t\tPath: USER_PATH,\n\t\t\t\tTags: [{ Key: TAG_EDGE, Value: server }],\n\t\t\t}),\n\t\t);\n\t} else {\n\t\tconst { Tags = [] } = await clients.iam.send(\n\t\t\tnew IAM.ListUserTagsCommand({ UserName: user }),\n\t\t);\n\t\tconst owned = Tags.some((t) => t.Key === TAG_EDGE && t.Value === server);\n\t\tif (!owned) throw new EdgeAcmeUserNotOwned(user, server);\n\t}\n\n\tawait clients.iam.send(\n\t\tnew IAM.PutUserPolicyCommand({\n\t\t\tUserName: user,\n\t\t\tPolicyName: project,\n\t\t\tPolicyDocument: acmeDnsPolicy(zoneId, domain),\n\t\t}),\n\t);\n\tlog(\n\t\t`🔑 ${EDGE_PROJECT} may write _acme-challenge.${domain} TXT records in ${zoneId}, and nothing else there, as IAM user ${user}`,\n\t);\n\n\tconst written = await readEdgeFile(docker, edge, EDGE_AWS_CREDENTIALS);\n\tconst held = written?.match(/aws_access_key_id\\s*=\\s*(\\S+)/)?.[1];\n\tconst { AccessKeyMetadata = [] } = await clients.iam.send(\n\t\tnew IAM.ListAccessKeysCommand({ UserName: user }),\n\t);\n\tif (held && AccessKeyMetadata.some((k) => k.AccessKeyId === held)) {\n\t\treturn { user, zoneId, issued: false };\n\t}\n\n\t// The edge holds none, or one IAM no longer has: every key of the user is\n\t// retired — it is the edge's alone — and one issued in its place.\n\tfor (const key of AccessKeyMetadata) {\n\t\tif (!key.AccessKeyId) continue;\n\t\tawait clients.iam.send(\n\t\t\tnew IAM.DeleteAccessKeyCommand({\n\t\t\t\tUserName: user,\n\t\t\t\tAccessKeyId: key.AccessKeyId,\n\t\t\t}),\n\t\t);\n\t}\n\tconst { AccessKey } = await clients.iam.send(\n\t\tnew IAM.CreateAccessKeyCommand({ UserName: user }),\n\t);\n\tawait writeEdgeSecret(\n\t\tdocker,\n\t\tedge,\n\t\tEDGE_AWS_CREDENTIALS,\n\t\t`# Written by gkm compose — the key ${EDGE_PROJECT} answers DNS challenges with.\n[default]\naws_access_key_id = ${AccessKey?.AccessKeyId}\naws_secret_access_key = ${AccessKey?.SecretAccessKey}\n`,\n\t);\n\tlog(\n\t\t`🔑 Wrote a new key for ${user} to ${EDGE_PROJECT} (${EDGE_AWS_CREDENTIALS})`,\n\t);\n\t// It replaced one the edge may already have read and kept.\n\tif (written !== undefined) await restartEdge(docker, edge);\n\treturn { user, zoneId, issued: true };\n}\n\n/** The id of the hosted zone named exactly `zone`, if there is one. */\nasync function hostedZoneId(\n\troute53: Route53Client,\n\tzone: string,\n): Promise<string | undefined> {\n\tconst { ListHostedZonesByNameCommand } = await import(\n\t\t'@aws-sdk/client-route-53'\n\t);\n\tconst name = zone.endsWith('.') ? zone : `${zone}.`;\n\tconst { HostedZones = [] } = await route53.send(\n\t\tnew ListHostedZonesByNameCommand({ DNSName: name, MaxItems: 1 }),\n\t);\n\tconst found = HostedZones.find((z) => z.Name === name);\n\treturn found?.Id?.replace('/hostedzone/', '');\n}\n","/**\n * A site served behind a password on some deployed stages — a `StaticSite`'s\n * `password`, naming a `RandomPassword` — so a staging build is not public\n * while it is being tried.\n *\n * The edge asks for it with HTTP basic auth, before a request reaches the\n * site: the browser prompts, and nothing of the site loads until the stage's\n * login is given. The user is the stage's name; the password is the\n * `RandomPassword`'s value on the stage, generated and kept like any other.\n * Only its bcrypt hash reaches the edge's config.\n *\n * Pure.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ConstructManifest, SiteDeclaration } from '@geekmidas/manifest';\nimport bcrypt from 'bcryptjs';\nimport { GkmError } from '../errors';\nimport { appKey } from '../workspace/derive.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/** The basic-auth login a site is served behind. */\nexport interface SiteAuth {\n\t/** The stage's name. */\n\tuser: string;\n\tpassword: string;\n\t/** The password's bcrypt hash — what the edge's config holds. */\n\thash: string;\n\t/** The stage secret the password is kept in: `SITE_PASSWORD`. */\n\tkey: string;\n}\n\n/** A site's `password` names a `RandomPassword` the manifest does not hold. */\nexport class SitePasswordNotDeclared extends GkmError {\n\tconstructor(\n\t\treadonly site: string,\n\t\treadonly secret: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${site}' is served behind the password '${secret}', and no ` +\n\t\t\t\t`RandomPassword '${secret}' was found. Export it from a constructs ` +\n\t\t\t\t`file, as any construct is: export const ${secret[0]!.toLowerCase()}${secret.slice(1)} = ` +\n\t\t\t\t`new RandomPassword('${secret}');`,\n\t\t);\n\t\tthis.name = 'SitePasswordNotDeclared';\n\t}\n}\n\n/** A site's `password` names a stage the workspace does not deploy. */\nexport class UnknownPasswordStage extends GkmError {\n\tconstructor(\n\t\treadonly site: string,\n\t\treadonly stage: string,\n\t\treadonly deployed: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${site}' is served behind a password on '${stage}', which is not ` +\n\t\t\t\t`one of the workspace's deployed stages (${deployed\n\t\t\t\t\t.map((s) => `'${s}'`)\n\t\t\t\t\t.join(', ')}). Name one of them in its password's stages.`,\n\t\t);\n\t\tthis.name = 'UnknownPasswordStage';\n\t}\n}\n\n/** A site behind a password, with none in the stage's secrets. */\nexport class SitePasswordMissing extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly key: string,\n\t) {\n\t\tsuper(\n\t\t\t`A site of '${stage}' is served behind a password, and the stage has ` +\n\t\t\t\t`no ${key} in its secrets. Run gkm compose --stage ${stage} once to ` +\n\t\t\t\t`generate it, or set one: gkm secrets:set ${key} '…' --stage ${stage}`,\n\t\t);\n\t\tthis.name = 'SitePasswordMissing';\n\t}\n}\n\n/**\n * A site behind a password on a stage it deploys through a target that cannot\n * ask for a login. Refused rather than ignored: ignored, the site would be\n * public while its construct says it is not.\n */\nexport class SitePasswordNeedsCompose extends GkmError {\n\tconstructor(\n\t\treadonly site: string,\n\t\treadonly stage: string,\n\t\treadonly target: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${site}' is served behind a password on '${stage}', and it deploys ` +\n\t\t\t\t`through '${target}', which cannot ask for one yet — only compose ` +\n\t\t\t\t`does. Remove ${stage} from its password's stages, or deploy it ` +\n\t\t\t\t`with compose.`,\n\t\t);\n\t\tthis.name = 'SitePasswordNeedsCompose';\n\t}\n}\n\n/**\n * The `RandomPassword` a site is served behind on `stage`, by its key —\n * `SITE_PASSWORD` — or `undefined` where the stage asks for none.\n *\n * @throws {SitePasswordNotDeclared} where the password is not in the manifest\n */\nexport function sitePasswordKey(\n\tmanifest: ConstructManifest,\n\tsite: SiteDeclaration,\n\tstage: string,\n): string | undefined {\n\tconst password = site.password;\n\tif (!password?.stages.includes(stage)) return undefined;\n\n\tconst secret = manifest[password.secret];\n\tconst key = secret?.kind === 'secret' ? secret.provides?.[0] : undefined;\n\tif (!key) throw new SitePasswordNotDeclared(site.id, password.secret);\n\treturn key;\n}\n\n/**\n * Before anything is deployed: every site behind a password names a deployed\n * stage and a declared `RandomPassword`, and one of `apps` behind it on\n * `stage` deploys through compose.\n *\n * @throws {UnknownPasswordStage}, {SitePasswordNotDeclared},\n * {SitePasswordNeedsCompose}\n */\nexport function assertSitePasswords(\n\tworkspace: Pick<NormalizedWorkspace, 'stages'>,\n\tmanifest: ConstructManifest,\n\tstage: string,\n\tapps: readonly string[],\n\ttarget: string,\n): void {\n\tfor (const site of Object.values(manifest)) {\n\t\tif (site.kind !== 'site' || !site.password) continue;\n\n\t\tfor (const named of site.password.stages) {\n\t\t\tif (!workspace.stages.deployed.includes(named)) {\n\t\t\t\tthrow new UnknownPasswordStage(\n\t\t\t\t\tsite.id,\n\t\t\t\t\tnamed,\n\t\t\t\t\tworkspace.stages.deployed,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst key = sitePasswordKey(manifest, site, stage);\n\t\tif (key && target !== 'compose' && apps.includes(appKey(site.id))) {\n\t\t\tthrow new SitePasswordNeedsCompose(site.id, stage, target);\n\t\t}\n\t}\n}\n\n/**\n * The login a site is served behind on `stage`, from the password kept under\n * `key`.\n *\n * The hash's salt is derived from the password, so the same password always\n * renders the same edge config: a deploy that changed nothing rewrites\n * nothing, and the proxy is not reloaded for it. A per-hash random salt\n * guards against a precomputed table of common passwords; a generated one is\n * 43 random characters, which no table holds.\n *\n * @throws {SitePasswordMissing} where the stage's secrets hold none\n */\nexport function siteAuth(\n\tstage: string,\n\tkey: string,\n\tcustom: Readonly<Record<string, string>>,\n): SiteAuth {\n\tconst password = custom[key];\n\tif (!password) throw new SitePasswordMissing(stage, key);\n\n\treturn {\n\t\tuser: stage,\n\t\tpassword,\n\t\thash: bcrypt.hashSync(password, saltFor(password)),\n\t\tkey,\n\t};\n}\n\n/** bcrypt's own base-64 alphabet, in which a salt is written. */\nconst BCRYPT_ALPHABET =\n\t'./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n/**\n * A bcrypt salt — `$2a$`, which Caddy and Traefik both read, at cost 10 —\n * derived from the password.\n */\nfunction saltFor(password: string): string {\n\tconst digest = createHash('sha256').update(password).digest();\n\tlet salt = '';\n\tfor (let i = 0; i < 22; i++) salt += BCRYPT_ALPHABET[digest[i]! % 64];\n\treturn `$2a$10$${salt}`;\n}\n","/**\n * The stack a workspace runs as for one stage — pure.\n *\n * Everything `gkm compose` writes is decided here, as data: the compose file,\n * the Caddyfile, one env file per process that reads one — each backend,\n * worker and site that runs a server — and the image each app runs. The\n * command around it reads the workspace, asks the registry, writes the files\n * and starts Docker; none of those decide anything, so all of it can be\n * asserted without a daemon.\n *\n * The values come from the same derivations every other target uses. The\n * plan is reconcile's `planFor`, the keys a process reads are\n * `processEnvKeys` — the rule `gkm dev` and `gkm exec` apply — and every URL\n * is `envFor`'s, with each app at its public address: a browser and a sibling\n * service reach an API by the same name, through the edge.\n */\n\nimport { createHash } from 'node:crypto';\nimport { join } from 'node:path';\nimport {\n\ttype LocalAuthorityPaths,\n\tlocalAuthorityPaths,\n} from '@geekmidas/edge/certificates/local';\nimport { CADDY_TLS_DIR, edgeCaddyfile } from '@geekmidas/edge/proxy/caddy';\nimport {\n\tACME_DNS_CHALLENGES,\n\tEDGE_NETWORK,\n\tedgeAlias,\n\tedgeCertificatePaths,\n\ttraefikDynamicFile,\n} from '@geekmidas/edge/proxy/traefik';\nimport {\n\ttype ComposeProxy,\n\tEDGE_LIMITS,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype EdgeWildcard,\n\tNOFILE,\n\trouteHosts,\n} from '@geekmidas/edge/routes';\nimport {\n\ttype ConstructManifest,\n\tEDGE_TOKEN_KEY,\n\tisWildcardSite,\n\tprovidedKeyFor,\n\tprovisionOrder,\n\ttype SiteDeclaration,\n\ttype WebSocketEdgeLimits,\n\tWILDCARD_SUBDOMAIN,\n} from '@geekmidas/manifest';\nimport { stageBackups } from '../backups/config.js';\nimport {\n\tBACKUPS_SERVICE,\n\tbackupsService,\n\ttype StackBackups,\n\tstackBackups,\n\twithArchiving,\n} from '../backups/service.js';\nimport {\n\ttype ProcessorUnit,\n\tprocessorUnits,\n\ttype WorkerUnit,\n\tworkerUnits,\n} from '../build/workers.js';\nimport {\n\ttype DevServiceUse,\n\tdevServicesUsed,\n\ttype ExternalServices,\n\texternalServices,\n\ttype ServiceDeclaration,\n\tstageServiceDeclarations,\n\tsuppliedOnly,\n} from '../deploy/devServices.js';\nimport { isMainFrontendApp, resolveHost } from '../deploy/domain.js';\nimport { type DeployIdentity, imageRef, stageTag } from '../deploy/identity.js';\nimport { nextBuildValues, nextRuntimeValues } from '../deploy/nextRelease.js';\nimport { validateImageRef } from '../docker/imageRef.js';\nimport {\n\tappDockerfile,\n\tprocessorDockerfile,\n\tworkerDockerfile,\n} from '../docker/index.js';\nimport { composeBuildPaths, type ImageLayout } from '../docker/layout.js';\nimport {\n\tLOCAL_CA_BUILD_SECRET,\n\tPRERENDER_RUN_ARG,\n\tPROCESSOR_PORT,\n\tTURBO_VERSION,\n\tWORKER_PORT,\n} from '../docker/templates.js';\nimport { GkmError } from '../errors';\nimport {\n\tobjectsRoute,\n\tSNS_SUBSCRIPTIONS_KEY,\n\tsubscriberRoute,\n} from '../generators/subscriberRoute.js';\nimport { gkmHome } from '../home';\nimport { stageProvider } from '../providers/config.js';\nimport { stageProviderNotes } from '../providers/notes.js';\nimport {\n\tORIGIN_VERIFY_HEADER,\n\toriginSecretKey,\n\tprocessorOriginHost,\n} from '../providers/processorOrigin.js';\nimport { servesOnCdn } from '../providers/s3/config.js';\nimport { plannedSignedOrigin } from '../providers/s3/plannedOrigin.js';\nimport { networkEnv, processEnvKeys } from '../reconcile/apps.js';\nimport { type ComposeService, composeFor } from '../reconcile/compose.js';\nimport { DEFAULT_IMAGES, portKeys } from '../reconcile/containers.js';\nimport type { BoundSubscriber } from '../reconcile/discover.js';\nimport { EMULATOR_ACCESS_KEY_ID } from '../reconcile/emulator.js';\nimport { type EnvOptions, localRolePassword } from '../reconcile/env.js';\nimport {\n\tINBOX_RELAY_TOKEN_KEY,\n\tinboxRelayWorker,\n\tinboxWebhookUrl,\n} from '../reconcile/inboxRelay.js';\nimport {\n\ttype ContainerCredentials,\n\tLOCAL_RABBITMQ_USER,\n\ttype LocalCredentials,\n\tpostgresSuperuser,\n} from '../reconcile/localCredentials.js';\nimport {\n\tminioWebhookEnv,\n\ttype ObjectWebhook,\n\twatchedBuckets,\n} from '../reconcile/objectEvents.js';\nimport { type Plan, type PlannedResource, planFor } from '../reconcile/plan.js';\nimport { bucketLifecycles, bucketPolicies } from '../reconcile/provision.js';\nimport {\n\thostFor,\n\thostsFor,\n\tLOCAL_TLD,\n\ttype ResourceHosts,\n} from '../reconcile/routes.js';\nimport { signedOrigins } from '../reconcile/signedOrigins.js';\nimport type { StageSecrets } from '../secrets/types.js';\nimport { NoDomainForStage } from '../target/dokploy/domain.js';\nimport {\n\totlpTelemetryEnv,\n\ttype ResolvedTelemetry,\n\tresolveStageTelemetry,\n\ttelemetryEnv,\n} from '../telemetry/config.js';\nimport {\n\tisTelemetryKey,\n\tscopeTelemetryEnv,\n\tstackTelemetry,\n\ttelemetryOf,\n\tusesTelemetry,\n} from '../telemetry/edges.js';\nimport { DEFAULT_EVENTS } from '../types.js';\nimport { appKey } from '../workspace/derive.js';\nimport { fileServerHost } from '../workspace/fileServerLabel.js';\nimport type {\n\tComposeTlsConfig,\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n\tS3ObjectsConfig,\n} from '../workspace/types.js';\nimport { acmeDnsZone } from './acmeDns.js';\nimport { isReservedStageKey } from './dnsConfig.js';\nimport type { AppImage } from './images.js';\nimport {\n\tLOGS_SERVICE,\n\tlogsOnPort,\n\tlogsPorts,\n\tlogsService,\n\ttype StackLogs,\n\tstackLogs,\n} from './logs.js';\nimport { LOGS_PORT } from './logsConfig.js';\nimport { certificateFor, proxyFor } from './proxy.js';\nimport {\n\tREDIS_SERVICE,\n\tredisService,\n\tSTACK_CACHE,\n\ttype StackRedis,\n\tstackRedis,\n} from './redis.js';\nimport {\n\tOFFLINE_BUILD_ADDRESS,\n\tofflineBuildHosts,\n\tpublicBuildValues,\n\trunsServer,\n} from './siteBuild.js';\nimport { type SiteAuth, siteAuth, sitePasswordKey } from './sitePassword.js';\n\n/** Where a stack's files are written, relative to the workspace root. */\nexport function stackDir(stage: string): string {\n\treturn `.gkm/compose/${stage}`;\n}\n\n/**\n * The compose project a stage's stack runs as.\n *\n * The deploy identity's scope, so two workspaces with one name in different\n * namespaces never share containers or volumes — and the stage, so a\n * machine can run two stages side by side.\n */\nexport function composeProject(identity: DeployIdentity): string {\n\treturn `${identity.scope}-${identity.stage}`;\n}\n\n/**\n * Containers this target does not run.\n *\n * The AWS emulator never applies: a stack is a server target, whose events\n * are pg-boss. Reconcile's Caddy fronts `gkm dev`'s host processes; the stack\n * brings its own edge.\n *\n * MinIO and Mailpit run on the local stage always, and on a deployed stage\n * only where `--allow-dev-services` allowed them and its secrets configure no\n * real bucket or mail server — see `devServices.ts`.\n */\nconst NOT_RUN: Readonly<Record<string, true>> = {\n\tlocalstack: true,\n\tcaddy: true,\n};\n\n/** The kinds a deployed stage takes from its secrets, or a dev service. */\nconst SERVICE_KINDS: Readonly<Record<string, ServiceDeclaration['kind']>> = {\n\temail: 'email',\n\tobjects: 'objects',\n\t'file-server': 'file-server',\n};\n\n/** The region MinIO is addressed with. It has no regions; the SDK wants one. */\nconst MINIO_REGION = 'us-east-1';\n\n/** The S3 client's credentials, read beside a bucket's URL when it has them. */\nconst STORAGE_KEYS = [\n\t'AWS_ACCESS_KEY_ID',\n\t'AWS_SECRET_ACCESS_KEY',\n\t'AWS_REGION',\n] as const;\n\n/**\n * Every service's Docker logs, rotated. The json-file driver keeps a\n * container's output in one file that grows until the disk is full — on a\n * small server, in weeks. Three files of 10 MB each per container is enough\n * to see what happened and never fills anything. A project's own override\n * file that sets `logging` wins over it.\n */\nexport const LOG_ROTATION = {\n\tdriver: 'json-file',\n\toptions: { 'max-size': '10m', 'max-file': '3' },\n} as const;\n\n/** Each image's build, where the stack builds rather than pulls. */\nexport interface AppBuild {\n\t/** Where the Dockerfile is written, relative to the workspace root. */\n\tdockerfile: string;\n\t/** A site's public URLs, inlined by its bundler. */\n\targs?: Record<string, string>;\n\t/**\n\t * A site's own hosts and its edges', refused for the length of its build —\n\t * see {@link offlineBuildHosts}.\n\t */\n\tofflineHosts?: string[];\n}\n\n/** One app in the stack. */\nexport interface StackApp extends AppImage {\n\t/** Its compose service name — the app key, `api`. */\n\tname: string;\n\t/** The construct it serves. */\n\tid: string;\n\tkind: 'rest-api' | 'websocket-api' | 'site';\n\t/**\n\t * A site's framework — whether its pages are rendered by a server (`next`,\n\t * `tanstack`) or built once as files (`static`). Absent for a backend.\n\t */\n\tvariant?: SiteDeclaration['variant'];\n\t/**\n\t * How many containers serve it, each an upstream of its route: `api`,\n\t * then `api-2`, `api-3`. One, but for a surface that asked for more.\n\t */\n\treplicas: number;\n\t/** Its directory, relative to the workspace root. */\n\tpath: string;\n\tport: number;\n\t/** The host the edge answers it on — canonical: its `<ID>_URL`'s. */\n\thost: string;\n\t/** More hosts the edge answers it on, as `host`: its `aliases`. */\n\taliases?: string[];\n\t/** Hosts the edge redirects to `host`, permanently: a site's `redirects`. */\n\tredirects?: string[];\n\t/** `https://<host>` — with the edge's port where it is not 443. */\n\turl: string;\n\tbuild?: AppBuild;\n\t/**\n\t * Whether it reads an environment at runtime: every backend, and a site\n\t * that runs a server (`runsServer`). A static site is a bundle.\n\t */\n\truntime: boolean;\n\t/**\n\t * Exactly the keys it reads at runtime (`processEnvKeys`). Absent for a\n\t * static site.\n\t */\n\tenv?: Record<string, string>;\n\t/** The login the edge asks for, where the site is behind a password. */\n\tauth?: SiteAuth;\n\t/**\n\t * A site that pre-renders against its stage (`prerender: 'stage'`): the\n\t * apps of the stack its `.dependsOn()` names, by compose service name —\n\t * what has to answer, healthy, before its image is built.\n\t */\n\tprerender?: { against: string[] };\n\t/** A WebSocket surface's per-address limits, which its route enforces. */\n\tlimits?: WebSocketEdgeLimits;\n}\n\n/**\n * A Worker in the stack: its crons, queue consumers and subscribers in a\n * container of their own. Nothing is published, and nothing routes to it\n * unless SNS pushes to one of its subscribers — then the edge answers it on\n * a host of its own, on exactly those subscribers' routes.\n */\nexport interface StackWorker extends AppImage {\n\t/** Its compose service name — `jobs`. */\n\tname: string;\n\t/** The Worker construct. */\n\tid: string;\n\t/** The app whose build writes its entry, which its image is built from. */\n\thost: string;\n\t/** Where its health check answers, inside the container. */\n\tport: number;\n\tbuild?: AppBuild;\n\t/** Exactly the keys the worker's constructs read. */\n\tenv?: Record<string, string>;\n\t/** Where SNS pushes to it, when it pushes to any of its subscribers. */\n\tpush?: WorkerPush;\n}\n\n/** A worker's public face: the routes SNS pushes its subscribers' messages to. */\nexport interface WorkerPush {\n\t/** e.g. `jobs.example.com` */\n\thost: string;\n\t/** `https://<host>` — what each route is subscribed under. */\n\turl: string;\n\t/** Each pushed subscriber's route, and nothing else the worker serves. */\n\tpaths: string[];\n\t/**\n\t * Each pushed subscriber: its export, the key of the SNS connection its\n\t * deliveries come from, and the URL the deploy subscribes for it.\n\t */\n\tsubscribers: PushedSubscriber[];\n}\n\n/** One subscriber SNS pushes to, as the deploy subscribes it. */\nexport interface PushedSubscriber {\n\t/** Its export — what its subscription ARN is recorded under. */\n\tname: string;\n\t/**\n\t * The env key of the SNS connection it is delivered from — its topic's\n\t * publisher string, or its bucket's events string.\n\t */\n\tconnectionKey: string;\n\t/** `https://<host>/__gkm/subscribers/<name>` */\n\tendpoint: string;\n\t/**\n\t * The event types a topic subscriber names — its subscription's filter.\n\t * Absent for a bucket's subscriber.\n\t */\n\tevents?: readonly string[];\n}\n\n/**\n * A file server's processors in the stack: one container answering each of\n * their patterns, built from the app whose build writes their entry.\n *\n * Reached on the file server's own host when the stack's MinIO serves it —\n * its patterns sent here, every other path to the bucket — or, when a CDN\n * serves the bucket, on a host of its own that only the CDN may call.\n */\nexport interface StackProcessor extends AppImage {\n\t/** Its compose service name — `assets-processors`. */\n\tname: string;\n\t/** The file server's surface it answers on, `AssetsServer`. */\n\tid: string;\n\t/** The app whose build writes its entry, which its image is built from. */\n\thost: string;\n\tport: number;\n\t/** Its processors' prefixes — `/i/` — the paths the edge sends it. */\n\tprefixes: string[];\n\t/**\n\t * Where a CDN reaches it, when the bucket is served by one: its host, and\n\t * the header value the CDN adds, without which the edge refuses.\n\t */\n\torigin?: { host: string; secret: string };\n\tbuild?: AppBuild;\n\t/** Exactly the keys its processors read. */\n\tenv?: Record<string, string>;\n}\n\n/** A CDN serves the bucket, and the secret it sends the processors is not in the stage. */\nexport class ProcessorOriginSecretMissing extends GkmError {\n\tconstructor(\n\t\treadonly fileServer: string,\n\t\treadonly key: string,\n\t\treadonly stage: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${fileServer}' has processors, and its bucket is not the stack's MinIO, ` +\n\t\t\t\t`so they are reached through the CDN in front of it — which sends ` +\n\t\t\t\t`${key}, and stage '${stage}' has none. It is written by the deploy ` +\n\t\t\t\t`that creates the CDN (\\`deploy.objects.${stage}\\` on s3, cdn on): run ` +\n\t\t\t\t`gkm deploy --stage ${stage}.`,\n\t\t);\n\t\tthis.name = 'ProcessorOriginSecretMissing';\n\t}\n}\n\n/**\n * A mobile app, as a stage builds it: nothing in the stack runs it — EAS\n * builds it and the stores ship it — but its build reads the stage's\n * public values, resolved here the way a site's build args are.\n */\nexport interface StackMobileApp {\n\t/** Its app key — `app`. */\n\tname: string;\n\t/** The `MobileApp` construct. */\n\tid: string;\n\t/**\n\t * What its build reads, for this stage: its scheme, its edges' public\n\t * URLs under `EXPO_PUBLIC_`, and every stage secret already named so.\n\t */\n\tvalues: Record<string, string>;\n}\n\n/** A service as the stack's compose file defines it. */\nexport interface StackService {\n\timage: string;\n\tbuild?: {\n\t\tcontext: string;\n\t\tdockerfile: string;\n\t\targs?: Record<string, string>;\n\t\t/** `host:address` lines for the build's own `/etc/hosts`. */\n\t\textra_hosts?: string[];\n\t\t/** Top-level {@link StackFile.secrets} the build may mount. */\n\t\tsecrets?: string[];\n\t};\n\t/** `build` for an image built on the server and never pulled. */\n\tpull_policy?: 'build';\n\trestart?: string;\n\tcommand?: string | string[];\n\tenv_file?: { path: string; format: 'raw' }[];\n\tenvironment?: Record<string, string>;\n\tports?: string[];\n\tvolumes?: string[];\n\t/** Names resolved to an address of the container's choosing — the host's. */\n\textra_hosts?: string[];\n\t/** Files handed to the container inline — see {@link withCaddyConfigs}. */\n\tconfigs?: { source: string; target: string; mode?: number }[];\n\tlabels?: Record<string, string>;\n\t/** Per-container kernel settings — namespaced ones only. */\n\tsysctls?: Record<string, string>;\n\tulimits?: Record<string, { soft: number; hard: number }>;\n\tdepends_on?: Record<\n\t\tstring,\n\t\t{ condition: 'service_healthy' | 'service_started' }\n\t>;\n\thealthcheck?: ComposeService['healthcheck'];\n\t/**\n\t * Behind the shared edge, a public service is on the stack's own network\n\t * and the edge's, by an alias unique on both.\n\t */\n\tnetworks?: Record<string, { aliases: string[] }>;\n\tlogging?: {\n\t\tdriver: string;\n\t\toptions: Record<string, string>;\n\t};\n}\n\nexport interface StackFile {\n\tname: string;\n\tservices: Record<string, StackService>;\n\tvolumes: Record<string, Record<string, never>>;\n\t/** The shared edge's network, which the stack joins but never creates. */\n\tnetworks?: Record<string, { name: string; external: true }>;\n\t/** Files the stack's containers are handed, by content. */\n\tconfigs?: Record<string, { content: string }>;\n\t/** Files a build mounts as a secret, from this machine. */\n\tsecrets?: Record<string, { file: string }>;\n}\n\n/**\n * The stack with Caddy's files inline: its Caddyfile and, where the stage has\n * one, its own certificate — `configs` with their `content`, which compose\n * copies into the container through the engine's API. Nothing is mounted from\n * a path, so the stack runs the same on a server's engine, over SSH, as on\n * this machine's. Their hash is a label: a changed file is a changed service,\n * which `up` recreates (compose does not, for a config's content alone).\n */\nexport function withCaddyConfigs(\n\tcompose: StackFile,\n\tfiles: { caddyfile: string; tls?: { cert: string; key: string } },\n): StackFile {\n\tconst caddy = compose.services.caddy;\n\tif (!caddy) return compose;\n\tconst configs: Record<string, { content: string }> = {\n\t\tcaddyfile: { content: files.caddyfile },\n\t\t...(files.tls\n\t\t\t? {\n\t\t\t\t\t'tls-cert': { content: files.tls.cert },\n\t\t\t\t\t'tls-key': { content: files.tls.key },\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n\tconst hash = createHash('sha256');\n\tfor (const [name, { content }] of Object.entries(configs)) {\n\t\thash.update(`${name}\\0${content}\\0`);\n\t}\n\treturn {\n\t\t...compose,\n\t\tservices: {\n\t\t\t...compose.services,\n\t\t\tcaddy: {\n\t\t\t\t...caddy,\n\t\t\t\tconfigs: [\n\t\t\t\t\t{ source: 'caddyfile', target: '/etc/caddy/Caddyfile' },\n\t\t\t\t\t...(files.tls\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{ source: 'tls-cert', target: `${CADDY_TLS_DIR}/cert.pem` },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsource: 'tls-key',\n\t\t\t\t\t\t\t\t\ttarget: `${CADDY_TLS_DIR}/key.pem`,\n\t\t\t\t\t\t\t\t\tmode: 0o400,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: []),\n\t\t\t\t],\n\t\t\t\tlabels: {\n\t\t\t\t\t...caddy.labels,\n\t\t\t\t\t'dev.geekmidas.caddy.config': hash.digest('hex').slice(0, 16),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconfigs: { ...compose.configs, ...configs },\n\t};\n}\n\nexport interface ComposeStack {\n\tproject: string;\n\tstage: string;\n\t/**\n\t * The project's local stage, served with the certificate gkm's local\n\t * authority issues — see {@link ComposeStack.authority} — unless it set\n\t * its own.\n\t */\n\tlocal: boolean;\n\t/**\n\t * The local stage's certificate authority: gkm's, on this machine — absent\n\t * when the stage set its own certificate (`deploy.compose.tls`). Its root\n\t * is what every app container trusts and the verify step checks against,\n\t * and it issues the edge's certificate as the stack is written.\n\t */\n\tauthority?: LocalAuthorityPaths;\n\tapps: StackApp[];\n\t/** Each Worker with background work, in a container of its own. */\n\tworkers: StackWorker[];\n\t/** Each file server's processors, in a container of their own. */\n\tprocessors: StackProcessor[];\n\t/** Each mobile app, and what its build reads for this stage. */\n\tmobileApps: StackMobileApp[];\n\t/** The infrastructure containers, by compose service name. */\n\tinfra: string[];\n\tcompose: StackFile;\n\t/**\n\t * What serves the stack: its own Caddy, or the machine's shared Traefik\n\t * edge (`deploy.compose.proxy` — see `proxyFor`).\n\t */\n\tproxy: ComposeProxy;\n\t/** Every public host and what answers it — what either proxy renders. */\n\troutes: EdgeRoute[];\n\t/**\n\t * A deployed stage's wildcard site: its id, the `*.<domain>` host its\n\t * one DNS record is written for, and where its certificate comes from —\n\t * `dns` when the deploy has to give the shared edge its DNS provider's key.\n\t */\n\twildcard?: {\n\t\tsite: string;\n\t\thost: string;\n\t\ttls: EdgeWildcard['tls']['kind'];\n\t};\n\t/** The stack's own Caddy's configuration — with `proxy: 'caddy'`. */\n\tcaddyfile?: string;\n\t/**\n\t * What the stack registers with the shared edge — with `proxy:\n\t * 'traefik'`: the dynamic configuration file written to its directory.\n\t */\n\ttraefik?: string;\n\t/**\n\t * The stage's own certificate and key, on this machine\n\t * (`deploy.compose.tls`) — copied to where the proxy reads it — and the\n\t * root it chains to, where it named one.\n\t */\n\ttls?: ComposeTlsConfig;\n\t/** Generated Dockerfiles, by path relative to the workspace root. */\n\tdockerfiles: Record<string, string>;\n\t/** The plan the stack was derived from — what provisioning creates. */\n\tplan: Plan;\n\t/** The containers' logins, and the seed role passwords take. */\n\tcredential: StackCredential;\n\t/**\n\t * What the stack resolves its values with, but the ports: its logins, its\n\t * seed, and each app's and file server's public address.\n\t *\n\t * What runs on this machine against the stack — its migrations and seeds\n\t * — resolves with the same (`stageEnv`), on the ports it reaches each of\n\t * {@link LOOPBACK_SERVICES} by, so a seed sees the keys `gkm seed` would\n\t * hand it and the addresses the stack's apps are given.\n\t */\n\tresolution: Omit<EnvOptions, 'ports'>;\n\t/**\n\t * The stack's MinIO, where it runs one: its root credential — what the\n\t * backends sign with — and the buckets and open paths provisioning\n\t * creates in it.\n\t */\n\tstorage?: StackStorage;\n\t/** The dev services a deployed stage runs (`--allow-dev-services`). */\n\tdevServices: DevServiceUse[];\n\t/**\n\t * The stack's OpenObserve, when the stage's telemetry is self-hosted —\n\t * every process with a `Telemetry` edge sends its logs and traces to it.\n\t */\n\tlogs?: StackLogs;\n\t/** Where the stage's telemetry goes, when any process uses it. */\n\ttelemetry?: ResolvedTelemetry;\n\t/**\n\t * The stack's Redis, where a declared cache lives in it — every cache\n\t * whose URL the stage's secrets do not set.\n\t */\n\tredis?: StackRedis;\n\t/**\n\t * The stage's backups, where it is deployed, runs Postgres and has not\n\t * set `deploy.backups.<stage>: false`.\n\t */\n\tbackups?: StackBackups;\n\t/**\n\t * The stack's Mailpit inbox, on the local stage where it runs Mailpit:\n\t * its web UI, routed through the edge at `mail.<project>.localhost`. A\n\t * deployed stage never has one — a dev service's Mailpit stays internal.\n\t */\n\tmailInbox?: StackMailInbox;\n\t/**\n\t * What the stack resolved and says without refusing it: a file server's\n\t * stored address that its stage's domain disagrees with. Printed by\n\t * whatever composed it.\n\t */\n\twarnings: string[];\n}\n\n/** The local stage's Mailpit inbox, as the edge serves it. */\nexport interface StackMailInbox {\n\t/** `mail.<project>.localhost` */\n\thost: string;\n\t/** What a browser opens, with the edge's port when it is not 443. */\n\turl: string;\n}\n\n/** The label the local stage's Mailpit inbox answers on. */\nexport const MAIL_INBOX_LABEL = 'mail';\n\n/** Mailpit's web UI and API, inside the stack's network. */\nconst MAILPIT_WEB_PORT = 8025;\n\n/** An app of the local stage on the host its Mailpit inbox is served at. */\nexport class MailInboxHostTaken extends GkmError {\n\tconstructor(\n\t\treadonly host: string,\n\t\treadonly app: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${app}' answers on ${host}, which the local stage serves its Mailpit ` +\n\t\t\t\t`inbox at. Give '${app}' another subdomain — '${MAIL_INBOX_LABEL}' is ` +\n\t\t\t\t`reserved for the inbox on the local stage.`,\n\t\t);\n\t\tthis.name = 'MailInboxHostTaken';\n\t}\n}\n\n/**\n * The services a stack publishes on its engine's loopback, and the port each\n * answers on inside — what gkm reaches from this machine to provision the\n * stack and run its migrations and seeds. Everything else is reached only on\n * the stack's network.\n */\nexport const LOOPBACK_SERVICES = {\n\tpostgres: 5432,\n\tminio: 9000,\n} as const satisfies Record<string, number>;\n\n/** What a stack's containers run with, and what its role passwords take. */\nexport interface StackCredential {\n\tcontainers: ContainerCredentials;\n\tseed: string;\n}\n\n/** The local stage's stack, without the logins `gkm dev` generates. */\nexport class LocalCredentialsMissing extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(\n\t\t\t`The local stage '${stage}' runs with this machine's generated logins, and none were passed. Load them with loadLocalCredentials(workspace) and pass them as localCredentials.`,\n\t\t);\n\t\tthis.name = 'LocalCredentialsMissing';\n\t}\n}\n\n/**\n * A deployed stage's container logins, derived from its seed like its role\n * passwords — so every deploy of the stage computes the same ones, and no one\n * reading the repo can.\n */\nexport function derivedCredentials(\n\tproject: string,\n\tplan: Plan,\n\tseed: string,\n): ContainerCredentials {\n\tconst derive = (purpose: string) =>\n\t\tlocalRolePassword(project, plan, purpose, seed);\n\treturn {\n\t\tpostgres: { user: postgresSuperuser(project), password: derive('master') },\n\t\tminio: { user: `${project}-minio`, password: derive('minio') },\n\t\trabbitmq: { user: LOCAL_RABBITMQ_USER, password: derive('rabbitmq') },\n\t\tredis: { password: derive('redis') },\n\t\tcacheToken: derive('cache-token'),\n\t\temulator: {\n\t\t\taccessKeyId: EMULATOR_ACCESS_KEY_ID,\n\t\t\tsecretAccessKey: derive('emulator'),\n\t\t},\n\t\t// Never read: a deployed stage's OpenObserve signs in with the root\n\t\t// login its secrets hold (`stackLogs`), and the stack hands each process\n\t\t// its telemetry keys from that, not from the derivation.\n\t\tlogs: { email: `admin@${project}`, password: derive('logs') },\n\t};\n}\n\n/** The stack's MinIO, and what is created in it. */\nexport interface StackStorage {\n\tuser: string;\n\tpassword: string;\n\t/** Each bucket's stage-scoped name. */\n\tbuckets: string[];\n\t/** The open paths of each served bucket. */\n\tpolicies: { bucket: string; open: string[] }[];\n\t/**\n\t * Each bucket by construct id and name, and which of them post their\n\t * events to a worker — the notifications gkm writes once MinIO runs.\n\t */\n\tobjects: { id: string; name: string }[];\n\t/** Where MinIO posts each watched bucket's events: on the stack's network. */\n\twebhooks: ObjectWebhook[];\n\t/** How long each bucket keeps what is under each prefix. */\n\tlifecycles: { bucket: string; expire: Readonly<Record<string, number>> }[];\n}\n\nexport interface StackInput {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\t/**\n\t * Each Worker's crons', queues' and subscribers' files, from discovery —\n\t * which workers run, and which app each is built from.\n\t */\n\tbackground?: Readonly<Record<string, readonly string[]>>;\n\t/**\n\t * Each Worker's topic subscribers, from discovery — which of them SNS\n\t * pushes to decides whether the worker answers on a host of its own.\n\t */\n\tsubscribers?: Readonly<Record<string, readonly BoundSubscriber[]>>;\n\t/**\n\t * The SNS subscriptions the deploy made for each worker's pushed\n\t * subscribers — worker id → subscriber export → subscription ARN — handed\n\t * to the worker as `GKM_SNS_SUBSCRIPTIONS`. A pushed subscriber without\n\t * one fails the stack: the worker would mount no route for it.\n\t */\n\tpushSubscriptions?: Readonly<\n\t\tRecord<string, Readonly<Record<string, string>>>\n\t>;\n\t/**\n\t * Composed before the deploy has made the subscriptions it is about to\n\t * record — to learn where SNS pushes, and with what. No worker is handed\n\t * `GKM_SNS_SUBSCRIPTIONS`, so a pushed subscriber without an ARN is not\n\t * refused: this stack is read, never run.\n\t */\n\trecordingSubscriptions?: boolean;\n\tstage: string;\n\tidentity: DeployIdentity;\n\timages: {\n\t\tmode: 'build' | 'pull';\n\t\t/**\n\t\t * A release tag, or — building — the commit. Each image carries it with\n\t\t * the stage on (`stageTag`).\n\t\t */\n\t\ttag: string;\n\t\tregistry?: string;\n\t};\n\t/** The stage's secrets — set by hand, and what a deployed stage generated. */\n\tsecrets?: StageSecrets | null;\n\t/**\n\t * This machine's generated local logins — required for the local stage,\n\t * which runs with the same ones `gkm dev` does. See `localCredentials.ts`.\n\t */\n\tlocalCredentials?: LocalCredentials;\n\t/**\n\t * gkm's local certificate authority, for the local stage: the CLI's\n\t * home's when not given.\n\t */\n\tlocalAuthority?: LocalAuthorityPaths;\n\t/**\n\t * `--allow-dev-services`: a deployed stage runs the dev service for every\n\t * bucket and mail it does not account for. The local stage runs both\n\t * regardless.\n\t */\n\tallowDevServices?: boolean;\n\t/** The edge's published ports. 443 and 80 by default. */\n\tports?: {\n\t\thttps?: number;\n\t\thttp?: number;\n\t\t/** The local stage's OpenObserve port — see `LOGS_PORT_ENV` (`compose/edge.ts`). */\n\t\tlogs?: number;\n\t};\n\t/**\n\t * The stack only builds its images, to push them (`--build --push`): no\n\t * backend's or worker's runtime environment is resolved and no service\n\t * reads an env file, so building needs none of the stage's backend\n\t * secrets. A site's build args — its public URLs — are still resolved.\n\t */\n\tbuildOnly?: boolean;\n\t/**\n\t * What names this deploy to a site that pre-renders against its stage —\n\t * its build's `GKM_PRERENDER_RUN`, so the layer that fetches the stage's\n\t * data is built again on every deploy rather than served from cache.\n\t */\n\tprerenderRun?: string;\n\t/**\n\t * For builds: where the images are built from and with what — the build\n\t * root, its package manager and turbo. The workspace's root, with pnpm,\n\t * when not given.\n\t */\n\tlayout?: ImageLayout;\n}\n\n/** A value only the stage's secrets can hold, and they do not. */\nexport class StageSecretMissing extends GkmError {\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly key: string,\n\t\treadonly stage: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${app}' reads ${key}, and the stage '${stage}' has none. Nothing in ` +\n\t\t\t\t`the stack can derive it; set it in the stage's secrets: ` +\n\t\t\t\t`gkm secrets:set ${key} '…' --stage ${stage}`,\n\t\t);\n\t\tthis.name = 'StageSecretMissing';\n\t}\n}\n\n/** Where a deployed inbox's values come from: the stage's domain, and its secrets. */\nexport interface DeployedInboxSources {\n\t/** Who reads them, named in the error when one is missing. */\n\treader: string;\n\tstage: string;\n\tdomain: string | undefined;\n\t/** The stage's secrets, where the inbox's provider wrote its keys. */\n\tsecrets: Readonly<Record<string, string>>;\n}\n\n/**\n * One key of a deployed inbox — the one rule every target reads it by.\n *\n * Its domain is the stage's, which mail is addressed to. Everything else (where\n * its raw messages are read, its topic's publisher string) is what its\n * provider made and wrote to the stage's secrets; nothing can derive it.\n *\n * @throws {NoDomainForStage} for its domain when the stage has none.\n * @throws {StageSecretMissing} when the provider has not written the key.\n */\nexport function deployedInboxValue(\n\tinbox: string,\n\tkey: string,\n\tsources: DeployedInboxSources,\n): string {\n\tif (key === providedKeyFor(inbox, 'inbox', 'domain')) {\n\t\tif (!sources.domain) throw new NoDomainForStage(sources.stage);\n\t\treturn sources.domain;\n\t}\n\tconst value = sources.secrets[key];\n\tif (value === undefined) {\n\t\tthrow new StageSecretMissing(sources.reader, key, sources.stage);\n\t}\n\treturn value;\n}\n\n/**\n * Every deployed inbox's keys, and its topic's publisher string, by key: what\n * a target that provisions nothing of the inbox's (SST) is handed, read by\n * {@link deployedInboxValue} as the compose stack reads each.\n */\nexport function deployedInboxEnv(\n\tmanifest: ConstructManifest,\n\tsources: DeployedInboxSources,\n): Record<string, string> {\n\tconst env: Record<string, string> = {};\n\tfor (const declaration of Object.values(manifest)) {\n\t\tif (declaration.kind !== 'inbox') continue;\n\t\tconst keys = [\n\t\t\t...(declaration.provides ?? []),\n\t\t\tprovidedKeyFor(declaration.topic, 'topic', 'publisherConnectionString'),\n\t\t];\n\t\tfor (const key of keys) {\n\t\t\tenv[key] = deployedInboxValue(declaration.id, key, sources);\n\t\t}\n\t}\n\treturn env;\n}\n\n/** A deployed stage's secrets with no seed to derive its passwords from. */\nexport class StageSeedMissing extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(\n\t\t\t`The stage '${stage}' has no seed in its secrets, and a deployed stage's ` +\n\t\t\t\t`database passwords are derived from it. Run gkm compose --stage ${stage} ` +\n\t\t\t\t`without --dry-run once, or gkm deploy, to generate it.`,\n\t\t);\n\t\tthis.name = 'StageSeedMissing';\n\t}\n}\n\n/** A workspace with no API and no site to run. */\nexport class NothingToCompose extends GkmError {\n\tconstructor(readonly root: string) {\n\t\tsuper(\n\t\t\t`${root} declares no RestApi, no site and no Worker with work to do, ` +\n\t\t\t\t`so a stack would run nothing. Mobile apps ship through their own ` +\n\t\t\t\t`toolchain.`,\n\t\t);\n\t\tthis.name = 'NothingToCompose';\n\t}\n}\n\n/** A value that cannot be written to an env file a line at a time. */\nexport class EnvValueMultiline extends GkmError {\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly key: string,\n\t) {\n\t\tsuper(\n\t\t\t`${key} for '${app}' spans more than one line, and an env file holds ` +\n\t\t\t\t`one value per line. Store it on one line — base64, or JSON — and ` +\n\t\t\t\t`decode it where it is read.`,\n\t\t);\n\t\tthis.name = 'EnvValueMultiline';\n\t}\n}\n\n/** The services a stack's apps wait on. */\nconst HEALTHY = { condition: 'service_healthy' } as const;\n\n/**\n * What Caddy waits on of each app: that it started, never that it is\n * healthy. Its routes are served whatever an app's health — Caddy's own\n * upstream health checks take one out of rotation — so one app that never\n * turns healthy leaves the others routed, and a site whose health check goes\n * through the edge can turn healthy at all.\n */\nconst STARTED = { condition: 'service_started' } as const;\n\n/**\n * An app's health check: its own server, asked on 127.0.0.1 — not\n * `localhost`, which resolves to `::1` first in an Alpine container while a\n * server may listen on IPv4 alone.\n */\nfunction probe(port: number, path: string): StackService['healthcheck'] {\n\treturn {\n\t\ttest: [\n\t\t\t'CMD',\n\t\t\t'wget',\n\t\t\t'-q',\n\t\t\t'-O',\n\t\t\t'/dev/null',\n\t\t\t`http://127.0.0.1:${port}${path}`,\n\t\t],\n\t\tinterval: '5s',\n\t\ttimeout: '3s',\n\t\tretries: 20,\n\t\tstart_period: '10s',\n\t};\n}\n\n/**\n * What a stage's stack provisions: reconcile's plan, with a server target's\n * backends whatever `deploy.default` says — the stack is one machine running\n * containers, so events are pg-boss beside the declared database, and every\n * cache, one declared from that database included, is in the stack's own\n * Redis.\n */\nexport function stackPlan(\n\tworkspace: Pick<\n\t\tNormalizedWorkspace,\n\t\t'stages' | 'protectedSubdomains' | 'domains'\n\t>,\n\tmanifest: ConstructManifest,\n\tstage: string,\n): Plan {\n\t// A stage whose domain sits under this one's is a label of it no tenant\n\t// may take: `staging`, beside every app's own and the configured names.\n\tconst protectedSubdomains = [\n\t\t...(workspace.protectedSubdomains ?? []),\n\t\t...nestedStageLabels(workspace.domains, stage),\n\t];\n\treturn planFor(manifest, stage, provisionOrder(manifest), {\n\t\tlocalStage: workspace.stages.local,\n\t\t...(protectedSubdomains.length > 0 ? { protectedSubdomains } : {}),\n\t\tevents: DEFAULT_EVENTS.server,\n\t\tcache: STACK_CACHE,\n\t\t// The stack brings its own edge; reconcile's would front the host.\n\t\tedge: false,\n\t});\n}\n\n/** The stack for one stage. */\nexport function composeStack(input: StackInput): ComposeStack {\n\tconst { workspace, manifest, stage, identity } = input;\n\tconst local = stage === workspace.stages.local;\n\tconst project = composeProject(identity);\n\tconst custom = input.secrets?.custom ?? {};\n\tconst https = input.ports?.https ?? 443;\n\tconst http = input.ports?.http ?? 80;\n\tconst proxy = proxyFor(workspace.deploy?.compose, stage);\n\tconst certificate = certificateFor(\n\t\tworkspace.deploy?.compose,\n\t\tstage,\n\t\tworkspace.root,\n\t);\n\n\t// A server target's backends, whatever `deploy.default` says: the stack is\n\t// one machine running containers, so events are pg-boss beside the\n\t// declared database — and every cache, one declared from that database\n\t// included, is in the stack's own Redis.\n\tconst plan = stackPlan(workspace, manifest, stage);\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\n\t// The local stage's logins are the ones `gkm dev` generated for this\n\t// machine, so the two run their containers with the same; a deployed\n\t// stage's are derived from its seed.\n\tif (local && !input.localCredentials) {\n\t\tthrow new LocalCredentialsMissing(stage);\n\t}\n\tconst seed = local ? input.localCredentials!.seed : input.secrets?.seed;\n\tif (!seed) throw new StageSeedMissing(stage);\n\tconst containers: ContainerCredentials = local\n\t\t? input.localCredentials!\n\t\t: derivedCredentials(workspace.name, plan, seed);\n\tconst credential: StackCredential = {\n\t\tcontainers: {\n\t\t\t...containers,\n\t\t\t// The stage's own key pair, where it set one, is what MinIO runs as.\n\t\t\tminio: {\n\t\t\t\tuser: custom.AWS_ACCESS_KEY_ID ?? containers.minio.user,\n\t\t\t\tpassword: custom.AWS_SECRET_ACCESS_KEY ?? containers.minio.password,\n\t\t\t},\n\t\t},\n\t\tseed,\n\t};\n\n\tconst apps = stackApps(workspace, manifest, plan, {\n\t\tlocal,\n\t\tstage,\n\t\thttps,\n\t\tidentity,\n\t\timages: input.images,\n\t});\n\tconst workers = stackWorkers(\n\t\tworkerUnits(workspace, manifest, input.background ?? {}),\n\t\t{ stage, identity, images: input.images },\n\t);\n\tconst processors = stackProcessors(processorUnits(workspace, manifest), {\n\t\tmanifest,\n\t\tstage,\n\t\tidentity,\n\t\timages: input.images,\n\t});\n\tif (apps.length === 0 && workers.length === 0 && processors.length === 0) {\n\t\tthrow new NothingToCompose(workspace.root);\n\t}\n\n\t// Which construct each key belongs to, so a key is resolved by what it is\n\t// rather than by its spelling.\n\tconst owners = new Map<string, PlannedResource>();\n\tfor (const resource of plan.resources) {\n\t\towners.set(resource.envKey, resource);\n\t\tif (resource.kind === 'email') {\n\t\t\towners.set(providedKeyFor(resource.id, resource.kind, 'from'), resource);\n\t\t\towners.set(\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'inboxUrl'),\n\t\t\t\tresource,\n\t\t\t);\n\t\t}\n\t\t// A bucket's signed origin is its own: derived from its connection,\n\t\t// wherever that resolved — never the stack's MinIO for a bucket on S3.\n\t\tif (resource.kind === 'objects') {\n\t\t\towners.set(\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'signedOrigin'),\n\t\t\t\tresource,\n\t\t\t);\n\t\t}\n\t\tif (resource.kind === 'external-api') {\n\t\t\towners.set(\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'credentials'),\n\t\t\t\tresource,\n\t\t\t);\n\t\t}\n\t\tif (resource.kind === 'inbox') {\n\t\t\towners.set(\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'domain'),\n\t\t\t\tresource,\n\t\t\t);\n\t\t}\n\t\tif (resource.kind === 'websocket-api') {\n\t\t\towners.set(\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'publisherConnectionString'),\n\t\t\t\tresource,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst domain = workspace.domains?.[stage];\n\n\t// Where the stage's telemetry goes, when a process uses a `Telemetry`\n\t// node: the local stage always to OpenObserve, a deployed one where\n\t// `deploy.telemetry` says — and OpenObserve when it says nothing.\n\tconst telemetry = resolveStageTelemetry({\n\t\t...(workspace.deploy?.telemetry\n\t\t\t? { telemetry: workspace.deploy.telemetry }\n\t\t\t: {}),\n\t\tstage,\n\t\tlocal,\n\t\ttarget: 'compose',\n\t\truntime: 'server',\n\t\tselfHosted: true,\n\t\tused: usesTelemetry(manifest),\n\t});\n\n\t// The log UI, when the stage's telemetry is self-hosted: its root login,\n\t// how it is reached, and what each process with the edge is handed to send\n\t// to it.\n\tconst logsBase =\n\t\ttelemetry?.provider === 'self-hosted'\n\t\t\t? stackLogs({\n\t\t\t\t\tconfig:\n\t\t\t\t\t\tlocal && input.ports?.logs\n\t\t\t\t\t\t\t? { ...telemetry.selfHosted, port: input.ports.logs }\n\t\t\t\t\t\t\t: telemetry.selfHosted,\n\t\t\t\t\tstage,\n\t\t\t\t\tlocal,\n\t\t\t\t\tproject: workspace.name,\n\t\t\t\t\t...(domain ? { domain } : {}),\n\t\t\t\t\ttelemetry: stackTelemetry(manifest),\n\t\t\t\t\tcustom,\n\t\t\t\t\thttps,\n\t\t\t\t\t...(local ? { localLogin: input.localCredentials!.logs } : {}),\n\t\t\t\t})\n\t\t\t: undefined;\n\n\t// Mail and storage: the local stage runs Mailpit and MinIO for all of it.\n\t// A deployed stage takes each from its secrets — or, where allowed, from a\n\t// dev service. Only decided here: whether the stage lacks a key is the\n\t// deploy's readiness check's to say, once, and a build asks no such thing.\n\tconst services: ExternalServices = local\n\t\t? {\n\t\t\t\tmissing: [],\n\t\t\t\tminio: plan.resources\n\t\t\t\t\t.filter((r) => r.kind === 'objects')\n\t\t\t\t\t.map((r) => r.id),\n\t\t\t\t// Mailpit receives for an inbox as it sends for mail.\n\t\t\t\tmailpit: plan.resources\n\t\t\t\t\t.filter((r) => r.kind === 'email' || r.kind === 'inbox')\n\t\t\t\t\t.map((r) => r.id),\n\t\t\t}\n\t\t: externalServices({\n\t\t\t\tstage,\n\t\t\t\tdeclarations: stageServiceDeclarations({\n\t\t\t\t\tmanifest,\n\t\t\t\t}),\n\t\t\t\tsupplied: custom,\n\t\t\t\tallow: input.allowDevServices === true,\n\t\t\t\t...(domain ? { domain } : {}),\n\t\t\t\tproviders: stageProviderNotes(workspace, stage),\n\t\t\t});\n\n\t// The caches: in the stack's Redis, unless the stage set a cache's URL —\n\t// a managed Redis — and with every one set, there is no Redis to run.\n\tconst redis = stackRedis({\n\t\tplan,\n\t\tstage,\n\t\tlocal,\n\t\tcustom,\n\t\t...(local ? { localPassword: input.localCredentials!.redis.password } : {}),\n\t});\n\n\tconst infra = [\n\t\t...plan.containers\n\t\t\t.filter((c) => !NOT_RUN[c])\n\t\t\t// Run as the stack's own, below, with the stage's login.\n\t\t\t.filter((c) => c !== LOGS_SERVICE)\n\t\t\t.filter((c) => c !== 'minio' || services.minio.length > 0)\n\t\t\t.filter((c) => c !== 'mailpit' || services.mailpit.length > 0)\n\t\t\t.filter((c) => c !== REDIS_SERVICE || redis !== undefined),\n\t\t...(logsBase ? [LOGS_SERVICE] : []),\n\t].sort();\n\n\t// The local stage's inbox: Mailpit's web UI on a host of the edge's, as\n\t// the apps are — `mail.<project>.localhost` — so a link a stack mails\n\t// can be opened and followed. Never on a deployed stage, where a dev\n\t// service's Mailpit stays internal.\n\tconst mailInbox: StackMailInbox | undefined =\n\t\tlocal && infra.includes('mailpit')\n\t\t\t? (() => {\n\t\t\t\t\tconst host = [MAIL_INBOX_LABEL, workspace.name, LOCAL_TLD]\n\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t.join('.');\n\t\t\t\t\treturn {\n\t\t\t\t\t\thost,\n\t\t\t\t\t\turl: `https://${host}${https !== 443 ? `:${https}` : ''}`,\n\t\t\t\t\t};\n\t\t\t\t})()\n\t\t\t: undefined;\n\n\t// The stack's MinIO signs with the stage's own key pair where it set one,\n\t// and otherwise with the stage's login: the local one `gkm dev` generated,\n\t// or — deployed — one derived from the stage's seed.\n\tconst storage: StackStorage | undefined = infra.includes('minio')\n\t\t? (() => {\n\t\t\t\tconst buckets = services.minio\n\t\t\t\t\t.map((id) => byId.get(id)?.name)\n\t\t\t\t\t.filter((name): name is string => Boolean(name))\n\t\t\t\t\t.sort();\n\t\t\t\treturn {\n\t\t\t\t\t...credential.containers.minio,\n\t\t\t\t\tbuckets,\n\t\t\t\t\tpolicies: bucketPolicies(plan).filter((p) =>\n\t\t\t\t\t\tbuckets.includes(p.bucket),\n\t\t\t\t\t),\n\t\t\t\t\tobjects: services.minio\n\t\t\t\t\t\t.map((id) => ({ id, name: byId.get(id)?.name }))\n\t\t\t\t\t\t.filter((b): b is { id: string; name: string } => Boolean(b.name))\n\t\t\t\t\t\t.sort((a, b) => a.name.localeCompare(b.name)),\n\t\t\t\t\t// Filled once each worker's environment is resolved, below.\n\t\t\t\t\twebhooks: [],\n\t\t\t\t\tlifecycles: bucketLifecycles(plan).filter((l) =>\n\t\t\t\t\t\tbuckets.includes(l.bucket),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t})()\n\t\t: undefined;\n\n\t// A bucket's events keys, so they resolve by where the bucket lives.\n\tconst bucketEventKeys = new Map<string, string>();\n\tfor (const resource of plan.resources) {\n\t\tif (resource.kind !== 'objects') continue;\n\t\tbucketEventKeys.set(\n\t\t\tprovidedKeyFor(resource.id, resource.kind, 'eventsConnectionString'),\n\t\t\tresource.id,\n\t\t);\n\t\tbucketEventKeys.set(\n\t\t\tprovidedKeyFor(resource.id, resource.kind, 'eventsToken'),\n\t\t\tresource.id,\n\t\t);\n\t}\n\n\t// Each file server over the stack's MinIO, at a host of its own on the\n\t// edge — the shape it has deployed: a domain serving a bucket.\n\tconst fileServers = new Map<string, { url: string; route: EdgeRoute }>();\n\tif (storage) {\n\t\tfor (const resource of plan.resources) {\n\t\t\tif (resource.kind !== 'file-server' || !resource.of) continue;\n\t\t\tif (!services.minio.includes(resource.of)) continue;\n\t\t\tif (custom[resource.envKey] !== undefined) continue;\n\t\t\tconst bucket = byId.get(resource.of);\n\t\t\tif (!bucket) continue;\n\n\t\t\tlet host: string;\n\t\t\tif (local) {\n\t\t\t\thost = hostFor(resource, workspace.name);\n\t\t\t} else {\n\t\t\t\tif (!domain) throw new NoDomainForStage(stage);\n\t\t\t\thost = fileServerHost(resource.id, domain);\n\t\t\t}\n\t\t\tfileServers.set(resource.id, {\n\t\t\t\turl: `https://${host}${local && https !== 443 ? `:${https}` : ''}`,\n\t\t\t\troute: {\n\t\t\t\t\tname: `files-${appKey(resource.id)}`,\n\t\t\t\t\thost,\n\t\t\t\t\tupstreams: [{ service: 'minio', port: 9000 }],\n\t\t\t\t\tstreaming: false,\n\t\t\t\t\tprefix: `/${bucket.name}`,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\t// What the stack says, without stopping, about a value it resolved.\n\tconst warnings: string[] = [];\n\n\t// Where each file server answers on this stage. Derived wherever the\n\t// stage's domain decides it — the stack's MinIO, or the CDN the s3\n\t// provider puts in front of a bucket at the same host — so an image built\n\t// ahead of the deploy that rewrites the stored copy (a domain change)\n\t// inlines the domain it is built for. Otherwise it is what the stage\n\t// stores: an address set by hand, or a bucket's own endpoint.\n\tconst objectsProvider = stageProvider(workspace, 'objects', stage);\n\tconst onCdn =\n\t\tobjectsProvider.mode === 'provider' &&\n\t\tobjectsProvider.name === 's3' &&\n\t\tservesOnCdn(objectsProvider.config as S3ObjectsConfig);\n\t// Where each bucket the s3 provider has not created yet will sign its\n\t// links: a site or mobile build inlines it, and a protected stage is built\n\t// on every push, before the release that first deploys it writes the\n\t// connection the origin is otherwise derived from.\n\tconst plannedOrigins = new Map<string, string>();\n\tif (\n\t\t!local &&\n\t\tobjectsProvider.mode === 'provider' &&\n\t\tobjectsProvider.name === 's3'\n\t) {\n\t\tfor (const resource of plan.resources) {\n\t\t\tif (resource.kind !== 'objects') continue;\n\t\t\tif (services.minio.includes(resource.id)) continue;\n\t\t\tconst connection = providedKeyFor(\n\t\t\t\tresource.id,\n\t\t\t\t'objects',\n\t\t\t\t'connectionString',\n\t\t\t);\n\t\t\tif (custom[connection] !== undefined) continue;\n\t\t\tconst origin = plannedSignedOrigin({\n\t\t\t\tworkspace,\n\t\t\t\tstage,\n\t\t\t\tscope: identity.scope,\n\t\t\t\tconfig: objectsProvider.config as S3ObjectsConfig,\n\t\t\t\tbucket: resource.id,\n\t\t\t});\n\t\t\tif (origin) {\n\t\t\t\tplannedOrigins.set(\n\t\t\t\t\tprovidedKeyFor(resource.id, 'objects', 'signedOrigin'),\n\t\t\t\t\torigin,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tconst fileServerUrls = new Map<string, string>();\n\tfor (const resource of plan.resources) {\n\t\tif (resource.kind !== 'file-server') continue;\n\t\tconst key = resource.envKey;\n\t\tconst stored = custom[key];\n\t\tconst inMinio = Boolean(\n\t\t\tresource.of && services.minio.includes(resource.of),\n\t\t);\n\t\tconst derived =\n\t\t\tfileServers.get(resource.id)?.url ??\n\t\t\t(!local && domain\n\t\t\t\t? `https://${fileServerHost(resource.id, domain)}`\n\t\t\t\t: undefined);\n\n\t\tif (onCdn && !inMinio && derived) {\n\t\t\tfileServerUrls.set(resource.id, derived);\n\t\t\tif (stored !== undefined && stored !== derived) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${key} is stored as ${stored}, and '${resource.id}' answers on ` +\n\t\t\t\t\t\t`${derived} — its CDN on the stage's domain. The stack is built ` +\n\t\t\t\t\t\t`and run with ${derived}; the deploy rewrites the stored copy.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (stored !== undefined) {\n\t\t\tfileServerUrls.set(resource.id, stored);\n\t\t\t// Set by hand — an external file server, or one over the stack's\n\t\t\t// MinIO — and kept. Said when the stage's domain gives another,\n\t\t\t// which is what a previous domain's address looks like.\n\t\t\tconst byHand = inMinio || objectsProvider.mode === 'external';\n\t\t\tif (byHand && derived && stored !== derived) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${key} is set by hand to ${stored}, and kept. On the stage's ` +\n\t\t\t\t\t\t`domain '${resource.id}' would answer on ${derived}; if ${stored} ` +\n\t\t\t\t\t\t`is a previous domain's, set it again: gkm secrets:set ${key} ` +\n\t\t\t\t\t\t`'${derived}' --stage ${stage}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst served = fileServers.get(resource.id)?.url;\n\t\tif (served) fileServerUrls.set(resource.id, served);\n\t}\n\n\t// Behind the shared edge, the services it routes to are on a network\n\t// every stack's public services share, where a bare name — `api` — would\n\t// be answered by each stack's. They are reached, from the edge and from\n\t// inside the stack alike, by an alias prefixed with the project.\n\tconst edgeServices = new Set(\n\t\tproxy === 'traefik'\n\t\t\t? [\n\t\t\t\t\t...apps.flatMap(replicaNames),\n\t\t\t\t\t...(fileServers.size > 0 ? ['minio'] : []),\n\t\t\t\t\t...(logsBase?.host && logsBase.public ? [LOGS_SERVICE] : []),\n\t\t\t\t\t...(mailInbox ? ['mailpit'] : []),\n\t\t\t\t]\n\t\t\t: [],\n\t);\n\tconst hostOf = (service: string) =>\n\t\tedgeServices.has(service) ? edgeAlias(project, service) : service;\n\tconst logs: StackLogs | undefined = logsBase && {\n\t\t...logsBase,\n\t\tappEnv: {\n\t\t\t...logsBase.appEnv,\n\t\t\tOTEL_EXPORTER_OTLP_ENDPOINT:\n\t\t\t\tlogsBase.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT.replace(\n\t\t\t\t\t`//${LOGS_SERVICE}:`,\n\t\t\t\t\t`//${hostOf(LOGS_SERVICE)}:`,\n\t\t\t\t),\n\t\t},\n\t};\n\n\t// Every key the stage resolves, with each app at its public address — what\n\t// a browser is handed, what an app says it is, and what one app calls\n\t// another on: through the edge, as it does deployed.\n\tconst derivation = {\n\t\tproject: workspace.name,\n\t\tcredentials: credential.containers,\n\t\tseed: credential.seed,\n\t\t// Mailpit on a deployed stage sends as the stage's domain.\n\t\t...(!local && domain ? { mailDomain: domain } : {}),\n\t\t// Each watched bucket in the stack's MinIO, whose events it posts to a\n\t\t// worker to relay onto the stack's broker.\n\t\trelayedBuckets: [\n\t\t\t...watchedBuckets(manifest, input.subscribers ?? {}).keys(),\n\t\t].filter((bucket) => services.minio.includes(bucket)),\n\t};\n\tconst publicAddresses = Object.fromEntries(\n\t\tapps.map((app) => [app.id, app.url]),\n\t);\n\t// Where each app also answers — its aliases, at the edge's port as its\n\t// own address is — so a surface trusts a site on every host it serves.\n\tconst aliasAddresses = Object.fromEntries(\n\t\tapps.map((app) => [\n\t\t\tapp.id,\n\t\t\t(app.aliases ?? []).map(\n\t\t\t\t(alias) =>\n\t\t\t\t\t`https://${alias}${local && https !== 443 ? `:${https}` : ''}`,\n\t\t\t),\n\t\t]),\n\t);\n\tconst outside = networkEnv(\n\t\tplan,\n\t\t{ ...derivation, addresses: publicAddresses, aliasAddresses },\n\t\thostOf,\n\t);\n\n\t/**\n\t * What a key resolves to for one app, from the stage's secrets where only\n\t * they can hold it, and the derivations otherwise.\n\t */\n\tconst valueFor = (\n\t\tapp: Pick<StackApp, 'name' | 'id' | 'kind'>,\n\t\tkey: string,\n\t\towner: PlannedResource | undefined,\n\t): string | undefined => {\n\t\t// The server's address is gkm's own: never in an app's environment.\n\t\tif (isReservedStageKey(key)) return undefined;\n\t\t// A bucket's events: relayed onto the stack's broker when the bucket is\n\t\t// in the stack's MinIO, and otherwise wherever the stage says — a topic\n\t\t// the storage publishes to — or nowhere.\n\t\tconst watching = bucketEventKeys.get(key);\n\t\tif (watching) {\n\t\t\tif (custom[key] !== undefined) return custom[key];\n\t\t\treturn services.minio.includes(watching) ? outside[key] : undefined;\n\t\t}\n\t\t// An inbox: locally, Mailpit's API and the project's local domain, as\n\t\t// `gkm dev` resolves them. Deployed, where its raw messages are read —\n\t\t// the bucket its provider made and wrote to the stage's secrets — and\n\t\t// the stage's domain, which mail is addressed to.\n\t\tif (owner?.kind === 'inbox') {\n\t\t\tif (local) return outside[key];\n\t\t\treturn deployedInboxValue(owner.id, key, {\n\t\t\t\treader: app.name,\n\t\t\t\tstage,\n\t\t\t\tdomain,\n\t\t\t\tsecrets: custom,\n\t\t\t});\n\t\t}\n\t\t// A deployed stage has no inbox: Mailpit runs only locally — not for a\n\t\t// backend, a site's bundle or a phone.\n\t\tif (!local && owner?.kind === 'email' && key.endsWith('_INBOX_URL')) {\n\t\t\treturn undefined;\n\t\t}\n\t\t// Mail and storage: what the stage set — a real server, a real bucket —\n\t\t// and otherwise the dev service it runs, which `services` has already\n\t\t// checked it may.\n\t\tif (owner && SERVICE_KINDS[owner.kind]) {\n\t\t\t// A file server's address is decided once, above, for every process\n\t\t\t// and every site's build alike.\n\t\t\tif (owner.kind === 'file-server') return fileServerUrls.get(owner.id);\n\t\t\tif (custom[key] !== undefined) return custom[key];\n\t\t\tif (owner.kind === 'objects') {\n\t\t\t\tconst origin = providedKeyFor(owner.id, owner.kind, 'signedOrigin');\n\t\t\t\tif (key === origin) {\n\t\t\t\t\treturn signedOrigins([owner.id], (k) => valueFor(app, k, owner))[key];\n\t\t\t\t}\n\t\t\t\t// The stack's MinIO serves only the buckets it was given: one on a\n\t\t\t\t// provider is what the provider wrote, or nothing yet.\n\t\t\t\tif (!services.minio.includes(owner.id)) return undefined;\n\t\t\t}\n\t\t\treturn outside[key];\n\t\t}\n\n\t\t// Supplied by somebody: a third party's credentials, and — deployed —\n\t\t// the secrets the stage generated.\n\t\tif (owner && suppliedOnly(owner.kind, owner.id, key, local)) {\n\t\t\tconst value = custom[key];\n\t\t\tif (value === undefined) {\n\t\t\t\tthrow new StageSecretMissing(app.name, key, stage);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\t// Set by hand wins over derived: it is the stage saying what it is.\n\t\tif (custom[key] !== undefined) return custom[key];\n\n\t\t// A cache, in the stack's Redis, by its name on the network — and a\n\t\t// WebSocket surface's publisher, on its pub/sub.\n\t\tif (owner?.kind === 'cache') return redis?.urls[key];\n\t\tif (\n\t\t\towner?.kind === 'websocket-api' &&\n\t\t\tkey === providedKeyFor(owner.id, owner.kind, 'publisherConnectionString')\n\t\t) {\n\t\t\treturn redis?.urls[key];\n\t\t}\n\n\t\t// A surface's or a site's address is its public one for every process\n\t\t// — a backend, a worker, a site's server — as `gkm dev` hands it.\n\t\treturn outside[key];\n\t};\n\n\t// What the stage resolves for its `Telemetry` node, before a process is\n\t// named: the stack's OpenObserve, or the provider `deploy.telemetry` names.\n\tconst telemetryValues: Record<string, string> | undefined = logs\n\t\t? telemetryEnv(\n\t\t\t\t{\n\t\t\t\t\tendpoint: logs.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT,\n\t\t\t\t\theaders: logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS,\n\t\t\t\t},\n\t\t\t\ttelemetry?.sampleRate ?? 1,\n\t\t\t)\n\t\t: telemetry?.provider === 'otlp'\n\t\t\t? otlpTelemetryEnv(telemetry)\n\t\t\t: undefined;\n\n\t/** Each key one backend process reads, resolved for this stage. */\n\tconst valuesFor = (\n\t\tapp: Pick<StackApp, 'name' | 'id' | 'kind'>,\n\t\tkeys: ReadonlySet<string>,\n\t): Record<string, string> => {\n\t\tconst values: Record<string, string> = {};\n\t\tfor (const key of [...keys].sort()) {\n\t\t\t// The node's keys are the stage's telemetry, added per process.\n\t\t\tif (isTelemetryKey(key)) continue;\n\t\t\tconst owner = owners.get(key) ?? storageOwner(key, plan);\n\t\t\tif ((STORAGE_KEYS as readonly string[]).includes(key)) {\n\t\t\t\t// The stage's own key pair where it set one — an external bucket\n\t\t\t\t// signs with it — and otherwise the stack's MinIO's.\n\t\t\t\tconst value = custom[key] ?? storageValue(key, storage);\n\t\t\t\tif (value !== undefined) values[key] = value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst value = valueFor(app, key, owner);\n\t\t\tif (value !== undefined) values[key] = value;\n\t\t}\n\t\treturn values;\n\t};\n\n\t// The stage's own keys — set by hand, read with `get('X')` — which every\n\t// process is handed, as `gkm dev` hands them (`processEnvKeys`).\n\tconst stageKeys = Object.keys(custom);\n\n\tfor (const app of apps) {\n\t\tconst site = manifest[app.id];\n\t\tif (site?.kind === 'site') {\n\t\t\tconst args = publicBuildValues(\n\t\t\t\tsite,\n\t\t\t\tmanifest,\n\t\t\t\t(key) => valueFor(app, key, owners.get(key)) ?? plannedOrigins.get(key),\n\t\t\t\tcustom,\n\t\t\t\t// Built here for a deployed stage, an image that cannot say where\n\t\t\t\t// its pages load files from is refused — not shipped without it.\n\t\t\t\t{ stage, requireFileOrigins: !local && app.build !== undefined },\n\t\t\t);\n\t\t\tif (app.prerender && input.prerenderRun) {\n\t\t\t\targs[PRERENDER_RUN_ARG] = input.prerenderRun;\n\t\t\t}\n\t\t\t// A Next build is tagged with its release — the image's tag — and\n\t\t\t// made with the stage's server actions key.\n\t\t\tObject.assign(\n\t\t\t\targs,\n\t\t\t\tnextBuildValues(site, stageTag(input.images.tag, stage), custom),\n\t\t\t);\n\t\t\tif (app.build && Object.keys(args).length > 0) app.build.args = args;\n\t\t\t// The build runs before the stack does: none of these answers yet.\n\t\t\tconst offline = offlineBuildHosts(site, manifest, (key) =>\n\t\t\t\tvalueFor(app, key, owners.get(key)),\n\t\t\t);\n\t\t\tif (app.build && offline.length > 0) app.build.offlineHosts = offline;\n\t\t\t// A static bundle reads nothing at runtime. A site that runs a server\n\t\t\t// — Next, TanStack Start — reads its edges and the stage's secrets\n\t\t\t// on it, as a backend does; its public values stay build arguments.\n\t\t\tif (!app.runtime) continue;\n\t\t}\n\t\t// Built to be pushed, an image is every stage's: what it reads at\n\t\t// runtime is the deploy's business, not the build's.\n\t\tif (input.buildOnly) continue;\n\n\t\tconst keys =\n\t\t\tprocessEnvKeys(manifest, { app: app.name }, stageKeys) ?? new Set();\n\t\tconst values = valuesFor(app, keys);\n\n\t\t// Telemetry: the stage's, to a backend with an edge to the node. A\n\t\t// site's server gets none — the exporter is the API's.\n\t\tapp.env = {\n\t\t\t...scopeTelemetryEnv(values, {\n\t\t\t\tuses:\n\t\t\t\t\tapp.kind !== 'site' && telemetryOf(manifest, app.id) !== undefined,\n\t\t\t\tserviceName: app.name,\n\t\t\t\t...(telemetryValues ? { telemetry: telemetryValues } : {}),\n\t\t\t}),\n\t\t\t// The key its build was made with, on a Next site's server alone.\n\t\t\t...(site?.kind === 'site' ? nextRuntimeValues(site, custom) : {}),\n\t\t\tNODE_ENV: 'production',\n\t\t\tPORT: String(app.port),\n\t\t\tSTAGE: stage,\n\t\t};\n\n\t\tfor (const [key, value] of Object.entries(app.env)) {\n\t\t\tif (/[\\r\\n]/.test(value)) throw new EnvValueMultiline(app.name, key);\n\t\t}\n\t}\n\n\t// A mobile app runs on a phone, which has only the public addresses — as\n\t// a browser does — so its values resolve as a site's do.\n\tconst mobileApps: StackMobileApp[] = [];\n\tfor (const declaration of Object.values(manifest)) {\n\t\tif (declaration.kind !== 'mobile-app') continue;\n\t\tconst app = {\n\t\t\tname: appKey(declaration.id),\n\t\t\tid: declaration.id,\n\t\t\tkind: 'site' as const,\n\t\t};\n\t\tmobileApps.push({\n\t\t\tname: app.name,\n\t\t\tid: app.id,\n\t\t\tvalues: publicBuildValues(\n\t\t\t\tdeclaration,\n\t\t\t\tmanifest,\n\t\t\t\t(key) => valueFor(app, key, owners.get(key)) ?? plannedOrigins.get(key),\n\t\t\t\tcustom,\n\t\t\t\t{ stage },\n\t\t\t),\n\t\t});\n\t}\n\n\t// A worker reaches every surface at its public address: it is never one,\n\t// so no address is its own — unless SNS pushes to it.\n\tfor (const worker of input.buildOnly ? [] : workers) {\n\t\tconst keys =\n\t\t\tprocessEnvKeys(manifest, { workers: [worker.id] }, stageKeys) ??\n\t\t\tnew Set();\n\t\tconst resolved = valuesFor(\n\t\t\t{ name: worker.name, id: worker.id, kind: 'rest-api' },\n\t\t\tkeys,\n\t\t);\n\t\tconst push = local\n\t\t\t? undefined\n\t\t\t: workerPush(worker, input.subscribers?.[worker.id] ?? [], resolved, {\n\t\t\t\t\tstage,\n\t\t\t\t\t...(domain ? { domain } : {}),\n\t\t\t\t});\n\t\tif (push) {\n\t\t\tworker.push = push;\n\t\t\tif (proxy === 'traefik') edgeServices.add(worker.name);\n\t\t}\n\t\tworker.env = {\n\t\t\t...scopeTelemetryEnv(resolved, {\n\t\t\t\tuses: telemetryOf(manifest, worker.id) !== undefined,\n\t\t\t\tserviceName: worker.name,\n\t\t\t\t...(telemetryValues ? { telemetry: telemetryValues } : {}),\n\t\t\t}),\n\t\t\t...(push && !input.recordingSubscriptions\n\t\t\t\t? {\n\t\t\t\t\t\t[SNS_SUBSCRIPTIONS_KEY]: recordedSubscriptions(\n\t\t\t\t\t\t\tworker,\n\t\t\t\t\t\t\tpush,\n\t\t\t\t\t\t\tinput.pushSubscriptions?.[worker.id],\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tNODE_ENV: 'production',\n\t\t\tPORT: String(worker.port),\n\t\t\tSTAGE: stage,\n\t\t};\n\t\tfor (const [key, value] of Object.entries(worker.env)) {\n\t\t\tif (/[\\r\\n]/.test(value)) throw new EnvValueMultiline(worker.name, key);\n\t\t}\n\t}\n\n\t// Each file server's processors: on its own host when the stack's MinIO\n\t// serves it — their patterns to their container, every other path to the\n\t// bucket — and otherwise on a host the CDN in front of the bucket reaches,\n\t// with the secret it sends.\n\tfor (const unit of processors) {\n\t\tconst served = fileServers.get(unit.id);\n\t\tif (served) {\n\t\t\tserved.route = {\n\t\t\t\t...served.route,\n\t\t\t\thandlers: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: unit.name,\n\t\t\t\t\t\tprefixes: unit.prefixes,\n\t\t\t\t\t\tupstreams: [{ service: unit.name, port: unit.port }],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} else if (!local && !input.buildOnly) {\n\t\t\tif (!domain) throw new NoDomainForStage(stage);\n\t\t\tconst key = originSecretKey(unit.id);\n\t\t\tconst secret = custom[key];\n\t\t\tif (!secret) throw new ProcessorOriginSecretMissing(unit.id, key, stage);\n\t\t\tunit.origin = { host: processorOriginHost(unit.id, domain), secret };\n\t\t}\n\t\tif (proxy === 'traefik' && (served || unit.origin)) {\n\t\t\tedgeServices.add(unit.name);\n\t\t}\n\n\t\tif (input.buildOnly) continue;\n\t\tconst keys =\n\t\t\tprocessEnvKeys(manifest, { processors: [unit.id] }, stageKeys) ??\n\t\t\tnew Set();\n\t\tunit.env = {\n\t\t\t// Telemetry: the stage's, when the file server has an edge to the node.\n\t\t\t...scopeTelemetryEnv(\n\t\t\t\tvaluesFor({ name: unit.name, id: unit.id, kind: 'rest-api' }, keys),\n\t\t\t\t{\n\t\t\t\t\tuses: telemetryOf(manifest, unit.id) !== undefined,\n\t\t\t\t\tserviceName: unit.name,\n\t\t\t\t\t...(telemetryValues ? { telemetry: telemetryValues } : {}),\n\t\t\t\t},\n\t\t\t),\n\t\t\tNODE_ENV: 'production',\n\t\t\tPORT: String(unit.port),\n\t\t\tSTAGE: stage,\n\t\t};\n\t\tfor (const [key, value] of Object.entries(unit.env)) {\n\t\t\tif (/[\\r\\n]/.test(value)) throw new EnvValueMultiline(unit.name, key);\n\t\t}\n\t}\n\n\t// Each watched bucket in the stack's MinIO posts its events to the worker\n\t// that runs one of its subscribers, across the stack's network — with the\n\t// token that worker was handed, so the two cannot disagree. Not where its\n\t// events come from SNS: then the storage publishes them itself.\n\tif (storage && !input.buildOnly) {\n\t\tconst watched = watchedBuckets(manifest, input.subscribers ?? {});\n\t\tfor (const [bucket, workerId] of watched) {\n\t\t\tif (!services.minio.includes(bucket)) continue;\n\t\t\tconst worker = workers.find((w) => w.id === workerId);\n\t\t\tconst relay =\n\t\t\t\tworker?.env?.[\n\t\t\t\t\tprovidedKeyFor(bucket, 'objects', 'eventsConnectionString')\n\t\t\t\t];\n\t\t\tconst token =\n\t\t\t\tworker?.env?.[providedKeyFor(bucket, 'objects', 'eventsToken')];\n\t\t\tif (!worker || !relay || relay.startsWith('sns:') || !token) continue;\n\t\t\tstorage.webhooks.push({\n\t\t\t\tbucket,\n\t\t\t\tendpoint: `http://${hostOf(worker.name)}:${worker.port}${objectsRoute(bucket)}`,\n\t\t\t\ttoken,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Mailpit posts what an inbox receives to the worker that runs every\n\t// inbox subscriber, across the stack's network, with the token that worker\n\t// was handed. Locally only: deployed, SES publishes to the inbox's topic.\n\tlet inboxRelay: string | undefined;\n\tif (local && infra.includes('mailpit') && !input.buildOnly) {\n\t\tconst relayId = inboxRelayWorker(manifest, input.subscribers ?? {});\n\t\tconst relay = workers.find((w) => w.id === relayId);\n\t\tconst token = relay?.env?.[INBOX_RELAY_TOKEN_KEY];\n\t\tif (relay && token) {\n\t\t\tinboxRelay = inboxWebhookUrl(\n\t\t\t\t`http://${hostOf(relay.name)}:${relay.port}`,\n\t\t\t\ttoken,\n\t\t\t);\n\t\t}\n\t}\n\n\t// The stage's certificate, as the proxy's container reads it: its own,\n\t// where it set one — any stage, either proxy — and otherwise, on the\n\t// local stage, the one gkm's local CA issues as the stack is written. A\n\t// deployed stage without one asks Let's Encrypt.\n\tconst tls: EdgeTls =\n\t\tcertificate || local\n\t\t\t? {\n\t\t\t\t\tkind: 'files',\n\t\t\t\t\t...(proxy === 'caddy'\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tcertFile: `${CADDY_TLS_DIR}/cert.pem`,\n\t\t\t\t\t\t\t\tkeyFile: `${CADDY_TLS_DIR}/key.pem`,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: edgeCertificatePaths(project)),\n\t\t\t\t}\n\t\t\t: { kind: 'acme' };\n\t// gkm's local CA: the local stage's issuer, unless it set its own.\n\tconst authority =\n\t\tlocal && !certificate\n\t\t\t? (input.localAuthority ?? localAuthorityPaths(gkmHome()))\n\t\t\t: undefined;\n\t// The root the stage's certificate chains to, on this machine: gkm's, or\n\t// the one its own certificate names. What the local stack's containers\n\t// trust for the stage's public hosts.\n\tconst root = authority?.certFile ?? certificate?.caFile;\n\n\t// The stage's backups: a deployed stage with Postgres, unless it said\n\t// `false`. A stack that only builds runs nothing, so has none.\n\tconst backupsChoice = input.buildOnly\n\t\t? undefined\n\t\t: stageBackups(workspace, manifest, stage);\n\tconst backups =\n\t\tbackupsChoice?.mode === 'on' && infra.includes('postgres')\n\t\t\t? stackBackups({\n\t\t\t\t\tworkspace,\n\t\t\t\t\tstage,\n\t\t\t\t\tproject,\n\t\t\t\t\tplan,\n\t\t\t\t\tbackups: backupsChoice.backups,\n\t\t\t\t\tcustom,\n\t\t\t\t\tseed,\n\t\t\t\t\tsuperuser: credential.containers.postgres,\n\t\t\t\t\t...(telemetryValues ? { telemetry: telemetryValues } : {}),\n\t\t\t\t})\n\t\t\t: undefined;\n\n\t// The sites behind a password on this stage, each with its login.\n\tif (!local) {\n\t\tfor (const app of apps) {\n\t\t\tconst site = manifest[app.id];\n\t\t\tif (site?.kind !== 'site') continue;\n\t\t\tconst key = sitePasswordKey(manifest, site, stage);\n\t\t\tif (key) app.auth = siteAuth(stage, key, custom);\n\t\t}\n\t}\n\n\t// The wildcard site's tenants, on a deployed stage: every label under\n\t// the domain nothing else answers, and where their certificate comes from.\n\tconst wildcard = local\n\t\t? undefined\n\t\t: stackWildcard(apps, {\n\t\t\t\tmanifest,\n\t\t\t\tbyId,\n\t\t\t\tworkspace,\n\t\t\t\tstage,\n\t\t\t\tproxy,\n\t\t\t\tcertificate: certificate !== undefined,\n\t\t\t\thostOf,\n\t\t\t});\n\n\t// One route per public host — the data both proxies render.\n\tconst routes: EdgeRoute[] = [\n\t\t...apps.map(\n\t\t\t(app): EdgeRoute => ({\n\t\t\t\tname: app.name,\n\t\t\t\thost: app.host,\n\t\t\t\t...(app.aliases?.length ? { aliases: app.aliases } : {}),\n\t\t\t\t...(app.redirects?.length\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t// Only a site has redirects, so its URL is the https origin.\n\t\t\t\t\t\t\tredirects: { hosts: app.redirects, to: app.url },\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(wildcard?.site === app.id ? { wildcard: wildcard.edge } : {}),\n\t\t\t\tupstreams: replicaNames(app).map((service) => ({\n\t\t\t\t\tservice,\n\t\t\t\t\tport: app.port,\n\t\t\t\t})),\n\t\t\t\tstreaming: true,\n\t\t\t\t...(app.auth\n\t\t\t\t\t? { auth: { user: app.auth.user, hash: app.auth.hash } }\n\t\t\t\t\t: {}),\n\t\t\t\t...(app.limits ? { limits: app.limits } : {}),\n\t\t\t\thealth: app.kind === 'site' ? '/' : '/health',\n\t\t\t}),\n\t\t),\n\t\t...[...fileServers.values()].map(({ route }) => route),\n\t\t...processors.flatMap(({ name, port, prefixes, origin }): EdgeRoute[] =>\n\t\t\torigin\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\thost: origin.host,\n\t\t\t\t\t\t\tupstreams: [{ service: name, port }],\n\t\t\t\t\t\t\tstreaming: false,\n\t\t\t\t\t\t\tprefixes,\n\t\t\t\t\t\t\trequireHeader: {\n\t\t\t\t\t\t\t\tname: ORIGIN_VERIFY_HEADER,\n\t\t\t\t\t\t\t\tvalue: origin.secret,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\thealth: '/health',\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t\t),\n\t\t...workers.flatMap(({ name, port, push }): EdgeRoute[] =>\n\t\t\tpush\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\thost: push.host,\n\t\t\t\t\t\t\tupstreams: [{ service: name, port }],\n\t\t\t\t\t\t\tstreaming: false,\n\t\t\t\t\t\t\tpaths: push.paths,\n\t\t\t\t\t\t\thealth: '/health',\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t\t),\n\t\t...(logs?.host && logs.public\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: LOGS_SERVICE,\n\t\t\t\t\t\thost: logs.host,\n\t\t\t\t\t\tupstreams: [{ service: LOGS_SERVICE, port: LOGS_PORT }],\n\t\t\t\t\t\tstreaming: true,\n\t\t\t\t\t\tallow: logs.public.allow,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t];\n\tif (mailInbox) {\n\t\t// Before every other route is checked against every other, so an app\n\t\t// on the inbox's host is told what the host is for.\n\t\tconst taken = routes.find((route) =>\n\t\t\trouteHosts(route).includes(mailInbox.host),\n\t\t);\n\t\tif (taken) throw new MailInboxHostTaken(mailInbox.host, taken.name);\n\t\troutes.push({\n\t\t\tname: 'mailpit',\n\t\t\thost: mailInbox.host,\n\t\t\tupstreams: [{ service: 'mailpit', port: MAILPIT_WEB_PORT }],\n\t\t\t// Its UI follows new mail live, over a websocket.\n\t\t\tstreaming: true,\n\t\t});\n\t}\n\tassertHostsUnique(routes);\n\tconst layout = input.layout ?? defaultLayout(workspace.root);\n\tconst compose = stackFile({\n\t\tproject,\n\t\tplan,\n\t\tinfra,\n\t\tapps,\n\t\tworkers,\n\t\tprocessors,\n\t\tcredentials: credential.containers,\n\t\t...(storage ? { storage } : {}),\n\t\t...(inboxRelay ? { inboxRelay } : {}),\n\t\t...(logs ? { logs } : {}),\n\t\t...(redis ? { redis } : {}),\n\t\t...(backups ? { backups } : {}),\n\t\thttps,\n\t\thttp,\n\t\tcomposeDir: join(workspace.root, stackDir(stage)),\n\t\tbuildRoot: layout.buildRoot,\n\t\tworkspaceRoot: workspace.root,\n\t\tenvFiles: !input.buildOnly,\n\t\tproxy,\n\t\tedge: new Map(\n\t\t\t[...edgeServices].map((service) => [service, hostOf(service)]),\n\t\t),\n\t\t// The local stage's own public hosts, which a container's own loopback\n\t\t// would answer, and the root their certificate chains to.\n\t\t...(local\n\t\t\t? {\n\t\t\t\t\tlocalEdge: {\n\t\t\t\t\t\thosts: stackPublicHosts(routes),\n\t\t\t\t\t\t...(root ? { authority: root } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t});\n\n\tconst dockerfiles: Record<string, string> = {};\n\tfor (const app of apps) {\n\t\tif (!app.build) continue;\n\t\t// The same Dockerfile `gkm docker` writes: the image is built inside\n\t\t// Docker from a pruned slice of the build root, and nothing is built\n\t\t// here first.\n\t\tdockerfiles[app.build.dockerfile] = appDockerfile(\n\t\t\tapp.name,\n\t\t\tworkspace.apps[app.name]!,\n\t\t\t{\n\t\t\t\tlayout,\n\t\t\t\tworkspaceRoot: workspace.root,\n\t\t\t\tapps: workspace.apps,\n\t\t\t\tmanifest,\n\t\t\t\tcache: STACK_CACHE,\n\t\t\t\t// A site's clients trace at this stage's sample rate.\n\t\t\t\tworkspace,\n\t\t\t\tstage,\n\t\t\t\t// Every build argument the site is handed, declared, or the\n\t\t\t\t// build drops it — but the run it is pre-rendered for, which\n\t\t\t\t// its Dockerfile declares itself.\n\t\t\t\t...(app.kind === 'site' && app.build.args\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpublicUrlArgs: Object.keys(app.build.args).filter(\n\t\t\t\t\t\t\t\t(key) => key !== PRERENDER_RUN_ARG,\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);\n\t}\n\tfor (const worker of workers) {\n\t\tif (!worker.build) continue;\n\t\tdockerfiles[worker.build.dockerfile] = workerDockerfile(\n\t\t\t{ id: worker.id, name: worker.name, app: worker.host },\n\t\t\tworkspace.apps[worker.host]!,\n\t\t\t{\n\t\t\t\tlayout,\n\t\t\t\tworkspaceRoot: workspace.root,\n\t\t\t\tmanifest,\n\t\t\t\tcache: STACK_CACHE,\n\t\t\t},\n\t\t);\n\t}\n\tfor (const unit of processors) {\n\t\tif (!unit.build) continue;\n\t\tdockerfiles[unit.build.dockerfile] = processorDockerfile(\n\t\t\t{ id: unit.id, name: unit.name, app: unit.host },\n\t\t\tworkspace.apps[unit.host]!,\n\t\t\t{\n\t\t\t\tlayout,\n\t\t\t\tworkspaceRoot: workspace.root,\n\t\t\t\tmanifest,\n\t\t\t\tcache: STACK_CACHE,\n\t\t\t},\n\t\t);\n\t}\n\n\treturn {\n\t\tproject,\n\t\tstage,\n\t\tlocal,\n\t\t...(authority ? { authority } : {}),\n\t\tapps,\n\t\tworkers,\n\t\tprocessors,\n\t\tmobileApps,\n\t\tinfra,\n\t\tcompose,\n\t\tproxy,\n\t\troutes,\n\t\t...(wildcard\n\t\t\t? {\n\t\t\t\t\twildcard: {\n\t\t\t\t\t\tsite: wildcard.site,\n\t\t\t\t\t\thost: `*.${wildcard.edge.domain}`,\n\t\t\t\t\t\ttls: wildcard.edge.tls.kind,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(proxy === 'caddy'\n\t\t\t? {\n\t\t\t\t\tcaddyfile: edgeCaddyfile(routes, {\n\t\t\t\t\t\ttls,\n\t\t\t\t\t\tedgeToken: outside[EDGE_TOKEN_KEY],\n\t\t\t\t\t\t...(local ? { redirects: false } : {}),\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\ttraefik: traefikDynamicFile(routes, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\ttls,\n\t\t\t\t\t\tedgeToken: outside[EDGE_TOKEN_KEY],\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t...(certificate ? { tls: certificate } : {}),\n\t\tdockerfiles,\n\t\tplan,\n\t\tcredential,\n\t\tresolution: {\n\t\t\t...derivation,\n\t\t\t// A file server at its address, as the apps are handed it.\n\t\t\taddresses: {\n\t\t\t\t...publicAddresses,\n\t\t\t\t...Object.fromEntries(fileServerUrls),\n\t\t\t},\n\t\t},\n\t\t...(storage ? { storage } : {}),\n\t\tdevServices: local ? [] : devServicesUsed(services),\n\t\t...(logs ? { logs } : {}),\n\t\t...(telemetry ? { telemetry } : {}),\n\t\t...(redis ? { redis } : {}),\n\t\t...(backups ? { backups } : {}),\n\t\t...(mailInbox ? { mailInbox } : {}),\n\t\twarnings,\n\t};\n}\n\n/** The stack's MinIO's value for one of the S3 client's keys. */\nfunction storageValue(\n\tkey: string,\n\tstorage: StackStorage | undefined,\n): string | undefined {\n\tif (!storage) return undefined;\n\tif (key === 'AWS_ACCESS_KEY_ID') return storage.user;\n\tif (key === 'AWS_SECRET_ACCESS_KEY') return storage.password;\n\tif (key === 'AWS_REGION') return MINIO_REGION;\n\treturn undefined;\n}\n\n/** Which bucket an S3 credential key belongs to — the first one declared. */\nfunction storageOwner(key: string, plan: Plan): PlannedResource | undefined {\n\tif (!(STORAGE_KEYS as readonly string[]).includes(key)) return undefined;\n\treturn plan.resources.find((r) => r.kind === 'objects');\n}\n\n/** The apps a stack runs: every API and every site, at its stage address. */\nfunction stackApps(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tplan: Plan,\n\toptions: {\n\t\tlocal: boolean;\n\t\tstage: string;\n\t\thttps: number;\n\t\tidentity: DeployIdentity;\n\t\timages: StackInput['images'];\n\t},\n): StackApp[] {\n\tconst apps: StackApp[] = [];\n\tconst resources = new Map(plan.resources.map((r) => [r.id, r]));\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\tconst name = appKey(id);\n\t\tconst app = workspace.apps[name];\n\t\tconst resource = resources.get(id);\n\t\tif (!app || !resource || !app.port) continue;\n\n\t\tconst { host, aliases, redirects } = appHosts(\n\t\t\tname,\n\t\t\tapp,\n\t\t\tworkspace,\n\t\t\tresource,\n\t\t\toptions,\n\t\t);\n\t\tconst site = declaration.kind === 'site';\n\t\tconst { ref, tag } = stackImage(name, options);\n\n\t\tapps.push({\n\t\t\tapp: name,\n\t\t\tname,\n\t\t\tid,\n\t\t\tkind: declaration.kind,\n\t\t\t...(declaration.kind === 'site' ? { variant: declaration.variant } : {}),\n\t\t\treplicas:\n\t\t\t\tdeclaration.kind === 'websocket-api' ? (declaration.replicas ?? 1) : 1,\n\t\t\t...(declaration.kind === 'websocket-api' && declaration.limits\n\t\t\t\t? { limits: declaration.limits }\n\t\t\t\t: {}),\n\t\t\truntime: !site || runsServer(declaration),\n\t\t\tpath: app.path,\n\t\t\tport: app.port,\n\t\t\thost,\n\t\t\t...(aliases.length ? { aliases } : {}),\n\t\t\t...(redirects.length ? { redirects } : {}),\n\t\t\turl: `${declaration.kind === 'websocket-api' ? 'wss' : 'https'}://${host}${options.local && options.https !== 443 ? `:${options.https}` : ''}`,\n\t\t\tref,\n\t\t\ttag,\n\t\t\t...(options.images.mode === 'build'\n\t\t\t\t? {\n\t\t\t\t\t\tbuild: {\n\t\t\t\t\t\t\tdockerfile: `${stackDir(options.stage)}/Dockerfile.${name}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t});\n\t}\n\n\t// A site built against its stage waits on each app its edges name.\n\tconst byId = new Map(apps.map((app) => [app.id, app.name]));\n\tfor (const app of apps) {\n\t\tconst declaration = manifest[app.id];\n\t\tif (declaration?.kind !== 'site' || declaration.prerender !== 'stage') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst against = declaration.dependencies\n\t\t\t.map(({ target }) => byId.get(target))\n\t\t\t.filter((name): name is string => !!name && name !== app.name);\n\t\tapp.prerender = { against: [...new Set(against)].sort() };\n\t}\n\n\treturn apps.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Where SNS pushes to a worker on a deployed stage, or nothing when it pushes\n * to none of its subscribers.\n *\n * A subscriber is pushed to when the connection string its deliveries come\n * from — its topic's, or its bucket's events — as this stage resolved it for\n * the worker, is an SNS one — the same test the worker's own\n * startup makes, so the edge exposes a route exactly when the worker mounts\n * it. Each such route, and nothing else the worker serves, answers on\n * `<worker>.<domain>`.\n */\nexport function workerPush(\n\tworker: Pick<StackWorker, 'name'>,\n\tsubscribers: readonly BoundSubscriber[],\n\tenv: Readonly<Record<string, string>>,\n\toptions: { stage: string; domain?: string },\n): WorkerPush | undefined {\n\tconst pushed = subscribers\n\t\t.filter(({ connectionKey }) => env[connectionKey]?.startsWith('sns:'))\n\t\t.filter(\n\t\t\t(subscriber, index, all) =>\n\t\t\t\tall.findIndex((s) => s.name === subscriber.name) === index,\n\t\t)\n\t\t.sort((a, b) => a.name.localeCompare(b.name));\n\tif (pushed.length === 0) return undefined;\n\tif (!options.domain) throw new NoDomainForStage(options.stage);\n\n\tconst host = `${worker.name}.${options.domain}`;\n\tconst url = `https://${host}`;\n\treturn {\n\t\thost,\n\t\turl,\n\t\tpaths: pushed.map(({ name }) => subscriberRoute(name)),\n\t\tsubscribers: pushed.map(({ name, connectionKey, events }) => ({\n\t\t\tname,\n\t\t\tconnectionKey,\n\t\t\tendpoint: `${url}${subscriberRoute(name)}`,\n\t\t\t...(events ? { events } : {}),\n\t\t})),\n\t};\n}\n\n/** A pushed subscriber the deploy recorded no SNS subscription for. */\nexport class PushSubscriptionMissing extends GkmError {\n\tconstructor(\n\t\treadonly worker: string,\n\t\treadonly subscriber: string,\n\t) {\n\t\tsuper(\n\t\t\t`SNS pushes to '${subscriber}' on the worker '${worker}', and the ` +\n\t\t\t\t`deploy recorded no subscription for it, so the worker would mount ` +\n\t\t\t\t`no route and SNS would deliver nowhere. Deploy the stage, which ` +\n\t\t\t\t`subscribes each pushed subscriber and records its ARN.`,\n\t\t);\n\t\tthis.name = 'PushSubscriptionMissing';\n\t}\n}\n\n/**\n * The worker's `GKM_SNS_SUBSCRIPTIONS`: each pushed subscriber's recorded\n * subscription ARN, and nothing for a subscriber it does not run.\n *\n * @throws {PushSubscriptionMissing} when one has none\n */\nfunction recordedSubscriptions(\n\tworker: Pick<StackWorker, 'name'>,\n\tpush: WorkerPush,\n\trecorded: Readonly<Record<string, string>> = {},\n): string {\n\tconst arns: Record<string, string> = {};\n\tfor (const { name } of push.subscribers) {\n\t\tconst arn = recorded[name];\n\t\tif (!arn) throw new PushSubscriptionMissing(worker.name, name);\n\t\tarns[name] = arn;\n\t}\n\treturn JSON.stringify(arns);\n}\n\n/**\n * A wildcard site on a deployed stage with nowhere to get a certificate for\n * its tenants' hosts from. Let's Encrypt issues a wildcard certificate only\n * over the DNS challenge, so the stage either brings its own or gives the\n * proxy a way to get one. On the stack's own Caddy that is a certificate per\n * host on demand, and only there is the site's `hosts` route required: the\n * one place the rule lives.\n */\nexport class WildcardSiteCertificateMissing extends GkmError {\n\tconstructor(\n\t\treadonly site: string,\n\t\treadonly stage: string,\n\t\treadonly proxy: ComposeProxy,\n\t\treadonly domain: string,\n\t) {\n\t\tsuper(\n\t\t\tproxy === 'traefik'\n\t\t\t\t? `'${site}' answers on every subdomain of ${domain}, and '${stage}' ` +\n\t\t\t\t\t\t`has no certificate for them. Set deploy.compose.tls for ` +\n\t\t\t\t\t\t`'${stage}' to a *.${domain} certificate, or manage ${domain} ` +\n\t\t\t\t\t\t`with dns: { '<root domain>': { provider: ${Object.keys(\n\t\t\t\t\t\t\tACME_DNS_CHALLENGES,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.map((p) => `'${p}'`)\n\t\t\t\t\t\t\t.join(' | ')} } } so the shared edge gets one over the ` +\n\t\t\t\t\t\t`DNS challenge.`\n\t\t\t\t: `'${site}' answers on every subdomain of ${domain}, and '${stage}' ` +\n\t\t\t\t\t\t`has no certificate for them. Set deploy.compose.tls for ` +\n\t\t\t\t\t\t`'${stage}' to a *.${domain} certificate, or let Caddy get ` +\n\t\t\t\t\t\t`one per tenant on demand by giving the site \\`hosts\\` — ` +\n\t\t\t\t\t\t`\\`hosts: { surface: api, path: '/tenants/hosts' }\\`, a GET ` +\n\t\t\t\t\t\t`route answering 200 for a tenant. On-demand certificates ` +\n\t\t\t\t\t\t`need it: Caddy asks it before issuing one, so no request ` +\n\t\t\t\t\t\t`can make it get certificates for hosts that are no tenant.`,\n\t\t);\n\t\tthis.name = 'WildcardSiteCertificateMissing';\n\t}\n}\n\n/**\n * A deployed stage's wildcard site, as its edge serves it: the labels it\n * never takes, and its certificate — the stage's own (`deploy.compose.tls`)\n * first; then, on the shared Traefik edge, a `*.<domain>` one over the DNS\n * challenge when a provider the edge can answer it through manages the\n * domain (`ACME_DNS_CHALLENGES`); on the stack's own Caddy, one\n * per host on demand, asked of the site's `hosts` route. That last is the\n * only certificate that needs `hosts`: behind a wildcard one every label but\n * the protected ones reaches the site, and the app answers an unknown tenant.\n *\n * @throws {WildcardSiteCertificateMissing} when neither applies\n */\nfunction stackWildcard(\n\tapps: readonly StackApp[],\n\toptions: {\n\t\tmanifest: ConstructManifest;\n\t\tbyId: ReadonlyMap<string, PlannedResource>;\n\t\tworkspace: NormalizedWorkspace;\n\t\tstage: string;\n\t\tproxy: ComposeProxy;\n\t\tcertificate: boolean;\n\t\thostOf: (service: string) => string;\n\t},\n): { site: string; edge: EdgeWildcard } | undefined {\n\tconst { manifest, workspace, stage, proxy } = options;\n\tconst app = apps.find((a) => isWildcardSite(manifest[a.id]));\n\tif (!app) return undefined;\n\tconst declaration = manifest[app.id];\n\tif (!isWildcardSite(declaration)) return undefined;\n\n\tconst domain = workspace.domains?.[stage];\n\tif (!domain) throw new NoDomainForStage(stage);\n\tconst except = options.byId.get(app.id)?.protectedSubdomains ?? [];\n\n\tconst tls = ((): EdgeWildcard['tls'] => {\n\t\tif (options.certificate) return { kind: 'stage' };\n\t\tif (proxy === 'traefik') {\n\t\t\tconst zone = acmeDnsZone(workspace, stage);\n\t\t\tif (zone) return { kind: 'dns', provider: zone.provider };\n\t\t} else if (declaration.hosts) {\n\t\t\tconst surface = apps.find((a) => a.id === declaration.hosts?.surface);\n\t\t\tif (surface) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'on-demand',\n\t\t\t\t\task: `http://${options.hostOf(surface.name)}:${surface.port}${declaration.hosts.path}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tthrow new WildcardSiteCertificateMissing(app.id, stage, proxy, domain);\n\t})();\n\n\treturn { site: app.id, edge: { domain, except, tls } };\n}\n\n/**\n * The first label under `stage`'s domain of every other stage's domain that\n * sits beneath it — `staging` for `staging.example.com` (or\n * `a.staging.example.com`) under `example.com`.\n */\nexport function nestedStageLabels(\n\tdomains: NormalizedWorkspace['domains'],\n\tstage: string,\n): string[] {\n\tconst own = domains?.[stage]?.toLowerCase();\n\tif (!own) return [];\n\tconst labels = new Set<string>();\n\tfor (const [other, domain] of Object.entries(domains ?? {})) {\n\t\tif (other === stage || !domain) continue;\n\t\tconst lower = domain.toLowerCase();\n\t\tif (!lower.endsWith(`.${own}`)) continue;\n\t\tconst rest = lower.slice(0, -(own.length + 1)).split('.');\n\t\tlabels.add(rest.at(-1)!);\n\t}\n\treturn [...labels].sort();\n}\n\n/** Two constructs the edge would answer on one host. */\nexport class EdgeHostTaken extends GkmError {\n\tconstructor(\n\t\treadonly host: string,\n\t\treadonly first: string,\n\t\treadonly second: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${first}' and '${second}' would both answer on ${host}, and the ` +\n\t\t\t\t`edge can send a host to only one of them. Give one a subdomain of ` +\n\t\t\t\t`its own, or rename it.`,\n\t\t);\n\t\tthis.name = 'EdgeHostTaken';\n\t}\n}\n\n/**\n * Refuse a stack where one host would be routed to two services — every\n * host of every route, its aliases and redirects included.\n */\nfunction assertHostsUnique(routes: readonly EdgeRoute[]): void {\n\tconst claimed = new Map<string, string>();\n\tfor (const route of routes) {\n\t\tfor (const host of routeHosts(route)) {\n\t\t\tconst first = claimed.get(host);\n\t\t\tif (first !== undefined && first !== route.name) {\n\t\t\t\tthrow new EdgeHostTaken(host, first, route.name);\n\t\t\t}\n\t\t\tclaimed.set(host, route.name);\n\t\t}\n\t}\n}\n\n/**\n * The image an app, worker or processor runs on the stage: the release's tag\n * with the stage on it (`stageTag`), as every target names its images.\n */\nfunction stackImage(\n\tname: string,\n\toptions: {\n\t\tstage: string;\n\t\tidentity: DeployIdentity;\n\t\timages: StackInput['images'];\n\t},\n): Pick<AppImage, 'ref' | 'tag'> {\n\tconst tag = stageTag(options.images.tag, options.stage);\n\treturn {\n\t\tref: validateImageRef(\n\t\t\timageRef(options.identity, name, options.images.registry, tag),\n\t\t),\n\t\ttag,\n\t};\n}\n\n/** Each processor unit's image, and where it is built from. */\nfunction stackProcessors(\n\tunits: readonly ProcessorUnit[],\n\toptions: {\n\t\tmanifest: ConstructManifest;\n\t\tstage: string;\n\t\tidentity: DeployIdentity;\n\t\timages: StackInput['images'];\n\t},\n): StackProcessor[] {\n\treturn units.map((unit) => {\n\t\tconst server = options.manifest[unit.id];\n\t\tconst processors =\n\t\t\tserver?.kind === 'file-server' ? (server.processors ?? []) : [];\n\t\treturn {\n\t\t\tapp: unit.name,\n\t\t\tname: unit.name,\n\t\t\tid: unit.id,\n\t\t\thost: unit.app,\n\t\t\tport: PROCESSOR_PORT,\n\t\t\tprefixes: [...new Set(processors.map((p) => p.prefix))].sort(),\n\t\t\t...stackImage(unit.name, options),\n\t\t\t...(options.images.mode === 'build'\n\t\t\t\t? {\n\t\t\t\t\t\tbuild: {\n\t\t\t\t\t\t\tdockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t});\n}\n\n/** Each worker's image, and where it is built from. */\nfunction stackWorkers(\n\tunits: readonly WorkerUnit[],\n\toptions: {\n\t\tstage: string;\n\t\tidentity: DeployIdentity;\n\t\timages: StackInput['images'];\n\t},\n): StackWorker[] {\n\treturn units.map((unit) => ({\n\t\tapp: unit.name,\n\t\tname: unit.name,\n\t\tid: unit.id,\n\t\thost: unit.app,\n\t\tport: WORKER_PORT,\n\t\t...stackImage(unit.name, options),\n\t\t...(options.images.mode === 'build'\n\t\t\t? {\n\t\t\t\t\tbuild: {\n\t\t\t\t\t\tdockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}`,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t}));\n}\n\n/**\n * The hosts an app answers on for a stage: the `gkm dev` edge's\n * `*.localhost` names for the local stage (`hostsFor`), and the stage's\n * domain — by the same rule a deploy follows — for any other. Its aliases\n * and redirects are labels under the stage's domain, as its own is.\n */\nfunction appHosts(\n\tname: string,\n\tapp: NormalizedAppConfig,\n\tworkspace: NormalizedWorkspace,\n\tresource: PlannedResource,\n\toptions: { local: boolean; stage: string },\n): ResourceHosts {\n\tif (options.local) return hostsFor(resource, workspace.name);\n\tconst domain = workspace.domains?.[options.stage];\n\t// Every label under the stage's domain, never the domain itself: a\n\t// wildcard site is no stage's root, whatever else the project has.\n\tif (resource.subdomain === WILDCARD_SUBDOMAIN) {\n\t\tif (!domain) throw new NoDomainForStage(options.stage);\n\t\treturn {\n\t\t\thost: `${WILDCARD_SUBDOMAIN}.${domain}`,\n\t\t\taliases: [],\n\t\t\tredirects: [],\n\t\t};\n\t}\n\n\tconst host = resolveHost(\n\t\tname,\n\t\tapp,\n\t\toptions.stage,\n\t\tworkspace.domains,\n\t\tisMainFrontendApp(name, app, workspace.apps),\n\t);\n\tconst under = (label: string) => {\n\t\tif (!domain) throw new NoDomainForStage(options.stage);\n\t\treturn `${label}.${domain}`;\n\t};\n\treturn {\n\t\thost,\n\t\taliases: (resource.aliases ?? []).map(under),\n\t\tredirects: (resource.redirects ?? []).map(under),\n\t};\n}\n\n/** An app's compose services, one per replica: `api`, `api-2`, `api-3`. */\nexport function replicaNames(\n\tapp: Pick<StackApp, 'name' | 'replicas'>,\n): string[] {\n\treturn [\n\t\tapp.name,\n\t\t...Array.from(\n\t\t\t{ length: app.replicas - 1 },\n\t\t\t(_, i) => `${app.name}-${i + 2}`,\n\t\t),\n\t];\n}\n\n/** Where an app container reads gkm's root certificate: mounted read-only. */\nexport const LOCAL_CA_IN_CONTAINER = '/etc/gkm/local-ca.pem';\n\n/**\n * The local stage's public hosts a container can be pointed at: every\n * route's but a wildcard's, which no host entry can name.\n */\nfunction stackPublicHosts(routes: readonly EdgeRoute[]): string[] {\n\treturn [...new Set(routes.flatMap(routeHosts))]\n\t\t.filter((host) => !host.startsWith('*.'))\n\t\t.sort();\n}\n\n/**\n * What a local stack's container needs to call the stage's own public hosts —\n * `https://api.<project>.localhost`, which a site's server-side code is\n * handed because a browser is.\n *\n * Inside a container `*.localhost` is its own loopback, so each host is\n * resolved to the host's gateway, where the edge — the stack's Caddy, or the\n * shared Traefik edge — publishes its ports. Not a network alias on the edge:\n * the address may carry the edge's published port\n * (`https://api.shop.localhost:8443`), which only the host answers on. And the\n * container trusts the root the edge's certificate chains to — gkm's, or the\n * one the stage's own certificate names — its public certificate, never a\n * key, mounted read-only.\n */\nexport function localEdgeAccess(edge: {\n\thosts: readonly string[];\n\tauthority?: string;\n}): {\n\textra_hosts: string[];\n\tvolumes: string[];\n\tenvironment: Record<string, string>;\n} {\n\treturn {\n\t\textra_hosts: edge.hosts.map((host) => `${host}:host-gateway`),\n\t\tvolumes: edge.authority\n\t\t\t? [`${edge.authority}:${LOCAL_CA_IN_CONTAINER}:ro`]\n\t\t\t: [],\n\t\tenvironment: edge.authority\n\t\t\t? { NODE_EXTRA_CA_CERTS: LOCAL_CA_IN_CONTAINER }\n\t\t\t: {},\n\t};\n}\n\n/**\n * What the build of a site that pre-renders against its stage needs to reach\n * the stage's public hosts. A deployed stage's resolve and are trusted as\n * anywhere. The local stage's are `*.localhost` — the build's own loopback —\n * so each is pointed at the host's gateway, where the edge publishes its\n * ports, and the build is handed the root the edge's certificate chains to,\n * as {@link localEdgeAccess} hands a container both.\n *\n * Not the stack's network: BuildKit builds on none but its own.\n */\nfunction prerenderBuildAccess(edge?: {\n\thosts: readonly string[];\n\tauthority?: string;\n}): { extra_hosts?: string[]; secrets?: string[] } {\n\tif (!edge) return {};\n\tconst { extra_hosts } = localEdgeAccess(edge);\n\treturn {\n\t\t...(extra_hosts.length ? { extra_hosts } : {}),\n\t\t...(edge.authority ? { secrets: [LOCAL_CA_BUILD_SECRET] } : {}),\n\t};\n}\n\n/** The compose document: the infrastructure, the apps, and the edge. */\nfunction stackFile(options: {\n\tproject: string;\n\tplan: Plan;\n\tinfra: readonly string[];\n\tapps: readonly StackApp[];\n\tworkers: readonly StackWorker[];\n\tprocessors: readonly StackProcessor[];\n\tcredentials: ContainerCredentials;\n\tstorage?: StackStorage;\n\t/** Mailpit's webhook: the inbox relay worker on the stack's network. */\n\tinboxRelay?: string;\n\tlogs?: StackLogs;\n\tredis?: StackRedis;\n\tbackups?: StackBackups;\n\thttps: number;\n\thttp: number;\n\tcomposeDir: string;\n\tbuildRoot: string;\n\tworkspaceRoot: string;\n\t/** Whether services read env files — not in a stack that only builds. */\n\tenvFiles: boolean;\n\tproxy: ComposeProxy;\n\t/** Behind the shared edge: each service it routes to, and its alias. */\n\tedge: ReadonlyMap<string, string>;\n\t/**\n\t * The local stage: its public hosts, and the root its certificate chains\n\t * to on this machine — see {@link localEdgeAccess}.\n\t */\n\tlocalEdge?: { hosts: readonly string[]; authority?: string };\n}): StackFile {\n\tconst { project, plan, apps } = options;\n\t// What reconcile defines; OpenObserve is the stack's own.\n\tconst infra = options.infra.filter((name) => name !== LOGS_SERVICE);\n\n\t// Reconcile's definitions — images, health checks, volumes — with nothing\n\t// published to the host. Ports are allocation's business there; here the\n\t// edge is the only way in.\n\tconst derived = composeFor(\n\t\t{ ...plan, containers: [...infra] },\n\t\t{\n\t\t\tproject,\n\t\t\tports: Object.fromEntries(\n\t\t\t\tportKeys(infra, plan.fakes).map((key) => [key, 0]),\n\t\t\t),\n\t\t\tcredentials: options.credentials,\n\t\t},\n\t);\n\n\tconst services: Record<string, StackService> = {};\n\tconst volumes: Record<string, Record<string, never>> = {\n\t\t...derived.volumes,\n\t\t...(options.proxy === 'caddy'\n\t\t\t? { 'caddy-data': {}, 'caddy-config': {} }\n\t\t\t: {}),\n\t\t...(options.logs ? { 'openobserve-data': {} } : {}),\n\t};\n\n\tfor (const name of infra) {\n\t\tconst {\n\t\t\tports: _ports,\n\t\t\tdepends_on,\n\t\t\tprofiles: _profiles,\n\t\t\t...service\n\t\t} = derived.services[name]!;\n\t\tservices[name] = {\n\t\t\t...service,\n\t\t\t...(depends_on?.length\n\t\t\t\t? {\n\t\t\t\t\t\tdepends_on: Object.fromEntries(\n\t\t\t\t\t\t\tdepends_on.map((dep) => [dep, HEALTHY]),\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\tconst postgres = services.postgres;\n\tif (postgres) {\n\t\t// Loopback only, on a port Docker picks: gkm creates the databases and\n\t\t// roles and runs the migrations from this machine, and nothing else\n\t\t// should reach the database from outside the stack.\n\t\tpostgres.ports = [`127.0.0.1::${LOOPBACK_SERVICES.postgres}`];\n\t\t// Point-in-time recovery: built with WAL-G, archiving its WAL.\n\t\tif (options.backups?.pitr) {\n\t\t\tservices.postgres = withArchiving(\n\t\t\t\tpostgres,\n\t\t\t\toptions.backups.pitr,\n\t\t\t\toptions.envFiles,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst minio = services.minio;\n\tif (minio && options.storage) {\n\t\tminio.environment = {\n\t\t\t...minio.environment,\n\t\t\tMINIO_ROOT_USER: options.storage.user,\n\t\t\tMINIO_ROOT_PASSWORD: options.storage.password,\n\t\t\t// Where each watched bucket's events are posted: a worker, on the\n\t\t\t// stack's network. In the environment, so a change recreates MinIO.\n\t\t\t...minioWebhookEnv(options.storage.webhooks),\n\t\t};\n\t\t// Loopback only, like Postgres: gkm creates the buckets and their\n\t\t// policies from this machine. The apps reach it on the network, and a\n\t\t// browser through a file server's host on the edge.\n\t\tminio.ports = [`127.0.0.1::${LOOPBACK_SERVICES.minio}`];\n\t}\n\n\tconst mailpit = services.mailpit;\n\tif (mailpit && options.inboxRelay) {\n\t\tmailpit.environment = {\n\t\t\t...mailpit.environment,\n\t\t\tMP_WEBHOOK_URL: options.inboxRelay,\n\t\t};\n\t}\n\n\t// Its own definition rather than reconcile's: `gkm dev`'s Redis is an\n\t// open, unbounded scratch store; this one is a production cache.\n\tif (services[REDIS_SERVICE] && options.redis) {\n\t\tservices[REDIS_SERVICE] = redisService(options.redis);\n\t}\n\n\t// Started with the infrastructure, but nothing waits on it: an app whose\n\t// telemetry cannot be delivered still serves.\n\tif (options.logs) services[LOGS_SERVICE] = logsService(options.logs);\n\n\t// The stage's backups: on the stack's network, from nothing on the host.\n\tif (options.backups) {\n\t\tservices[BACKUPS_SERVICE] = backupsService(\n\t\t\toptions.backups,\n\t\t\toptions.envFiles,\n\t\t);\n\t}\n\n\tfor (const app of apps) {\n\t\tconst definition: StackService = {\n\t\t\timage: app.ref,\n\t\t\t...(app.build\n\t\t\t\t? {\n\t\t\t\t\t\tbuild: {\n\t\t\t\t\t\t\t...composeBuildPaths({\n\t\t\t\t\t\t\t\tcomposeDir: options.composeDir,\n\t\t\t\t\t\t\t\tbuildRoot: options.buildRoot,\n\t\t\t\t\t\t\t\tworkspaceRoot: options.workspaceRoot,\n\t\t\t\t\t\t\t\tdockerfile: app.build.dockerfile,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(app.build.args ? { args: app.build.args } : {}),\n\t\t\t\t\t\t\t...(app.build.offlineHosts\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\textra_hosts: app.build.offlineHosts.map(\n\t\t\t\t\t\t\t\t\t\t\t(host) => `${host}:${OFFLINE_BUILD_ADDRESS}`,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t// Built once its APIs answer, it reaches them as the stack's\n\t\t\t\t\t\t\t// containers do — see `prerenderBuildAccess`.\n\t\t\t\t\t\t\t...(app.prerender ? prerenderBuildAccess(options.localEdge) : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\trestart: 'unless-stopped',\n\t\t\t// A static site is a bundle and reads nothing at runtime; a backend,\n\t\t\t// and a site that runs a server, reads exactly the keys in its own\n\t\t\t// file. Only a backend waits on the stack's services.\n\t\t\t...(app.runtime\n\t\t\t\t? {\n\t\t\t\t\t\tenv_file: [{ path: `./${app.name}.env`, format: 'raw' as const }],\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(app.kind !== 'site' && infra.length\n\t\t\t\t? {\n\t\t\t\t\t\tdepends_on: Object.fromEntries(\n\t\t\t\t\t\t\tinfra.map((name) => [name, HEALTHY]),\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\thealthcheck: probe(app.port, app.kind === 'site' ? '/' : '/health'),\n\t\t\t// Every socket is a descriptor, and Docker's default soft limit is\n\t\t\t// 1024 wherever the engine was not told otherwise.\n\t\t\t...(app.kind === 'websocket-api' ? { ulimits: { nofile: NOFILE } } : {}),\n\t\t};\n\t\t// Each replica the same service under its own name: one image, one\n\t\t// env file, and an upstream each.\n\t\tfor (const name of replicaNames(app)) services[name] = { ...definition };\n\t}\n\n\t// A worker or a processor unit: no published port — its health check is\n\t// Docker's, and the edge reaches it only on the paths it routes there.\n\tfor (const worker of [...options.workers, ...options.processors]) {\n\t\tservices[worker.name] = {\n\t\t\timage: worker.ref,\n\t\t\t...(worker.build\n\t\t\t\t? {\n\t\t\t\t\t\tbuild: composeBuildPaths({\n\t\t\t\t\t\t\tcomposeDir: options.composeDir,\n\t\t\t\t\t\t\tbuildRoot: options.buildRoot,\n\t\t\t\t\t\t\tworkspaceRoot: options.workspaceRoot,\n\t\t\t\t\t\t\tdockerfile: worker.build.dockerfile,\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\trestart: 'unless-stopped',\n\t\t\tenv_file: [{ path: `./${worker.name}.env`, format: 'raw' as const }],\n\t\t\t...(infra.length\n\t\t\t\t? {\n\t\t\t\t\t\tdepends_on: Object.fromEntries(\n\t\t\t\t\t\t\tinfra.map((name) => [name, HEALTHY]),\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\thealthcheck: probe(worker.port, '/health'),\n\t\t};\n\t}\n\n\t// Every container that runs the stage's code reaches its public hosts as\n\t// a browser does — through the edge, trusting gkm's root.\n\tif (options.localEdge) {\n\t\tconst access = localEdgeAccess(options.localEdge);\n\t\tfor (const name of [\n\t\t\t...apps.flatMap(replicaNames),\n\t\t\t...options.workers.map((w) => w.name),\n\t\t\t...options.processors.map((p) => p.name),\n\t\t]) {\n\t\t\tconst service = services[name];\n\t\t\tif (!service) continue;\n\t\t\tservices[name] = {\n\t\t\t\t...service,\n\t\t\t\tenvironment: { ...service.environment, ...access.environment },\n\t\t\t\t...(access.volumes.length\n\t\t\t\t\t? { volumes: [...(service.volumes ?? []), ...access.volumes] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(access.extra_hosts.length\n\t\t\t\t\t? {\n\t\t\t\t\t\t\textra_hosts: [\n\t\t\t\t\t\t\t\t...(service.extra_hosts ?? []),\n\t\t\t\t\t\t\t\t...access.extra_hosts,\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}\n\t}\n\n\tif (options.proxy === 'caddy') {\n\t\tservices.caddy = {\n\t\t\timage: DEFAULT_IMAGES.caddy!,\n\t\t\trestart: 'unless-stopped',\n\t\t\tports: [`${options.https}:443`, `${options.http}:80`],\n\t\t\t// The Caddyfile and the stage's own certificate are inline configs,\n\t\t\t// added as the file is written (`withCaddyConfigs`).\n\t\t\tvolumes: ['caddy-data:/data', 'caddy-config:/config'],\n\t\t\t...EDGE_LIMITS,\n\t\t\t// Not a site built against its stage: it is built once Caddy, and\n\t\t\t// the APIs behind it, already answer.\n\t\t\tdepends_on: Object.fromEntries(\n\t\t\t\t[\n\t\t\t\t\t...apps\n\t\t\t\t\t\t.filter((app) => !(app.prerender && app.build))\n\t\t\t\t\t\t.flatMap(replicaNames),\n\t\t\t\t\t...options.workers.filter((w) => w.push).map((w) => w.name),\n\t\t\t\t\t...options.processors.map((p) => p.name),\n\t\t\t\t].map((name) => [name, STARTED]),\n\t\t\t),\n\t\t\thealthcheck: {\n\t\t\t\ttest: ['CMD', 'caddy', 'version'],\n\t\t\t\tinterval: '10s',\n\t\t\t\ttimeout: '5s',\n\t\t\t\tretries: 5,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Behind the shared edge: each service it routes to joins its network,\n\t// under the alias the edge reaches it by — and keeps the stack's own,\n\t// with the same alias, which is how the stack's services reach it too.\n\t// Everything else — the databases, Redis, the workers — stays off it.\n\tfor (const [service, alias] of options.edge) {\n\t\tconst definition = services[service];\n\t\tif (!definition) continue;\n\t\tdefinition.networks = {\n\t\t\tdefault: { aliases: [alias] },\n\t\t\tedge: { aliases: [alias] },\n\t\t};\n\t}\n\n\tfor (const service of Object.values(services)) {\n\t\tif (!options.envFiles) delete service.env_file;\n\t\tservice.logging = {\n\t\t\tdriver: LOG_ROTATION.driver,\n\t\t\toptions: { ...LOG_ROTATION.options },\n\t\t};\n\t}\n\n\t// The local edge's root, for a build that reaches the stage through it.\n\tconst authority = options.localEdge?.authority;\n\tconst prerendered = apps.some((app) => app.prerender && app.build);\n\n\treturn {\n\t\tname: project,\n\t\tservices,\n\t\tvolumes,\n\t\t...(prerendered && authority\n\t\t\t? { secrets: { [LOCAL_CA_BUILD_SECRET]: { file: authority } } }\n\t\t\t: {}),\n\t\t...(options.edge.size > 0\n\t\t\t? { networks: { edge: { name: EDGE_NETWORK, external: true as const } } }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * A build without a layout: the workspace is the build root, with pnpm.\n * What a caller that never looked at the filesystem gets.\n */\nfunction defaultLayout(root: string): ImageLayout {\n\treturn {\n\t\tbuildRoot: root,\n\t\tgkmRoot: '.',\n\t\ttools: {\n\t\t\tpackageManager: 'pnpm',\n\t\t\tturboVersion: TURBO_VERSION,\n\t\t\tmonorepo: true,\n\t\t},\n\t\tgkmPaths: ['gkm.config.*'],\n\t};\n}\n\n/** Render an app's env file: one `KEY=value` per line, read raw by compose. */\nexport function envFile(env: Readonly<Record<string, string>>): string {\n\treturn `${Object.entries(env)\n\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t.map(([key, value]) => `${key}=${value}`)\n\t\t.join('\\n')}\\n`;\n}\n\n/**\n * The stack with its OpenObserve on another loopback port — the one its\n * server has free for it, found before anything is written. Its UI's URL and\n * its service's published port move together; nothing else reads the port.\n */\nexport function withLogsPort(stack: ComposeStack, port: number): ComposeStack {\n\tif (!stack.logs) return stack;\n\tconst logs = logsOnPort(stack.logs, port);\n\tconst service = stack.compose.services[LOGS_SERVICE];\n\tif (logs === stack.logs || !service) return stack;\n\treturn {\n\t\t...stack,\n\t\tlogs,\n\t\tcompose: {\n\t\t\t...stack.compose,\n\t\t\tservices: {\n\t\t\t\t...stack.compose.services,\n\t\t\t\t[LOGS_SERVICE]: { ...service, ...logsPorts(logs) },\n\t\t\t},\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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