@geekmidas/cli 10.0.0-alpha.154 → 10.0.0-alpha.156
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/README.md +10 -0
- package/dist/{GoDaddyProvider-CQ4YrB5P.mjs → GoDaddyProvider-C6kihaSF.mjs} +2 -2
- package/dist/{GoDaddyProvider-CQ4YrB5P.mjs.map → GoDaddyProvider-C6kihaSF.mjs.map} +1 -1
- package/dist/{GoDaddyProvider-H59_cXa0.cjs → GoDaddyProvider-bCGjHmq_.cjs} +2 -2
- package/dist/{GoDaddyProvider-H59_cXa0.cjs.map → GoDaddyProvider-bCGjHmq_.cjs.map} +1 -1
- package/dist/{HostingerProvider-DBfHH0qT.mjs → HostingerProvider-CH3qcNOp.mjs} +2 -2
- package/dist/{HostingerProvider-DBfHH0qT.mjs.map → HostingerProvider-CH3qcNOp.mjs.map} +1 -1
- package/dist/{HostingerProvider-DecF9ELH.cjs → HostingerProvider-l-pKR3UU.cjs} +2 -2
- package/dist/{HostingerProvider-DecF9ELH.cjs.map → HostingerProvider-l-pKR3UU.cjs.map} +1 -1
- package/dist/{LegacyStateStore-DwsnVS-2.cjs → LegacyStateStore-BLTALNNX.cjs} +2 -2
- package/dist/{LegacyStateStore-DwsnVS-2.cjs.map → LegacyStateStore-BLTALNNX.cjs.map} +1 -1
- package/dist/{LegacyStateStore-Cz1ORtCx.mjs → LegacyStateStore-kxFSoD1P.mjs} +2 -2
- package/dist/{LegacyStateStore-Cz1ORtCx.mjs.map → LegacyStateStore-kxFSoD1P.mjs.map} +1 -1
- package/dist/{LocalStateStore-BZ5b3sw4.cjs → LocalStateStore-CCYbRnLH.cjs} +2 -2
- package/dist/{LocalStateStore-BZ5b3sw4.cjs.map → LocalStateStore-CCYbRnLH.cjs.map} +1 -1
- package/dist/{LocalStateStore-dz7OkMGm.mjs → LocalStateStore-CjA4PPQ8.mjs} +2 -2
- package/dist/{LocalStateStore-dz7OkMGm.mjs.map → LocalStateStore-CjA4PPQ8.mjs.map} +1 -1
- package/dist/{S3StateStore-Dw9Dx_vy.cjs → S3StateStore-B4Qu-euw.cjs} +4 -4
- package/dist/{S3StateStore-Dw9Dx_vy.cjs.map → S3StateStore-B4Qu-euw.cjs.map} +1 -1
- package/dist/{S3StateStore-Bda3aGqz.mjs → S3StateStore-nCDpz4Gi.mjs} +4 -4
- package/dist/{S3StateStore-Bda3aGqz.mjs.map → S3StateStore-nCDpz4Gi.mjs.map} +1 -1
- package/dist/{SSMStateStore-DPZpYnda.cjs → SSMStateStore-BI5sYXl-.cjs} +2 -2
- package/dist/{SSMStateStore-DPZpYnda.cjs.map → SSMStateStore-BI5sYXl-.cjs.map} +1 -1
- package/dist/{SSMStateStore-CcT6YJFd.mjs → SSMStateStore-VOk8OdaW.mjs} +2 -2
- package/dist/{SSMStateStore-CcT6YJFd.mjs.map → SSMStateStore-VOk8OdaW.mjs.map} +1 -1
- package/dist/{add-Bwek61Bv.cjs → add-B0VtHNY5.cjs} +4 -4
- package/dist/{add-Bwek61Bv.cjs.map → add-B0VtHNY5.cjs.map} +1 -1
- package/dist/{add-Feiof1dz.mjs → add-CtkmKzg0.mjs} +4 -4
- package/dist/{add-Feiof1dz.mjs.map → add-CtkmKzg0.mjs.map} +1 -1
- package/dist/{apps-CrQhJueV.cjs → apps-Bj3U4v3a.cjs} +3 -3
- package/dist/{apps-CrQhJueV.cjs.map → apps-Bj3U4v3a.cjs.map} +1 -1
- package/dist/{apps-C0kZVQpf.mjs → apps-CggMxcW9.mjs} +3 -3
- package/dist/{apps-C0kZVQpf.mjs.map → apps-CggMxcW9.mjs.map} +1 -1
- package/dist/{bundler-CV-UpPpb.cjs → bundler-CcK6uiP5.cjs} +6 -6
- package/dist/{bundler-CV-UpPpb.cjs.map → bundler-CcK6uiP5.cjs.map} +1 -1
- package/dist/{bundler-o10_P4d9.mjs → bundler-isYJiy1x.mjs} +6 -6
- package/dist/{bundler-o10_P4d9.mjs.map → bundler-isYJiy1x.mjs.map} +1 -1
- package/dist/{cli-BO4qIuTd.cjs → cli-B5k3qrO4.cjs} +4 -4
- package/dist/{cli-BO4qIuTd.cjs.map → cli-B5k3qrO4.cjs.map} +1 -1
- package/dist/{cli-KFbKAyaH.mjs → cli-BVHsKFMj.mjs} +4 -4
- package/dist/{cli-KFbKAyaH.mjs.map → cli-BVHsKFMj.mjs.map} +1 -1
- package/dist/{compose-djwQcfQD.cjs → compose-8_6I_Vhv.cjs} +4 -4
- package/dist/{compose-djwQcfQD.cjs.map → compose-8_6I_Vhv.cjs.map} +1 -1
- package/dist/{compose-C-k9AoH0.mjs → compose-DA4mTDZr.mjs} +7 -7
- package/dist/{compose-C-k9AoH0.mjs.map → compose-DA4mTDZr.mjs.map} +1 -1
- package/dist/{compose-D8fn0ebx.mjs → compose-DS0L5WGA.mjs} +4 -4
- package/dist/{compose-D8fn0ebx.mjs.map → compose-DS0L5WGA.mjs.map} +1 -1
- package/dist/{compose-CyGZOLcK.cjs → compose-Dxaaqmzz.cjs} +7 -7
- package/dist/{compose-CyGZOLcK.cjs.map → compose-Dxaaqmzz.cjs.map} +1 -1
- package/dist/{credentials-DY_Cu5Ht.mjs → credentials-DidjPIcM.mjs} +5 -5
- package/dist/{credentials-DY_Cu5Ht.mjs.map → credentials-DidjPIcM.mjs.map} +1 -1
- package/dist/{credentials-DixsjQcu.cjs → credentials-LLoLkwjB.cjs} +5 -5
- package/dist/{credentials-DixsjQcu.cjs.map → credentials-LLoLkwjB.cjs.map} +1 -1
- package/dist/deploy/public.cjs +10 -10
- package/dist/deploy/public.mjs +10 -10
- package/dist/{deploy-DsWQ8kTC.mjs → deploy-BEwiKZBG.mjs} +11 -11
- package/dist/{deploy-DsWQ8kTC.mjs.map → deploy-BEwiKZBG.mjs.map} +1 -1
- package/dist/{deploy-DzYn1rNl.cjs → deploy-DpQPFrhf.cjs} +11 -11
- package/dist/{deploy-DzYn1rNl.cjs.map → deploy-DpQPFrhf.cjs.map} +1 -1
- package/dist/{docker-CobK4rVH.mjs → docker-BeO31G2F.mjs} +4 -4
- package/dist/{docker-CobK4rVH.mjs.map → docker-BeO31G2F.mjs.map} +1 -1
- package/dist/{docker-DDHfNbM8.cjs → docker-BficHJMS.cjs} +4 -4
- package/dist/{docker-DDHfNbM8.cjs.map → docker-BficHJMS.cjs.map} +1 -1
- package/dist/{dokploy-2bH8IDTX.mjs → dokploy-BLZlrTf7.mjs} +2 -2
- package/dist/{dokploy-2bH8IDTX.mjs.map → dokploy-BLZlrTf7.mjs.map} +1 -1
- package/dist/{dokploy-CCgBM22f.cjs → dokploy-D6ktFzjP.cjs} +2 -2
- package/dist/{dokploy-CCgBM22f.cjs.map → dokploy-D6ktFzjP.cjs.map} +1 -1
- package/dist/{eas-CYs_Grue.mjs → eas-DdE1PH-Z.mjs} +2 -2
- package/dist/{eas-CYs_Grue.mjs.map → eas-DdE1PH-Z.mjs.map} +1 -1
- package/dist/{eas-8X90Y3ks.cjs → eas-Dh9LBIJi.cjs} +2 -2
- package/dist/{eas-8X90Y3ks.cjs.map → eas-Dh9LBIJi.cjs.map} +1 -1
- package/dist/{emit-Bj6XSivk.mjs → emit-C4KSXOeS.mjs} +18 -1
- package/dist/emit-C4KSXOeS.mjs.map +1 -0
- package/dist/{emit-CDC__ubE.cjs → emit-DiW0kbue.cjs} +18 -1
- package/dist/emit-DiW0kbue.cjs.map +1 -0
- package/dist/{encryption-Bm9pJAlv.mjs → encryption-1TTbMp4E.mjs} +2 -2
- package/dist/{encryption-Bm9pJAlv.mjs.map → encryption-1TTbMp4E.mjs.map} +1 -1
- package/dist/{encryption-BlvEsxDL.cjs → encryption-BDCTITiO.cjs} +2 -2
- package/dist/{encryption-BlvEsxDL.cjs.map → encryption-BDCTITiO.cjs.map} +1 -1
- package/dist/{engine-CVgtgVgf.mjs → engine-DBimzOpv.mjs} +8 -8
- package/dist/{engine-CVgtgVgf.mjs.map → engine-DBimzOpv.mjs.map} +1 -1
- package/dist/{engine-BL_34-M8.cjs → engine-DPVbMn1R.cjs} +8 -8
- package/dist/{engine-BL_34-M8.cjs.map → engine-DPVbMn1R.cjs.map} +1 -1
- package/dist/{github-Ci0PUjjW.cjs → github-Bur2rvbL.cjs} +6 -6
- package/dist/{github-Ci0PUjjW.cjs.map → github-Bur2rvbL.cjs.map} +1 -1
- package/dist/{github-j9ytVxlm.mjs → github-e4EXHIAd.mjs} +6 -6
- package/dist/{github-j9ytVxlm.mjs.map → github-e4EXHIAd.mjs.map} +1 -1
- package/dist/{googlePlay-CvYKw65D.mjs → googlePlay-CH5BrkCd.mjs} +4 -4
- package/dist/{googlePlay-CvYKw65D.mjs.map → googlePlay-CH5BrkCd.mjs.map} +1 -1
- package/dist/{googlePlay-jR8oRAzy.cjs → googlePlay-gCxefG71.cjs} +4 -4
- package/dist/{googlePlay-jR8oRAzy.cjs.map → googlePlay-gCxefG71.cjs.map} +1 -1
- package/dist/index.cjs +222 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +222 -68
- package/dist/index.mjs.map +1 -1
- package/dist/{local-5DkpRnl2.cjs → local-B9psHtjC.cjs} +2 -2
- package/dist/{local-5DkpRnl2.cjs.map → local-B9psHtjC.cjs.map} +1 -1
- package/dist/{local-pFyO21et.mjs → local-qbOxBD9I.mjs} +2 -2
- package/dist/{local-pFyO21et.mjs.map → local-qbOxBD9I.mjs.map} +1 -1
- package/dist/{migrate-DKep6Tol.cjs → migrate-B3T5iHyR.cjs} +2 -2
- package/dist/{migrate-DKep6Tol.cjs.map → migrate-B3T5iHyR.cjs.map} +1 -1
- package/dist/{migrate-CPoStsvd.cjs → migrate-BqjeJXXX.cjs} +4 -4
- package/dist/{migrate-CPoStsvd.cjs.map → migrate-BqjeJXXX.cjs.map} +1 -1
- package/dist/{migrate-C1SSvzNZ.mjs → migrate-Cg6ogGbR.mjs} +2 -2
- package/dist/{migrate-C1SSvzNZ.mjs.map → migrate-Cg6ogGbR.mjs.map} +1 -1
- package/dist/{migrate-Dv8Qk0jw.mjs → migrate-DJ6o58e4.mjs} +4 -4
- package/dist/{migrate-Dv8Qk0jw.mjs.map → migrate-DJ6o58e4.mjs.map} +1 -1
- package/dist/{notes-Dwz8jmoh.mjs → notes-CV9tczQF.mjs} +2 -2
- package/dist/{notes-Dwz8jmoh.mjs.map → notes-CV9tczQF.mjs.map} +1 -1
- package/dist/{notes-CFCdqMQ4.cjs → notes-WW3tkekq.cjs} +2 -2
- package/dist/{notes-CFCdqMQ4.cjs.map → notes-WW3tkekq.cjs.map} +1 -1
- package/dist/{projectBucket-UCuebUhW.cjs → projectBucket-BCutOEvv.cjs} +2 -2
- package/dist/{projectBucket-UCuebUhW.cjs.map → projectBucket-BCutOEvv.cjs.map} +1 -1
- package/dist/{projectBucket-Daak2eUn.mjs → projectBucket-CRAuyO-t.mjs} +2 -2
- package/dist/{projectBucket-Daak2eUn.mjs.map → projectBucket-CRAuyO-t.mjs.map} +1 -1
- package/dist/{publish-DibqEZ2a.mjs → publish-BJyVR2lE.mjs} +2 -2
- package/dist/{publish-DibqEZ2a.mjs.map → publish-BJyVR2lE.mjs.map} +1 -1
- package/dist/{publish-CBuMAY04.cjs → publish-BcPp-_qQ.cjs} +2 -2
- package/dist/{publish-CBuMAY04.cjs.map → publish-BcPp-_qQ.cjs.map} +1 -1
- package/dist/reconcile/public.cjs +1 -1
- package/dist/reconcile/public.d.cts +3 -1
- package/dist/reconcile/public.d.cts.map +1 -1
- package/dist/reconcile/public.d.mts +3 -1
- package/dist/reconcile/public.d.mts.map +1 -1
- package/dist/reconcile/public.mjs +1 -1
- package/dist/{resolve-BF4-f30m.mjs → resolve-CH_DwRLq.mjs} +4 -4
- package/dist/{resolve-BF4-f30m.mjs.map → resolve-CH_DwRLq.mjs.map} +1 -1
- package/dist/{resolve-BjgqLxcZ.cjs → resolve-CwJ_ScjX.cjs} +4 -4
- package/dist/{resolve-BjgqLxcZ.cjs.map → resolve-CwJ_ScjX.cjs.map} +1 -1
- package/dist/{rollback-BXkzAkAh.cjs → rollback-BBdR1h3T.cjs} +5 -5
- package/dist/{rollback-BXkzAkAh.cjs.map → rollback-BBdR1h3T.cjs.map} +1 -1
- package/dist/{rollback-DBewZGz9.mjs → rollback-Bpuaon23.mjs} +5 -5
- package/dist/{rollback-DBewZGz9.mjs.map → rollback-Bpuaon23.mjs.map} +1 -1
- package/dist/{s3-CR8gEP-7.mjs → s3-C5pbgCxY.mjs} +2 -2
- package/dist/{s3-CR8gEP-7.mjs.map → s3-C5pbgCxY.mjs.map} +1 -1
- package/dist/{s3-Cp2eA2v_.cjs → s3-Cx5XUsK2.cjs} +2 -2
- package/dist/{s3-Cp2eA2v_.cjs.map → s3-Cx5XUsK2.cjs.map} +1 -1
- package/dist/{serverSetup-B9BPzpUQ.mjs → serverSetup-B9sp6uWM.mjs} +5 -5
- package/dist/{serverSetup-B9BPzpUQ.mjs.map → serverSetup-B9sp6uWM.mjs.map} +1 -1
- package/dist/{serverSetup-0eV8bl75.cjs → serverSetup-CQ96N5tn.cjs} +5 -5
- package/dist/{serverSetup-0eV8bl75.cjs.map → serverSetup-CQ96N5tn.cjs.map} +1 -1
- package/dist/{sniffer-0wN20Fuy.cjs → sniffer-CSgeus1c.cjs} +6 -6
- package/dist/{sniffer-0wN20Fuy.cjs.map → sniffer-CSgeus1c.cjs.map} +1 -1
- package/dist/{sniffer-C2yPOlOW.mjs → sniffer-DmigJFSC.mjs} +6 -6
- package/dist/{sniffer-C2yPOlOW.mjs.map → sniffer-DmigJFSC.mjs.map} +1 -1
- package/dist/{snsSubscriptions-DR3drFJK.cjs → snsSubscriptions-PcvjBC8J.cjs} +2 -2
- package/dist/{snsSubscriptions-DR3drFJK.cjs.map → snsSubscriptions-PcvjBC8J.cjs.map} +1 -1
- package/dist/{snsSubscriptions-CtOrP15M.mjs → snsSubscriptions-UJrUbrPC.mjs} +2 -2
- package/dist/{snsSubscriptions-CtOrP15M.mjs.map → snsSubscriptions-UJrUbrPC.mjs.map} +1 -1
- package/dist/{sst-fbVtyw_h.cjs → sst-BX_dHQYC.cjs} +21 -5
- package/dist/{sst-fbVtyw_h.cjs.map → sst-BX_dHQYC.cjs.map} +1 -1
- package/dist/{sst-BF85FnBg.mjs → sst-CVBDMb9x.mjs} +21 -5
- package/dist/{sst-BF85FnBg.mjs.map → sst-CVBDMb9x.mjs.map} +1 -1
- package/dist/{stack-CB0U6NiV.cjs → stack-B8JVuA2N.cjs} +35 -14
- package/dist/stack-B8JVuA2N.cjs.map +1 -0
- package/dist/{stack-ZV2le8OB.mjs → stack-BrqdoNWg.mjs} +35 -14
- package/dist/stack-BrqdoNWg.mjs.map +1 -0
- package/dist/{stage-B6bQKczF.cjs → stage-BtX7qbNh.cjs} +5 -5
- package/dist/{stage-B6bQKczF.cjs.map → stage-BtX7qbNh.cjs.map} +1 -1
- package/dist/{stage-CPtCIwru.mjs → stage-DfDPXyKq.mjs} +5 -5
- package/dist/{stage-CPtCIwru.mjs.map → stage-DfDPXyKq.mjs.map} +1 -1
- package/dist/target/public.cjs +1 -1
- package/dist/target/public.mjs +1 -1
- package/dist/{terminal-b_4H0MHd.mjs → terminal-BG75hJ72.mjs} +2 -2
- package/dist/{terminal-b_4H0MHd.mjs.map → terminal-BG75hJ72.mjs.map} +1 -1
- package/dist/{terminal-CyB5bRPt.cjs → terminal-Cz-uD2VK.cjs} +2 -2
- package/dist/{terminal-CyB5bRPt.cjs.map → terminal-Cz-uD2VK.cjs.map} +1 -1
- package/package.json +15 -15
- package/dist/emit-Bj6XSivk.mjs.map +0 -1
- package/dist/emit-CDC__ubE.cjs.map +0 -1
- package/dist/stack-CB0U6NiV.cjs.map +0 -1
- package/dist/stack-ZV2le8OB.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stack-B8JVuA2N.cjs","names":["clientIpRule","GkmError","GkmError","appKey","bcrypt","createHash","createHash","CLIENT_IP_HEADER","EDGE_TOKEN_HEADER","parse","yaml","stringify","GkmError","createHash","localRolePassword","postgresSuperuser","LOCAL_RABBITMQ_USER","EMULATOR_ACCESS_KEY_ID","provideKey","NoDomainForStage","planFor","provisionOrder","DEFAULT_EVENTS","STACK_CACHE","proxyFor","certificateFor","workerUnits","processorUnits","resolveStageTelemetry","usesTelemetry","stackLogs","externalServices","stageServiceDeclarations","stageProviderNotes","stackRedis","LOGS_SERVICE","LOCAL_TLD","bucketPolicies","bucketLifecycles","hostFor","appKey","watchedBuckets","networkEnv","isReservedStageKey","suppliedOnly","telemetryEnv","otlpTelemetryEnv","isTelemetryKey","publicBuildValues","PRERENDER_RUN_ARG","offlineBuildHosts","processEnvKeys","scopeTelemetryEnv","telemetryOf","SNS_SUBSCRIPTIONS_KEY","originSecretKey","processorOriginHost","objectsRoute","inboxRelayWorker","INBOX_RELAY_TOKEN_KEY","inboxWebhookUrl","localAuthorityPaths","stageBackups","stackBackups","ORIGIN_VERIFY_HEADER","LOGS_PORT","join","appDockerfile","workerDockerfile","processorDockerfile","EDGE_TOKEN_KEY","devServicesUsed","validateImageRef","imageRef","runsServer","subscriberRoute","isWildcardSite","normalizeDnsConfig","findRootDomain","PROCESSOR_PORT","WORKER_PORT","WILDCARD_SUBDOMAIN","resolveHost","isMainFrontendApp","LOCAL_CA_BUILD_SECRET","composeFor","portKeys","minioWebhookEnv","REDIS_SERVICE","redisService","logsService","BACKUPS_SERVICE","backupsService","composeBuildPaths","OFFLINE_BUILD_ADDRESS","DEFAULT_IMAGES","TURBO_VERSION"],"sources":["../src/compose/routes.ts","../src/compose/caddyfile.ts","../src/compose/images.ts","../src/compose/sitePassword.ts","../src/compose/traefik.ts","../src/compose/stack.ts"],"sourcesContent":["/**\n * What a stack's edge serves, as data: one route per public host, and the\n * service behind it. Computed once by the stack, then rendered by whichever\n * proxy the stage runs — a Caddyfile for the stack's own Caddy, or a dynamic\n * config file for the server's shared Traefik — so the two never drift.\n *\n * Pure.\n */\n\n/** A service of the stack that a route sends to. */\nexport interface Upstream {\n\t/** Its compose service name — `api`, `minio`. */\n\tservice: string;\n\t/** The port it listens on, inside the network. */\n\tport: number;\n}\n\n/** One public host and what answers it. */\nexport interface EdgeRoute {\n\t/**\n\t * Its name within the stack — unique there, and what a renderer names\n\t * its routers and middlewares after: `api`, `files-uploads`.\n\t */\n\tname: string;\n\t/** e.g. `api.example.com` */\n\thost: string;\n\t/**\n\t * Where requests go. One today; a release that swaps containers without\n\t * downtime routes to the old and the new while it does.\n\t */\n\tupstreams: readonly Upstream[];\n\t/**\n\t * Never buffer the response: a streamed one — server-sent events, a\n\t * Next.js RSC payload — reaches the client as each chunk is written.\n\t */\n\tstreaming: boolean;\n\t/**\n\t * A path prefix added before the request is sent, with the upstream's own\n\t * address as `Host`: a bucket, served at a host of its own, is a prefix\n\t * on MinIO, which routes and signs on the Host header.\n\t */\n\tprefix?: string;\n\t/**\n\t * The client addresses (IPs or CIDRs) it answers; every other is refused\n\t * with 403, before the request reaches the upstream. Absent, it answers\n\t * everyone. Matched against the peer the proxy sees, never a header a\n\t * client could set.\n\t */\n\tallow?: readonly string[];\n\t/**\n\t * The only paths it answers, matched exactly; every other is refused at\n\t * the edge, before the request reaches the upstream. Absent, it answers\n\t * every path. A worker is reached only on the routes SNS pushes to.\n\t */\n\tpaths?: readonly string[];\n\t/**\n\t * Path prefixes it answers besides `paths` — `/i/` admits everything\n\t * under it. Together they are the whole allowlist; absent both, it\n\t * answers every path. A processor unit's own host is reached only on its\n\t * processors' prefixes.\n\t */\n\tprefixes?: readonly string[];\n\t/**\n\t * A header every request must carry, with exactly this value; any other\n\t * is refused at the edge. What a CDN adds to reach its origin, so the\n\t * origin's public host cannot be called around the CDN.\n\t */\n\trequireHeader?: { name: string; value: string };\n\t/**\n\t * Path prefixes on this host sent to another upstream, ahead of the\n\t * route's own: a file server's processor patterns, to its processor unit,\n\t * while every other path is the bucket. Served at the path asked for —\n\t * no `prefix` — and never combined with `allow`, `paths`, `prefixes` or\n\t * `requireHeader`, which would have to hold for every handler too.\n\t */\n\thandlers?: readonly EdgeHandler[];\n\t/**\n\t * The login every request must carry — HTTP basic auth, asked for by the\n\t * edge before anything reaches the upstream. Absent, it asks for none.\n\t * The password's bcrypt hash, never the password.\n\t */\n\tauth?: { user: string; hash: string };\n\t/**\n\t * What one client address may ask of it — a WebSocket surface's\n\t * handshakes a minute and open sockets — refused with 429 at the edge.\n\t * Rendered for Traefik (`rateLimit`, `inFlightReq`); Caddy ships no rate\n\t * limiter, so behind it the surface's own count is what holds.\n\t */\n\tlimits?: { handshakesPerMinute?: number; connectionsPerIp?: number };\n\t/** The path the upstream answers its health on — `/health`, `/`. */\n\thealth?: string;\n\t/**\n\t * For a wildcard site's route, whose `host` is `*.<domain>`: every one\n\t * label under the domain that no other route answers, and how its\n\t * certificate is had. Named hosts always win over it.\n\t */\n\twildcard?: EdgeWildcard;\n}\n\n/** How a `*.<domain>` route is matched and certified. */\nexport interface EdgeWildcard {\n\t/** The domain under the `*` — `example.com`. */\n\tdomain: string;\n\t/**\n\t * Labels under the domain that never reach it, although no route of this\n\t * stack answers them: the protected subdomains (`www`, `mail`), and a\n\t * stage whose domain sits under this one's (`staging`).\n\t */\n\texcept: readonly string[];\n\t/**\n\t * Where its certificate comes from:\n\t * - `stage`: the stage's own (`deploy.compose.tls`), a wildcard one;\n\t * - `dns`: one `*.<domain>` certificate from Let's Encrypt over the DNS\n\t * challenge, which the shared Traefik edge answers through Route 53;\n\t * - `on-demand`: one per host, as Caddy is first asked for it, once the\n\t * site's `hosts` route — `ask`, on the stack's network — answers 200.\n\t */\n\ttls: { kind: 'stage' } | { kind: 'dns' } | { kind: 'on-demand'; ask: string };\n}\n\n/** Some of a route's paths, answered by another upstream. */\nexport interface EdgeHandler {\n\t/** Unique within the route: what a renderer names its router after. */\n\tname: string;\n\t/** e.g. `/i/` — everything under it. */\n\tprefixes: readonly string[];\n\tupstreams: readonly Upstream[];\n}\n\n/** A route with handlers and a check that would have to hold for each of them. */\nexport class EdgeRouteConflict extends Error {\n\tconstructor(readonly route: string) {\n\t\tsuper(\n\t\t\t`The edge route '${route}' sends some paths to other upstreams and also ` +\n\t\t\t\t`restricts who or what it answers. The two are not combined: give the ` +\n\t\t\t\t`restricted paths a host of their own.`,\n\t\t);\n\t\tthis.name = 'EdgeRouteConflict';\n\t}\n}\n\n/** @throws {EdgeRouteConflict} */\nexport function assertRouteRenderable(route: EdgeRoute): void {\n\tif (\n\t\troute.handlers?.length &&\n\t\t(route.allow || route.paths || route.prefixes || route.requireHeader)\n\t) {\n\t\tthrow new EdgeRouteConflict(route.name);\n\t}\n}\n\n/** Where a stack's certificates come from. */\nexport type EdgeTls =\n\t/** A deployed stage: Let's Encrypt, over HTTP-01, on first request. */\n\t| { kind: 'acme' }\n\t/**\n\t * A certificate and key, as the proxy's container reads them: a deployed\n\t * stage's own (`deploy.compose.tls`), or — on the local stage — the one\n\t * gkm's local authority issued (`trust/authority.ts`).\n\t */\n\t| { kind: 'files'; certFile: string; keyFile: string };\n\n/** File descriptors a process holding sockets may open. */\nexport const NOFILE = { soft: 1_048_576, hard: 1_048_576 };\n\n/**\n * What the edge runs with: a descriptor per socket, twice — the client's and\n * the upstream's — and every local port for those upstream connections. One\n * edge address to one upstream has only the ephemeral range to open\n * connections from, ~28k by Linux's default; widened, ~64k per replica.\n */\nexport const EDGE_LIMITS: {\n\tsysctls: Record<string, string>;\n\tulimits: Record<string, { soft: number; hard: number }>;\n} = {\n\tsysctls: { 'net.ipv4.ip_local_port_range': '1024 65535' },\n\tulimits: { nofile: NOFILE },\n};\n\nexport type { ComposeProxy } from '../workspace/types.js';\n","/**\n * The stack's own edge, rendered for Caddy: one site block per route.\n *\n * Deployed, each host is the stage's real domain and Caddy gets it a\n * certificate from Let's Encrypt on first request — the same automatic HTTPS\n * it does anywhere, with nothing to configure but the name — or serves the\n * stage's own certificate (`deploy.compose.tls`). Locally the hosts are\n * `*.localhost` and the certificate is the one gkm's local authority issued,\n * as the `gkm dev` edge's is, so a local stack is `https://` like a deployed\n * one.\n *\n * Pure: the routes are data (`routes.ts`), and rendering them is one string.\n */\n\nimport { clientIpRule } from '../reconcile/caddyfile.js';\nimport {\n\tassertRouteRenderable,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype Upstream,\n} from './routes.js';\n\n/** Where Caddy reads a stage's own certificate, inside its container. */\nexport const CADDY_TLS_DIR = '/etc/caddy/tls';\n\nexport interface CaddyfileOptions {\n\ttls: EdgeTls;\n\t/**\n\t * The stack's token, on which a service of the stack keeps gkm's client\n\t * address through the edge — see `clientIpRule`.\n\t */\n\tedgeToken?: string;\n\t/** Where ACME sends expiry notices, when someone wants them. */\n\temail?: string;\n\t/**\n\t * `false` on the local stage: plain HTTP is not sent to HTTPS, whose\n\t * published port there may not be 443.\n\t */\n\tredirects?: boolean;\n}\n\n/** An upstream on the stack's own network: its service name. */\nfunction address({ service, port }: Upstream): string {\n\treturn `${service}:${port}`;\n}\n\n/** The Caddyfile for a stack's edge. */\nexport function edgeCaddyfile(\n\troutes: readonly EdgeRoute[],\n\toptions: CaddyfileOptions,\n): string {\n\tconst { tls } = options;\n\t// A wildcard site certified host by host: Caddy asks its `hosts` route\n\t// before it gets a certificate for one, so a name no tenant has is never\n\t// sent to Let's Encrypt.\n\tconst ask = routes.find((route) => route.wildcard?.tls.kind === 'on-demand')\n\t\t?.wildcard?.tls;\n\tconst onDemand =\n\t\task?.kind === 'on-demand'\n\t\t\t? `\n\ton_demand_tls {\n\t\task ${ask.ask}\n\t}`\n\t\t\t: '';\n\tconst settings = `${options.email ? `\\n\\temail ${options.email}` : ''}${\n\t\toptions.redirects === false ? '\\n\\tauto_https disable_redirects' : ''\n\t}${onDemand}`;\n\tconst global = settings ? `{${settings}\\n}` : '';\n\n\tconst certificate =\n\t\ttls.kind === 'files'\n\t\t\t? `\n\ttls ${tls.certFile} ${tls.keyFile}\n`\n\t\t\t: '';\n\n\t// The wildcard site last: Caddy prefers a named host to `*.<domain>`\n\t// wherever the blocks are, and reading it last says the same.\n\tconst blocks = [\n\t\t...routes.filter((route) => !route.wildcard),\n\t\t...routes.filter((route) => route.wildcard),\n\t].map((route) =>\n\t\tsiteBlock(\n\t\t\troute,\n\t\t\toptions.edgeToken,\n\t\t\troute.wildcard?.tls.kind === 'on-demand'\n\t\t\t\t? `\n\ttls {\n\t\ton_demand\n\t}\n`\n\t\t\t\t: certificate,\n\t\t),\n\t);\n\n\t// No blank line under the header: `caddy fmt` wants the first block there.\n\treturn `${HEADER}${global ? `${global}\\n\\n` : ''}${blocks.join('\\n\\n')}\\n`;\n}\n\n/** One route's site block. */\nfunction siteBlock(\n\troute: EdgeRoute,\n\tedgeToken: string | undefined,\n\tcertificate: string,\n): string {\n\tassertRouteRenderable(route);\n\tconst { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;\n\tconst allowed = [\n\t\t...(paths ?? []),\n\t\t...(prefixes ?? []).map((prefix) => `${prefix}*`),\n\t];\n\n\tconst except = route.wildcard?.except ?? [];\n\tconst checks = `${\n\t\texcept.length\n\t\t\t? `\n\t# Labels no tenant may take, although nothing in this stack answers them.\n\t@protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(' ')}\n\trespond @protected 404\n`\n\t\t\t: ''\n\t}${\n\t\tallow\n\t\t\t? `\n\t# Only these addresses — the peer Caddy sees, never a header a client\n\t# could set. Everything else is refused before it reaches the upstream.\n\t@denied not remote_ip ${allow.join(' ')}\n\trespond @denied 403\n`\n\t\t\t: ''\n\t}${\n\t\trequireHeader\n\t\t\t? `\n\t# Only what the CDN sends: it adds this header to every request, and this\n\t# host would be reached around the CDN otherwise.\n\t@forged not header ${requireHeader.name} \"${requireHeader.value}\"\n\trespond @forged 403\n`\n\t\t\t: ''\n\t}${\n\t\tauth\n\t\t\t? `\n\t# The stage's login, asked for before anything reaches the upstream.\n\tbasic_auth {\n\t\t${auth.user} ${auth.hash}\n\t}\n`\n\t\t\t: ''\n\t}${\n\t\tallowed.length\n\t\t\t? `\n\t# Only these paths answer. Everything else on this host is refused before\n\t# it reaches the upstream.\n\t@elsewhere not path ${allowed.join(' ')}\n\trespond @elsewhere 404\n`\n\t\t\t: ''\n\t}`;\n\n\tconst proxy = proxyBlock(route);\n\tconst body = handlers?.length\n\t\t? `${handlers\n\t\t\t\t.map(\n\t\t\t\t\t(handler, index) => `\n\t# Answered by another service: ${handler.name}.\n\t@handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(' ')}\n\thandle @handler${index} {\n\t\treverse_proxy ${handler.upstreams.map(address).join(' ')}\n\t}\n`,\n\t\t\t\t)\n\t\t\t\t.join('')}\n\thandle {${proxy.replace(/\\n/g, '\\n\\t')}\n\t}`\n\t\t: proxy;\n\n\treturn `https://${host} {${certificate}${clientIpRule(edgeToken)}\n${checks}${body}\n}`;\n}\n\n/** Where a route's requests go, when no handler took them. */\nfunction proxyBlock(route: EdgeRoute): string {\n\tconst { upstreams, prefix, streaming } = route;\n\tconst health = healthCheck(route);\n\treturn prefix\n\t\t? `\n\t# A bucket, served at a host of its own: the bucket is a prefix on MinIO,\n\t# which routes and signs on the Host header — so it is sent the upstream's.\n\treverse_proxy ${upstreams.map(address).join(' ')} {\n\t\trewrite ${prefix}{uri}\n\t\theader_up Host {upstream_hostport}${health}\n\t}`\n\t\t: `\n\t# Host and X-Forwarded-* are passed through as Caddy does by default, so\n\t# an app builds redirects, cookies and links on the address a caller used.\n\treverse_proxy ${upstreams.map(address).join(' ')}${\n\t\tstreaming || health\n\t\t\t? ` {${\n\t\t\t\t\tstreaming\n\t\t\t\t\t\t? `\n\t\t# Never buffer: a streamed response — server-sent events, a Next.js\n\t\t# RSC payload — reaches the client as each chunk is written.\n\t\tflush_interval -1`\n\t\t\t\t\t\t: ''\n\t\t\t\t}${health}\n\t}`\n\t\t\t: ''\n\t}`;\n}\n\n/**\n * Caddy's own check of each upstream, as the Traefik edge's\n * `loadBalancer.healthCheck`: one that stops answering is taken out of\n * rotation until it does again. Caddy starts once its apps have — not once\n * they are healthy — so this is what keeps a request from an upstream that\n * is not up, and a route to an app with none up answers an error (503)\n * rather than going missing.\n */\nfunction healthCheck({ health }: EdgeRoute): string {\n\treturn health\n\t\t? `\n\t\t# Each upstream asked on its own: one that stops answering is out of\n\t\t# rotation until it answers again.\n\t\thealth_uri ${health}\n\t\thealth_interval 5s\n\t\thealth_timeout 3s`\n\t\t: '';\n}\n\nconst HEADER = `# Generated by gkm compose from the construct manifest — do not edit.\n#\n# One host per API and site, each in front of its own container, one per\n# file server in front of the stack's MinIO — its processors' paths sent to\n# their own service — one per worker SNS pushes to and per processor unit a\n# CDN reaches, answering only those paths, and — when its logs are served\n# publicly — one for OpenObserve, to the addresses it allows. A site the\n# stage puts behind a password asks for its login first.\n`;\n","/**\n * Which image each app runs — and, for a tag, whether every one exists.\n *\n * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as\n * v1.4.0, and nothing else. So a stack is never half rolled out: every app's\n * image is asked of the registry before anything is pulled or the running\n * stack is touched, and one missing image stops the whole run naming every\n * one that is missing. Nor is a missing image quietly built instead — a build\n * of whatever is checked out here is not the release the tag names.\n */\n\nimport { GkmError } from '../errors';\nimport type { ComposeDocker } from './docker';\n\n/** One app's image, as the stack runs it. */\nexport interface AppImage {\n\tapp: string;\n\tref: string;\n\ttag: string;\n}\n\n/**\n * The tag a site's image carries for a release.\n *\n * A site's public URLs are inlined when it is built, so one bundle serves one\n * stage: `v1.4.0-production` and `v1.4.0-staging` are two images of the same\n * commit. A backend reads its URLs at runtime, so one image serves every stage\n * and its tag is the release's alone.\n */\nexport function siteTag(tag: string, stage: string): string {\n\treturn `${tag}-${stage}`;\n}\n\n/** Images a tag names that the registry does not have. */\nexport class ImageTagNotFound extends GkmError {\n\tconstructor(\n\t\treadonly tag: string,\n\t\treadonly refs: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`The registry has no image for ${refs.length === 1 ? 'this app' : `${refs.length} apps`} at '${tag}':\\n` +\n\t\t\t\trefs.map((ref) => ` - ${ref}`).join('\\n') +\n\t\t\t\t`\\nNothing was pulled or started. Push '${tag}' for every app from CI, ` +\n\t\t\t\t`pick a tag that exists, or run without --tag to build from this checkout.`,\n\t\t);\n\t\tthis.name = 'ImageTagNotFound';\n\t}\n}\n\n/** The registry did not answer, or did not let this machine in. */\nexport class RegistryUnreachable extends GkmError {\n\tconstructor(\n\t\treadonly ref: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not ask the registry about ${ref}: ${detail || 'no answer'}\\n` +\n\t\t\t\t`Nothing was pulled or started. Check the registry is reachable and ` +\n\t\t\t\t`that this machine is logged in to it (\\`docker login <registry>\\`).`,\n\t\t);\n\t\tthis.name = 'RegistryUnreachable';\n\t}\n}\n\n/**\n * Assert every image exists, before anything else happens.\n *\n * Asked all at once and reported all at once: a release missing two images is\n * one problem with two names, and finding the second only after fixing the\n * first is a slower way to learn the same thing.\n *\n * @throws {RegistryUnreachable} when the registry cannot say\n * @throws {ImageTagNotFound} listing every missing image\n */\nexport async function assertImagesExist(\n\tdocker: Pick<ComposeDocker, 'lookup'>,\n\ttag: string,\n\timages: readonly AppImage[],\n): Promise<void> {\n\tconst lookups = await Promise.all(\n\t\timages.map((image) => docker.lookup(image.ref)),\n\t);\n\n\tconst unreachable = lookups.find((lookup) => lookup.status === 'unreachable');\n\tif (unreachable?.status === 'unreachable') {\n\t\tthrow new RegistryUnreachable(unreachable.ref, unreachable.detail);\n\t}\n\n\tconst missing = lookups\n\t\t.filter((lookup) => lookup.status === 'missing')\n\t\t.map((lookup) => lookup.ref);\n\tif (missing.length > 0) throw new ImageTagNotFound(tag, missing);\n}\n\n/**\n * A push or a pull with no `deploy.registry` to push to or pull from.\n *\n * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which\n * Docker resolves to Docker Hub — so a release would be pushed to, or pulled\n * from, somebody else's account. It is never a fallback.\n */\nexport class RegistryRequired extends GkmError {\n\tconstructor(\n\t\t/** What needed the registry: `--push`, or a pull (`--tag`/`--pull`). */\n\t\treadonly operation: 'push' | 'pull',\n\t\t/** The ref an image would have had: a Docker Hub name. */\n\t\treadonly ref: string,\n\t) {\n\t\tsuper(\n\t\t\t`${operation === 'push' ? 'Pushing' : 'Pulling'} images needs a registry, and gkm.config.ts sets no deploy.registry: ` +\n\t\t\t\t`'${ref}' would be ${operation === 'push' ? 'pushed to' : 'pulled from'} Docker Hub. ` +\n\t\t\t\t`Set deploy.registry (e.g. registry: 'ghcr.io/acme') in gkm.config.ts.` +\n\t\t\t\t(operation === 'pull'\n\t\t\t\t\t? ' To run images built here instead, pass --build.'\n\t\t\t\t\t: ''),\n\t\t);\n\t\tthis.name = 'RegistryRequired';\n\t}\n}\n\n/**\n * What a push reports, and what a pull can pin to: each app's image as\n * `<ref>@sha256:…` — the tag it was pushed as, and the exact image, whatever\n * that tag is later moved to.\n */\nexport type ImageDigests = Record<string, string>;\n\n/** An image pinned to its digest: `<ref>@sha256:…`. */\nexport function pinnedRef(ref: string, digest: string): string {\n\treturn `${ref.split('@')[0]}@${digest}`;\n}\n\n/** A digests file with no entry for an app the stack runs. */\nexport class ImageDigestMissing extends GkmError {\n\tconstructor(\n\t\treadonly file: string,\n\t\treadonly apps: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`${file} pins no digest for ${apps.join(', ')}. Use the file the ` +\n\t\t\t\t`same release's \\`gkm compose --build --push --digests-file\\` wrote, ` +\n\t\t\t\t`or run without --digests-file to pull by tag.`,\n\t\t);\n\t\tthis.name = 'ImageDigestMissing';\n\t}\n}\n\n/** A digests file entry that is not this app's image. */\nexport class ImageDigestMismatch extends GkmError {\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly expected: string,\n\t\treadonly found: string,\n\t) {\n\t\tsuper(\n\t\t\t`The digests file pins '${app}' to ${found}, but this release runs ` +\n\t\t\t\t`${expected}. It was written for another registry, project, stage ` +\n\t\t\t\t`or tag; use the file this stage's push of this tag wrote.`,\n\t\t);\n\t\tthis.name = 'ImageDigestMismatch';\n\t}\n}\n\n/** A digests file that is not a JSON object of app to pinned ref. */\nexport class ImageDigestsInvalid extends GkmError {\n\tconstructor(\n\t\treadonly file: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`${file} is not a digests file (${detail}). It should be the JSON ` +\n\t\t\t\t`object \\`gkm compose --build --push --digests-file\\` writes: ` +\n\t\t\t\t`{ \"api\": \"<registry>/<image>:<tag>@sha256:…\" }.`,\n\t\t);\n\t\tthis.name = 'ImageDigestsInvalid';\n\t}\n}\n\n/** Parse a digests file's content, checking its shape. */\nexport function parseDigests(file: string, content: string): ImageDigests {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch (error) {\n\t\tthrow new ImageDigestsInvalid(\n\t\t\tfile,\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n\t\tthrow new ImageDigestsInvalid(file, 'not a JSON object');\n\t}\n\tfor (const [app, value] of Object.entries(parsed)) {\n\t\tif (typeof value !== 'string' || !/@sha256:[0-9a-f]{64}$/.test(value)) {\n\t\t\tthrow new ImageDigestsInvalid(\n\t\t\t\tfile,\n\t\t\t\t`'${app}' is not an <image>:<tag>@sha256:… ref`,\n\t\t\t);\n\t\t}\n\t}\n\treturn parsed as ImageDigests;\n}\n\n/**\n * Each image pinned to the digest the file names for it.\n *\n * @throws {ImageDigestMissing} naming every app the file has no entry for\n * @throws {ImageDigestMismatch} when an entry is another image or tag\n */\nexport function pinImages<T extends AppImage>(\n\tfile: string,\n\tdigests: ImageDigests,\n\timages: readonly T[],\n): T[] {\n\tconst missing = images\n\t\t.filter((image) => !digests[image.app])\n\t\t.map((image) => image.app);\n\tif (missing.length > 0) throw new ImageDigestMissing(file, missing);\n\n\treturn images.map((image) => {\n\t\tconst pinned = digests[image.app]!;\n\t\tif (pinned.split('@')[0] !== image.ref) {\n\t\t\tthrow new ImageDigestMismatch(image.app, image.ref, pinned);\n\t\t}\n\t\treturn { ...image, ref: pinned };\n\t});\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 server's shared edge, rendered for Traefik: what the edge itself runs\n * with, and what one stack registers with it.\n *\n * One Traefik per server owns 80 and 443, the ACME state and the redirect to\n * HTTPS. It is configured through its file provider alone: each stack writes\n * one file — its routers, services and middlewares, every name prefixed with\n * its compose project — into a directory the edge watches, and removes it\n * when it stops. There is no Docker socket: the edge never learns what runs\n * on the server except from those files.\n *\n * The edge and the stacks meet on one external Docker network. Only a\n * stack's public services join it, each under an alias prefixed with its\n * project (`<project>-api`), because the network is shared: a bare service\n * name there would be answered by every stack's `api`.\n *\n * Pure but for the edge's name, read from the environment once (see\n * {@link EDGE_PROJECT_ENV}): the documents are data, and the edge's side\n * effects are `edge.ts`'s.\n */\n\nimport { createHash } from 'node:crypto';\nimport { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from '@geekmidas/manifest';\nimport { parse, stringify } from 'yaml';\nimport {\n\tassertRouteRenderable,\n\tEDGE_LIMITS,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype Upstream,\n} from './routes.js';\n\n/**\n * The image, pinned: the edge is every stack's way in, so a new version is a\n * change to this line, not whatever `latest` is on the day a server starts.\n */\nexport const TRAEFIK_IMAGE = 'traefik:v3.7.13';\n\n/** The edge's name when nothing renames it: one per server. */\nexport const DEFAULT_EDGE_PROJECT = 'gkm-edge';\n\n/**\n * The variable that renames the edge — its compose project, and with it its\n * network and its volumes (`<project>_acme`, `_certs`, `_dynamic`). A testing\n * and advanced knob: an end-to-end suite runs an edge of its own beside a\n * developer's, and never touches theirs. Every command that registers with\n * one edge must be run with the same value.\n */\nexport const EDGE_PROJECT_ENV = 'GKM_EDGE_PROJECT';\n\n/** The edge's compose project: `GKM_EDGE_PROJECT`, else `gkm-edge`. */\nexport function edgeProject(env: NodeJS.ProcessEnv = process.env): string {\n\treturn env[EDGE_PROJECT_ENV] || DEFAULT_EDGE_PROJECT;\n}\n\n/**\n * The edge's compose project, one per server — read once, when gkm starts,\n * so every step of a run names the same edge.\n */\nexport const EDGE_PROJECT = edgeProject();\n\n/**\n * The external network the edge and every stack's public services share:\n * named after the edge, so a renamed edge has a network of its own.\n */\nexport const EDGE_NETWORK = EDGE_PROJECT;\n\n/** The edge's compose service. */\nexport const EDGE_SERVICE = 'traefik';\n\n/** Inside the edge's container: what it watches, and where certificates are. */\nexport const EDGE_DYNAMIC_DIR = '/etc/gkm-edge/dynamic';\nexport const EDGE_CERTS_DIR = '/etc/gkm-edge/certs';\n\n/** The certificate resolver every deployed route without its own certificate uses. */\nexport const ACME_RESOLVER = 'letsencrypt';\n\n/**\n * The resolver a wildcard site's `*.<domain>` certificate comes from: Let's\n * Encrypt issues a wildcard only over the DNS challenge, which the edge\n * answers by writing an `_acme-challenge` TXT record through Route 53.\n */\nexport const ACME_DNS_RESOLVER = 'letsencrypt-dns';\n\n/**\n * The key the edge writes those records with, inside its container: written\n * by the deploy of a stage with a wildcard site, and allowed nothing but\n * each such stage's `_acme-challenge` record (see `acmeDns.ts`).\n */\nexport const EDGE_AWS_CREDENTIALS = `${EDGE_CERTS_DIR}/aws-credentials`;\n\n/** The internal entrypoint the edge's health check asks; never published. */\nconst PING_PORT = 8082;\n\n/** A stack's service, as the edge — and the stack itself — reach it. */\nexport function edgeAlias(project: string, service: string): string {\n\treturn `${project}-${service}`;\n}\n\n/** A stack's certificate, as the edge's container reads it. */\nexport function edgeCertificatePaths(project: string): {\n\tcertFile: string;\n\tkeyFile: string;\n} {\n\treturn {\n\t\tcertFile: `${EDGE_CERTS_DIR}/${project}.crt`,\n\t\tkeyFile: `${EDGE_CERTS_DIR}/${project}.key`,\n\t};\n}\n\n/** The edge's ports on the host. */\nexport interface EdgePorts {\n\thttps: number;\n\thttp: number;\n}\n\n/**\n * The edge's static configuration: the entrypoints, the redirect, ACME, and\n * the directory it watches. No API and no dashboard — nothing about the edge\n * is reachable but the routes stacks register.\n */\nexport function traefikStatic(ports: EdgePorts): Record<string, unknown> {\n\treturn {\n\t\tglobal: { checkNewVersion: false, sendAnonymousUsage: false },\n\t\tentryPoints: {\n\t\t\tweb: {\n\t\t\t\taddress: ':80',\n\t\t\t\thttp: {\n\t\t\t\t\t// Every plain-HTTP request is sent to HTTPS — but an ACME\n\t\t\t\t\t// HTTP-01 challenge, which Traefik answers before the redirect.\n\t\t\t\t\tredirections: {\n\t\t\t\t\t\tentryPoint: {\n\t\t\t\t\t\t\t// The published port when it is not 443, so the redirect\n\t\t\t\t\t\t\t// lands where the edge actually listens.\n\t\t\t\t\t\t\tto: ports.https === 443 ? 'websecure' : `:${ports.https}`,\n\t\t\t\t\t\t\tscheme: 'https',\n\t\t\t\t\t\t\tpermanent: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twebsecure: { address: ':443' },\n\t\t\tping: { address: `:${PING_PORT}` },\n\t\t},\n\t\tping: { entryPoint: 'ping' },\n\t\tproviders: {\n\t\t\tfile: { directory: EDGE_DYNAMIC_DIR, watch: true },\n\t\t},\n\t\tcertificatesResolvers: {\n\t\t\t[ACME_RESOLVER]: {\n\t\t\t\tacme: {\n\t\t\t\t\tstorage: '/acme/acme.json',\n\t\t\t\t\thttpChallenge: { entryPoint: 'web' },\n\t\t\t\t},\n\t\t\t},\n\t\t\t[ACME_DNS_RESOLVER]: {\n\t\t\t\tacme: {\n\t\t\t\t\tstorage: '/acme/acme-dns.json',\n\t\t\t\t\tdnsChallenge: {\n\t\t\t\t\t\tprovider: 'route53',\n\t\t\t\t\t\t// Asked directly, so the record is seen as soon as Route 53\n\t\t\t\t\t\t// serves it rather than when a cache on the server expires.\n\t\t\t\t\t\tresolvers: ['1.1.1.1:53', '8.8.8.8:53'],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tlog: { level: 'INFO' },\n\t};\n}\n\n/** The edge's compose document. */\nexport function edgeCompose(options: {\n\tports: EdgePorts;\n\t/**\n\t * The static configuration, as written: handed to the container inline\n\t * (`configs.content`), so nothing is read from a path on whichever machine\n\t * runs the deploy — and its hash recreates the edge when it changes.\n\t */\n\tstaticConfig: string;\n\tlogging: { driver: string; options: Record<string, string> };\n}): Record<string, unknown> {\n\tconst { ports } = options;\n\treturn {\n\t\tname: EDGE_PROJECT,\n\t\tservices: {\n\t\t\t[EDGE_SERVICE]: {\n\t\t\t\timage: TRAEFIK_IMAGE,\n\t\t\t\trestart: 'unless-stopped',\n\t\t\t\tports: [`${ports.https}:443`, `${ports.http}:80`],\n\t\t\t\tconfigs: [{ source: 'traefik', target: '/etc/traefik/traefik.yml' }],\n\t\t\t\tvolumes: [\n\t\t\t\t\t// Volumes on the server, written through the engine (`docker\n\t\t\t\t\t// exec`): each stack's routes and certificate, replaced by a\n\t\t\t\t\t// rename the file provider sees whole.\n\t\t\t\t\t`dynamic:${EDGE_DYNAMIC_DIR}`,\n\t\t\t\t\t`certs:${EDGE_CERTS_DIR}`,\n\t\t\t\t\t'acme:/acme',\n\t\t\t\t],\n\t\t\t\t// Static configuration is read at start: a change to it is a\n\t\t\t\t// change to the service, so `up` recreates the edge.\n\t\t\t\tlabels: {\n\t\t\t\t\t'dev.geekmidas.edge.config': createHash('sha256')\n\t\t\t\t\t\t.update(options.staticConfig)\n\t\t\t\t\t\t.digest('hex')\n\t\t\t\t\t\t.slice(0, 16),\n\t\t\t\t},\n\t\t\t\t// What the DNS challenge writes with: read from the file a stage\n\t\t\t\t// with a wildcard site puts there, and never needed otherwise.\n\t\t\t\tenvironment: {\n\t\t\t\t\tAWS_SHARED_CREDENTIALS_FILE: EDGE_AWS_CREDENTIALS,\n\t\t\t\t\tAWS_REGION: 'us-east-1',\n\t\t\t\t},\n\t\t\t\tnetworks: ['edge'],\n\t\t\t\t// Every stack on the server shares it, so it is sized for the one\n\t\t\t\t// that holds the most sockets — see `EDGE_LIMITS`.\n\t\t\t\t...EDGE_LIMITS,\n\t\t\t\thealthcheck: {\n\t\t\t\t\ttest: ['CMD', 'traefik', 'healthcheck', '--ping'],\n\t\t\t\t\tinterval: '10s',\n\t\t\t\t\ttimeout: '5s',\n\t\t\t\t\tretries: 5,\n\t\t\t\t},\n\t\t\t\tlogging: options.logging,\n\t\t\t},\n\t\t},\n\t\tconfigs: { traefik: { content: options.staticConfig } },\n\t\tvolumes: { acme: {}, dynamic: {}, certs: {} },\n\t\tnetworks: { edge: { name: EDGE_NETWORK, external: true } },\n\t};\n}\n\n/** What a stack registers with the edge — its routes, and its certificate. */\nexport interface TraefikStackOptions {\n\tproject: string;\n\t/** ACME, or the stage's own certificate. */\n\ttls: EdgeTls;\n\t/**\n\t * The stack's token, on which a service of the stack keeps gkm's client\n\t * address through the edge — see `clientIpRule`.\n\t */\n\tedgeToken?: string;\n}\n\n/** A stack's dynamic configuration, as an object. */\nexport function traefikDynamic(\n\troutes: readonly EdgeRoute[],\n\toptions: TraefikStackOptions,\n): Record<string, unknown> {\n\tconst { project, tls, edgeToken } = options;\n\tconst name = (route: EdgeRoute, suffix?: string) =>\n\t\t`${project}-${route.name}${suffix ? `-${suffix}` : ''}`;\n\tconst url = ({ service, port }: Upstream) =>\n\t\t`http://${edgeAlias(project, service)}:${port}`;\n\n\tconst routers: Record<string, unknown> = {};\n\tconst services: Record<string, unknown> = {};\n\tconst middlewares: Record<string, unknown> = {};\n\n\t// gkm's own header, which only a service of this stack may send — the\n\t// auth server rate-limits by the client address it carries — removed from\n\t// every request that arrives from outside. An empty value is Traefik's\n\t// way of removing a request header. A request carrying the stack's token\n\t// is one of its own services calling a sibling through the edge: it is\n\t// matched by a router of its own, below, whose chain keeps the header.\n\tconst strip = `${project}-strip-gkm-headers`;\n\tif (routes.length > 0) {\n\t\tmiddlewares[strip] = {\n\t\t\theaders: { customRequestHeaders: { [CLIENT_IP_HEADER]: '' } },\n\t\t};\n\t}\n\n\tfor (const route of routes) {\n\t\tconst chain: string[] = [strip];\n\t\t// The client-address limits, which the stack's own services — all\n\t\t// behind one address — are not counted against.\n\t\tconst limited = new Set<string>();\n\t\tif (route.allow) {\n\t\t\t// The peer Traefik sees — never X-Forwarded-For, which a client\n\t\t\t// could set. Everything else gets 403.\n\t\t\tmiddlewares[name(route, 'allow')] = {\n\t\t\t\tipAllowList: { sourceRange: [...route.allow] },\n\t\t\t};\n\t\t\tchain.push(name(route, 'allow'));\n\t\t}\n\t\tif (route.auth) {\n\t\t\t// The stage's login, asked for before anything reaches the\n\t\t\t// upstream. The service's health check goes to the upstream\n\t\t\t// directly, so it is never asked.\n\t\t\tmiddlewares[name(route, 'auth')] = {\n\t\t\t\tbasicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] },\n\t\t\t};\n\t\t\tchain.push(name(route, 'auth'));\n\t\t}\n\t\t// Per client address, as the edge — the first hop — sees it: an\n\t\t// upgrade past either is answered 429 before it reaches a replica.\n\t\t// An upgraded request stays in flight while its socket is open, so\n\t\t// `inFlightReq` counts open sockets.\n\t\tif (route.limits?.handshakesPerMinute) {\n\t\t\tconst perMinute = route.limits.handshakesPerMinute;\n\t\t\tmiddlewares[name(route, 'rate')] = {\n\t\t\t\trateLimit: { average: perMinute, period: '1m', burst: perMinute },\n\t\t\t};\n\t\t\tchain.push(name(route, 'rate'));\n\t\t\tlimited.add(name(route, 'rate'));\n\t\t}\n\t\tif (route.limits?.connectionsPerIp) {\n\t\t\tmiddlewares[name(route, 'in-flight')] = {\n\t\t\t\tinFlightReq: { amount: route.limits.connectionsPerIp },\n\t\t\t};\n\t\t\tchain.push(name(route, 'in-flight'));\n\t\t\tlimited.add(name(route, 'in-flight'));\n\t\t}\n\t\tif (route.prefix) {\n\t\t\tmiddlewares[name(route, 'prefix')] = {\n\t\t\t\taddPrefix: { prefix: route.prefix },\n\t\t\t};\n\t\t\tchain.push(name(route, 'prefix'));\n\t\t}\n\n\t\tassertRouteRenderable(route);\n\t\t// Only the paths it names, where it names some: a request for any\n\t\t// other matches no router, and the edge answers it 404 itself. So\n\t\t// does one without the header a CDN sends, where it requires one.\n\t\tconst allowed = [\n\t\t\t...(route.paths ?? []).map((path) => `Path(\\`${path}\\`)`),\n\t\t\t...(route.prefixes ?? []).map((prefix) => `PathPrefix(\\`${prefix}\\`)`),\n\t\t];\n\t\tconst paths = allowed.length ? ` && (${allowed.join(' || ')})` : '';\n\t\tconst header = route.requireHeader\n\t\t\t? ` && Header(\\`${route.requireHeader.name}\\`, \\`${route.requireHeader.value}\\`)`\n\t\t\t: '';\n\n\t\tconst certificate = (): Record<string, unknown> =>\n\t\t\troute.wildcard?.tls.kind === 'dns'\n\t\t\t\t? {\n\t\t\t\t\t\tcertResolver: ACME_DNS_RESOLVER,\n\t\t\t\t\t\tdomains: [{ main: `*.${route.wildcard.domain}` }],\n\t\t\t\t\t}\n\t\t\t\t: tls.kind === 'acme'\n\t\t\t\t\t? { certResolver: ACME_RESOLVER }\n\t\t\t\t\t: {};\n\n\t\t// Each handler: a router of its own on the same host, ahead of the\n\t\t// route's, to a service of its own.\n\t\tfor (const handler of route.handlers ?? []) {\n\t\t\tconst handlerName = name(route, handler.name);\n\t\t\trouters[handlerName] = {\n\t\t\t\trule: `Host(\\`${route.host}\\`) && (${handler.prefixes\n\t\t\t\t\t.map((prefix) => `PathPrefix(\\`${prefix}\\`)`)\n\t\t\t\t\t.join(' || ')})`,\n\t\t\t\t// Above the route's own router, whatever the rules' lengths.\n\t\t\t\tpriority: 10_000,\n\t\t\t\tentryPoints: ['websecure'],\n\t\t\t\tservice: handlerName,\n\t\t\t\tmiddlewares: [strip],\n\t\t\t\ttls: certificate(),\n\t\t\t};\n\t\t\tservices[handlerName] = {\n\t\t\t\tloadBalancer: {\n\t\t\t\t\tservers: handler.upstreams.map((upstream) => ({\n\t\t\t\t\t\turl: url(upstream),\n\t\t\t\t\t})),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst rule = `${hostRule(route)}${paths}${header}`;\n\t\trouters[name(route)] = {\n\t\t\trule,\n\t\t\t// Below every named host's router, whatever the rules' lengths: a\n\t\t\t// wildcard site gets only the labels nothing else answers.\n\t\t\t...(route.wildcard ? { priority: 1 } : {}),\n\t\t\tentryPoints: ['websecure'],\n\t\t\tservice: name(route),\n\t\t\tmiddlewares: chain,\n\t\t\ttls: certificate(),\n\t\t};\n\t\t// The stack's own services, proven by its token: the same route, to\n\t\t// the same service, keeping gkm's header. Its longer rule puts it ahead\n\t\t// of the route's own; a wildcard's, just above that one's.\n\t\tif (edgeToken && !route.prefix) {\n\t\t\tconst trusted = chain.slice(1).filter((m) => !limited.has(m));\n\t\t\trouters[name(route, 'stack')] = {\n\t\t\t\trule: `${rule} && Header(\\`${EDGE_TOKEN_HEADER}\\`, \\`${edgeToken}\\`)`,\n\t\t\t\t...(route.wildcard ? { priority: 2 } : {}),\n\t\t\t\tentryPoints: ['websecure'],\n\t\t\t\tservice: name(route),\n\t\t\t\t...(trusted.length > 0 ? { middlewares: trusted } : {}),\n\t\t\t\ttls: certificate(),\n\t\t\t};\n\t\t}\n\n\t\tservices[name(route)] = {\n\t\t\tloadBalancer: {\n\t\t\t\tservers: route.upstreams.map((upstream) => ({ url: url(upstream) })),\n\t\t\t\t// A bucket is routed and signed on the Host header, so MinIO is\n\t\t\t\t// sent its own; an app is sent the one the caller used, which is\n\t\t\t\t// what it builds redirects, cookies and links on.\n\t\t\t\t...(route.prefix ? { passHostHeader: false } : {}),\n\t\t\t\t...(route.streaming\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t// Never buffer: each chunk of a streamed response is\n\t\t\t\t\t\t\t// flushed to the client as it is written.\n\t\t\t\t\t\t\tresponseForwarding: { flushInterval: '-1ms' },\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(route.health\n\t\t\t\t\t? {\n\t\t\t\t\t\t\thealthCheck: {\n\t\t\t\t\t\t\t\tpath: route.health,\n\t\t\t\t\t\t\t\tinterval: '5s',\n\t\t\t\t\t\t\t\ttimeout: '3s',\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\treturn {\n\t\thttp: {\n\t\t\trouters,\n\t\t\tservices,\n\t\t\t...(Object.keys(middlewares).length > 0 ? { middlewares } : {}),\n\t\t},\n\t\t...(tls.kind === 'files'\n\t\t\t? {\n\t\t\t\t\ttls: {\n\t\t\t\t\t\tcertificates: [{ certFile: tls.certFile, keyFile: tls.keyFile }],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * The hosts a route answers, as a Traefik rule: its own, or — for a wildcard\n * site — exactly one label under its domain, but the ones it never takes.\n * One label, as a wildcard certificate covers: a stage at\n * `staging.example.com` is never reached through `example.com`'s wildcard.\n */\nfunction hostRule(route: EdgeRoute): string {\n\tif (!route.wildcard) return `Host(\\`${route.host}\\`)`;\n\tconst { domain, except } = route.wildcard;\n\tconst pattern = `^[a-z0-9-]+\\\\.${domain.replace(/\\./g, '\\\\.')}$`;\n\treturn [\n\t\t`HostRegexp(\\`${pattern}\\`)`,\n\t\t...except.map((label) => `!Host(\\`${label}.${domain}\\`)`),\n\t].join(' && ');\n}\n\n/**\n * A host a stack routes on the shared edge: one name, or — for a wildcard\n * site — every one label under a domain but the ones it never takes.\n */\nexport type EdgeClaim =\n\t| { host: string }\n\t| { wildcard: string; except: readonly string[] };\n\n/** What a stack's routes claim on the edge, from the route model. */\nexport function edgeClaims(routes: readonly EdgeRoute[]): EdgeClaim[] {\n\treturn routes.map((route) =>\n\t\troute.wildcard\n\t\t\t? {\n\t\t\t\t\twildcard: route.wildcard.domain.toLowerCase(),\n\t\t\t\t\texcept: [...route.wildcard.except],\n\t\t\t\t}\n\t\t\t: { host: route.host.toLowerCase() },\n\t);\n}\n\n/**\n * The comment line a stack's file carries its claims on: a comment, because\n * Traefik's file provider refuses a whole file over a key it does not know,\n * and gkm reads it back rather than taking the routers' rules apart.\n */\nconst CLAIMS_PREFIX = '# gkm-claims: ';\n\n/**\n * The hosts a stack's file on the edge claims: from its claims line, or — a\n * file written before gkm wrote one — from its routers' rules, in the shapes\n * `traefikDynamic` renders them.\n */\nexport function readEdgeClaims(file: string): EdgeClaim[] {\n\tfor (const line of file.split('\\n')) {\n\t\tif (!line.startsWith(CLAIMS_PREFIX)) continue;\n\t\ttry {\n\t\t\tconst claims = JSON.parse(line.slice(CLAIMS_PREFIX.length));\n\t\t\tif (Array.isArray(claims)) return claims.filter(isClaim);\n\t\t} catch {\n\t\t\t// A line that is not gkm's: the rules below still say.\n\t\t}\n\t}\n\tlet document: unknown;\n\ttry {\n\t\tdocument = parse(file);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst routers = (document as { http?: { routers?: unknown } } | null)?.http\n\t\t?.routers;\n\tif (!routers || typeof routers !== 'object') return [];\n\tconst claims: EdgeClaim[] = [];\n\tfor (const router of Object.values(routers)) {\n\t\tconst rule = (router as { rule?: unknown } | null)?.rule;\n\t\tif (typeof rule === 'string') claims.push(...ruleClaims(rule));\n\t}\n\treturn claims;\n}\n\nfunction isClaim(value: unknown): value is EdgeClaim {\n\tif (!value || typeof value !== 'object') return false;\n\tconst claim = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof claim.host === 'string' ||\n\t\t(typeof claim.wildcard === 'string' && Array.isArray(claim.except))\n\t);\n}\n\n/**\n * The hosts a rule matches: each `Host(\\`a\\`)` not negated, and a\n * `HostRegexp` of a wildcard site — one label under a domain — with the\n * `!Host` labels it leaves out.\n */\nfunction ruleClaims(rule: string): EdgeClaim[] {\n\tconst negated = [...rule.matchAll(/!\\s*Host\\(`([^`]+)`\\)/g)].map((match) =>\n\t\tmatch[1]!.toLowerCase(),\n\t);\n\tconst wildcard = /HostRegexp\\(`\\^\\[a-z0-9-\\]\\+\\\\\\.(.+)\\$`\\)/.exec(rule);\n\tif (wildcard) {\n\t\tconst domain = wildcard[1]!.replace(/\\\\\\./g, '.').toLowerCase();\n\t\tconst suffix = `.${domain}`;\n\t\treturn [\n\t\t\t{\n\t\t\t\twildcard: domain,\n\t\t\t\texcept: negated\n\t\t\t\t\t.filter((host) => host.endsWith(suffix))\n\t\t\t\t\t.map((host) => host.slice(0, -suffix.length)),\n\t\t\t},\n\t\t];\n\t}\n\treturn [...rule.matchAll(/(?<![!\\w])Host\\(`([^`]+)`\\)/g)].map((match) => ({\n\t\thost: match[1]!.toLowerCase(),\n\t}));\n}\n\n/**\n * Where two claims meet, as a host to name — or undefined where they never\n * do. A wildcard takes one label under its domain, so it meets a name one\n * label under it that it does not leave out, and another wildcard on the\n * same domain.\n */\nexport function claimsOverlap(a: EdgeClaim, b: EdgeClaim): string | undefined {\n\tif ('host' in a && 'host' in b) {\n\t\treturn a.host === b.host ? a.host : undefined;\n\t}\n\tif ('wildcard' in a && 'wildcard' in b) {\n\t\treturn a.wildcard === b.wildcard ? `*.${a.wildcard}` : undefined;\n\t}\n\tconst [name, wildcard] = ('host' in a ? [a, b] : [b, a]) as [\n\t\t{ host: string },\n\t\t{ wildcard: string; except: readonly string[] },\n\t];\n\tconst suffix = `.${wildcard.wildcard}`;\n\tif (!name.host.endsWith(suffix)) return undefined;\n\tconst label = name.host.slice(0, -suffix.length);\n\tif (!/^[a-z0-9-]+$/.test(label) || wildcard.except.includes(label)) {\n\t\treturn undefined;\n\t}\n\treturn name.host;\n}\n\n/** A stack's dynamic configuration file, as written to the edge's directory. */\nexport function traefikDynamicFile(\n\troutes: readonly EdgeRoute[],\n\toptions: TraefikStackOptions,\n): string {\n\treturn `# Generated by gkm compose for ${options.project} — do not edit.\n# The shared edge (${EDGE_PROJECT}) reads every file in this directory; this\n# one is removed by gkm compose --down. The hosts it routes, which no other\n# stack on the edge may route:\n${CLAIMS_PREFIX}${JSON.stringify(edgeClaims(routes))}\n${yaml(traefikDynamic(routes, options))}`;\n}\n\n/** The edge's static configuration file. */\nexport function traefikStaticFile(ports: EdgePorts): string {\n\treturn `# Generated by gkm compose — the server's shared edge. Do not edit.\n${yaml(traefikStatic(ports))}`;\n}\n\n/** The edge's compose file. */\nexport function edgeComposeFile(\n\toptions: Parameters<typeof edgeCompose>[0],\n): string {\n\treturn `# Generated by gkm compose — the server's shared edge. Do not edit.\n#\n# Started by the first stack that runs with proxy: 'traefik', and left\n# running by gkm compose --down. Stop it, once nothing uses it, with:\n#\n# docker compose -p ${EDGE_PROJECT} down\n${yaml(edgeCompose(options))}`;\n}\n\nfunction yaml(value: unknown): string {\n\treturn stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });\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 ConstructManifest,\n\tEDGE_TOKEN_KEY,\n\tisWildcardSite,\n\tprovideKey,\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} 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 } from '../deploy/identity.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 { stageProviderNotes } from '../providers/notes.js';\nimport {\n\tORIGIN_VERIFY_HEADER,\n\toriginSecretKey,\n\tprocessorOriginHost,\n} from '../providers/processorOrigin.js';\nimport { networkEnv, processEnvKeys } from '../reconcile/apps.js';\nimport { hostFor, LOCAL_TLD } from '../reconcile/caddyfile.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 type { StageSecrets } from '../secrets/types.js';\nimport {\n\tfindRootDomain,\n\tnormalizeDnsConfig,\n} from '../target/dokploy/dns/index.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\ttelemetryOf,\n\tusesTelemetry,\n} from '../telemetry/edges.js';\nimport {\n\ttype LocalAuthorityPaths,\n\tlocalAuthorityPaths,\n} from '../trust/authority.js';\nimport { DEFAULT_EVENTS } from '../types.js';\nimport { appKey } from '../workspace/derive.js';\nimport type {\n\tComposeTlsConfig,\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport { CADDY_TLS_DIR, edgeCaddyfile } from './caddyfile.js';\nimport { isReservedStageKey } from './dnsConfig.js';\nimport { type AppImage, siteTag } from './images.js';\nimport {\n\tLOGS_SERVICE,\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\ttype ComposeProxy,\n\tEDGE_LIMITS,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype EdgeWildcard,\n\tNOFILE,\n} from './routes.js';\nimport {\n\tOFFLINE_BUILD_ADDRESS,\n\tofflineBuildHosts,\n\tpublicBuildValues,\n\trunsServer,\n} from './siteBuild.js';\nimport { type SiteAuth, siteAuth, sitePasswordKey } from './sitePassword.js';\nimport {\n\tEDGE_NETWORK,\n\tedgeAlias,\n\tedgeCertificatePaths,\n\ttraefikDynamicFile,\n} from './traefik.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/** 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/**\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. */\n\thost: 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 Route 53 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}\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/** A release tag, or — building — the commit. */\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 {@link LOGS_PORT_ENV}. */\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 === provideKey(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\tprovideKey(declaration.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, local);\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(provideKey(resource.id, 'from'), resource);\n\t\t\towners.set(provideKey(resource.id, 'inboxUrl'), resource);\n\t\t}\n\t\tif (resource.kind === 'external-api') {\n\t\t\towners.set(provideKey(resource.id, 'credentials'), resource);\n\t\t}\n\t\tif (resource.kind === 'inbox') {\n\t\t\towners.set(provideKey(resource.id, 'domain'), resource);\n\t\t}\n\t\tif (resource.kind === 'websocket-api') {\n\t\t\towners.set(\n\t\t\t\tprovideKey(resource.id, '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\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\tprovideKey(resource.id, 'eventsConnectionString'),\n\t\t\tresource.id,\n\t\t);\n\t\tbucketEventKeys.set(provideKey(resource.id, 'eventsToken'), resource.id);\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 = `${resource.subdomain ?? appKey(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// 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 ? { mailFrom: `noreply@${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\tconst outside = networkEnv(\n\t\tplan,\n\t\t{ ...derivation, addresses: publicAddresses },\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\tif (custom[key] !== undefined) return custom[key];\n\t\t\tif (owner.kind === 'file-server') return fileServers.get(owner.id)?.url;\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 === provideKey(owner.id, '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)),\n\t\t\t\tcustom,\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\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\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)),\n\t\t\t\tcustom,\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 = worker?.env?.[provideKey(bucket, 'eventsConnectionString')];\n\t\t\tconst token = worker?.env?.[provideKey(bucket, '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())\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...(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) => route.host === mailInbox.host);\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{ layout, workspaceRoot: workspace.root, cache: STACK_CACHE },\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\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 host on the edge, as the apps are handed it.\n\t\t\taddresses: {\n\t\t\t\t...publicAddresses,\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t[...fileServers].map(([id, { url }]) => [id, url]),\n\t\t\t\t),\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};\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 = hostOf(name, app, workspace, resource, options);\n\t\tconst site = declaration.kind === 'site';\n\t\tconst tag = site\n\t\t\t? siteTag(options.images.tag, options.stage)\n\t\t\t: options.images.tag;\n\t\tconst ref = validateImageRef(\n\t\t\timageRef(options.identity, name, options.images.registry, tag),\n\t\t);\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\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.\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: 'route53' } } so the ` +\n\t\t\t\t\t\t`shared edge gets one over the 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 give the site ` +\n\t\t\t\t\t\t`\\`hosts\\` so Caddy gets one per tenant, on demand.`,\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 Route 53 manages the domain; on the stack's own Caddy, one\n * per host on demand, asked of the site's `hosts` route.\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 dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\t\t\tconst root = findRootDomain(domain, dns);\n\t\t\tif (root && dns[root]?.provider === 'route53') return { kind: 'dns' };\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/** Refuse a stack where one host would be routed to two services. */\nfunction assertHostsUnique(routes: readonly EdgeRoute[]): void {\n\tconst claimed = new Map<string, string>();\n\tfor (const { host, name } of routes) {\n\t\tconst first = claimed.get(host);\n\t\tif (first !== undefined) throw new EdgeHostTaken(host, first, name);\n\t\tclaimed.set(host, name);\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\tref: validateImageRef(\n\t\t\t\timageRef(\n\t\t\t\t\toptions.identity,\n\t\t\t\t\tunit.name,\n\t\t\t\t\toptions.images.registry,\n\t\t\t\t\toptions.images.tag,\n\t\t\t\t),\n\t\t\t),\n\t\t\ttag: options.images.tag,\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\tref: validateImageRef(\n\t\t\timageRef(\n\t\t\t\toptions.identity,\n\t\t\t\tunit.name,\n\t\t\t\toptions.images.registry,\n\t\t\t\toptions.images.tag,\n\t\t\t),\n\t\t),\n\t\ttag: options.images.tag,\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 host an app answers on for a stage: the `gkm dev` edge's\n * `*.localhost` names for the local stage, and the stage's domain — by the\n * same rule a deploy follows — for any other.\n */\nfunction hostOf(\n\tname: string,\n\tapp: NormalizedAppConfig,\n\tworkspace: NormalizedWorkspace,\n\tresource: PlannedResource,\n\toptions: { local: boolean; stage: string },\n): string {\n\tif (options.local) return hostFor(resource, workspace.name);\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\tconst domain = workspace.domains?.[options.stage];\n\t\tif (!domain) throw new NoDomainForStage(options.stage);\n\t\treturn `${WILDCARD_SUBDOMAIN}.${domain}`;\n\t}\n\n\treturn 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}\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.map((route) => route.host))]\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}\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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C,CACxC,KAAK,IAAI,EAAE;AACd"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
|
|
2
|
-
import { Q as imageRef, a as findRootDomain, o as normalizeDnsConfig } from "./credentials-
|
|
2
|
+
import { Q as imageRef, a as findRootDomain, o as normalizeDnsConfig } from "./credentials-DidjPIcM.mjs";
|
|
3
3
|
import { B as LOGS_PORT, I as otlpTelemetryEnv, L as resolveStageTelemetry, lt as certificateFor, ut as proxyFor, yt as isReservedStageKey, z as telemetryEnv } from "./workspace-DFGsrjGD.mjs";
|
|
4
|
-
import { A as originSecretKey, B as WORKER_PORT, Bt as LOCAL_TLD, D as ORIGIN_VERIFY_HEADER, Ft as scopeTelemetryEnv, Ht as hostFor, I as LOCAL_CA_BUILD_SECRET, L as PRERENDER_RUN_ARG, N as composeBuildPaths, Ot as localRolePassword, Pt as isTelemetryKey, R as PROCESSOR_PORT, Rt as telemetryOf, St as bucketPolicies, Vt as clientIpRule, Yt as stageBackups, a as networkEnv, ct as processorUnits, ht as stackBackups, it as runsServer, j as processorOriginHost, jt as planFor, lt as workerUnits, mt as backupsService, nt as offlineBuildHosts, rt as publicBuildValues, s as processEnvKeys, tt as OFFLINE_BUILD_ADDRESS, ut as BACKUPS_SERVICE, w as localAuthorityPaths, xt as bucketLifecycles, z as TURBO_VERSION, zt as usesTelemetry } from "./apps-
|
|
5
|
-
import { A as minioWebhookEnv, C as redisService, M as watchedBuckets, N as EMULATOR_ACCESS_KEY_ID, Q as logsService, R as DEFAULT_IMAGES, S as STACK_CACHE, T as stackRedis, V as portKeys, X as LOGS_SERVICE, at as resolveHost, et as stackLogs, g as postgresSuperuser, it as isMainFrontendApp, n as composeFor, nt as NoDomainForStage, p as LOCAL_RABBITMQ_USER, x as REDIS_SERVICE } from "./compose-
|
|
4
|
+
import { A as originSecretKey, B as WORKER_PORT, Bt as LOCAL_TLD, D as ORIGIN_VERIFY_HEADER, Ft as scopeTelemetryEnv, Ht as hostFor, I as LOCAL_CA_BUILD_SECRET, L as PRERENDER_RUN_ARG, N as composeBuildPaths, Ot as localRolePassword, Pt as isTelemetryKey, R as PROCESSOR_PORT, Rt as telemetryOf, St as bucketPolicies, Vt as clientIpRule, Yt as stageBackups, a as networkEnv, ct as processorUnits, ht as stackBackups, it as runsServer, j as processorOriginHost, jt as planFor, lt as workerUnits, mt as backupsService, nt as offlineBuildHosts, rt as publicBuildValues, s as processEnvKeys, tt as OFFLINE_BUILD_ADDRESS, ut as BACKUPS_SERVICE, w as localAuthorityPaths, xt as bucketLifecycles, z as TURBO_VERSION, zt as usesTelemetry } from "./apps-CggMxcW9.mjs";
|
|
5
|
+
import { A as minioWebhookEnv, C as redisService, M as watchedBuckets, N as EMULATOR_ACCESS_KEY_ID, Q as logsService, R as DEFAULT_IMAGES, S as STACK_CACHE, T as stackRedis, V as portKeys, X as LOGS_SERVICE, at as resolveHost, et as stackLogs, g as postgresSuperuser, it as isMainFrontendApp, n as composeFor, nt as NoDomainForStage, p as LOCAL_RABBITMQ_USER, x as REDIS_SERVICE } from "./compose-DS0L5WGA.mjs";
|
|
6
6
|
import { a as SNS_SUBSCRIPTIONS_KEY, c as INBOX_RELAY_TOKEN_KEY, d as inboxWebhookUrl, o as objectsRoute, s as subscriberRoute, u as inboxRelayWorker } from "./SubscriberGenerator-CzPrixYu.mjs";
|
|
7
7
|
import { g as appKey } from "./config-BLrAd7Of.mjs";
|
|
8
8
|
import { n as DEFAULT_EVENTS } from "./types-Y1NfWlyG.mjs";
|
|
9
|
-
import { _ as suppliedOnly, f as devServicesUsed, g as stageServiceDeclarations, i as stageProviderNotes, p as externalServices } from "./notes-
|
|
10
|
-
import { o as processorDockerfile, r as appDockerfile, s as workerDockerfile, v as validateImageRef } from "./docker-
|
|
9
|
+
import { _ as suppliedOnly, f as devServicesUsed, g as stageServiceDeclarations, i as stageProviderNotes, p as externalServices } from "./notes-CV9tczQF.mjs";
|
|
10
|
+
import { o as processorDockerfile, r as appDockerfile, s as workerDockerfile, v as validateImageRef } from "./docker-BeO31G2F.mjs";
|
|
11
11
|
import { join } from "node:path";
|
|
12
12
|
import { createHash } from "node:crypto";
|
|
13
13
|
import { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER, EDGE_TOKEN_KEY, WILDCARD_SUBDOMAIN, isWildcardSite, provideKey, provisionOrder } from "@geekmidas/manifest";
|
|
@@ -629,6 +629,7 @@ function traefikDynamic(routes, options) {
|
|
|
629
629
|
if (routes.length > 0) middlewares[strip] = { headers: { customRequestHeaders: { [CLIENT_IP_HEADER]: "" } } };
|
|
630
630
|
for (const route of routes) {
|
|
631
631
|
const chain = [strip];
|
|
632
|
+
const limited = /* @__PURE__ */ new Set();
|
|
632
633
|
if (route.allow) {
|
|
633
634
|
middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
|
|
634
635
|
chain.push(name(route, "allow"));
|
|
@@ -637,6 +638,21 @@ function traefikDynamic(routes, options) {
|
|
|
637
638
|
middlewares[name(route, "auth")] = { basicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] } };
|
|
638
639
|
chain.push(name(route, "auth"));
|
|
639
640
|
}
|
|
641
|
+
if (route.limits?.handshakesPerMinute) {
|
|
642
|
+
const perMinute = route.limits.handshakesPerMinute;
|
|
643
|
+
middlewares[name(route, "rate")] = { rateLimit: {
|
|
644
|
+
average: perMinute,
|
|
645
|
+
period: "1m",
|
|
646
|
+
burst: perMinute
|
|
647
|
+
} };
|
|
648
|
+
chain.push(name(route, "rate"));
|
|
649
|
+
limited.add(name(route, "rate"));
|
|
650
|
+
}
|
|
651
|
+
if (route.limits?.connectionsPerIp) {
|
|
652
|
+
middlewares[name(route, "in-flight")] = { inFlightReq: { amount: route.limits.connectionsPerIp } };
|
|
653
|
+
chain.push(name(route, "in-flight"));
|
|
654
|
+
limited.add(name(route, "in-flight"));
|
|
655
|
+
}
|
|
640
656
|
if (route.prefix) {
|
|
641
657
|
middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
|
|
642
658
|
chain.push(name(route, "prefix"));
|
|
@@ -670,14 +686,17 @@ function traefikDynamic(routes, options) {
|
|
|
670
686
|
middlewares: chain,
|
|
671
687
|
tls: certificate()
|
|
672
688
|
};
|
|
673
|
-
if (edgeToken && !route.prefix)
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
689
|
+
if (edgeToken && !route.prefix) {
|
|
690
|
+
const trusted = chain.slice(1).filter((m) => !limited.has(m));
|
|
691
|
+
routers[name(route, "stack")] = {
|
|
692
|
+
rule: `${rule} && Header(\`${EDGE_TOKEN_HEADER}\`, \`${edgeToken}\`)`,
|
|
693
|
+
...route.wildcard ? { priority: 2 } : {},
|
|
694
|
+
entryPoints: ["websecure"],
|
|
695
|
+
service: name(route),
|
|
696
|
+
...trusted.length > 0 ? { middlewares: trusted } : {},
|
|
697
|
+
tls: certificate()
|
|
698
|
+
};
|
|
699
|
+
}
|
|
681
700
|
services[name(route)] = { loadBalancer: {
|
|
682
701
|
servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
|
|
683
702
|
...route.prefix ? { passHostHeader: false } : {},
|
|
@@ -1579,6 +1598,7 @@ function composeStack(input) {
|
|
|
1579
1598
|
user: app.auth.user,
|
|
1580
1599
|
hash: app.auth.hash
|
|
1581
1600
|
} } : {},
|
|
1601
|
+
...app.limits ? { limits: app.limits } : {},
|
|
1582
1602
|
health: app.kind === "site" ? "/" : "/health"
|
|
1583
1603
|
})),
|
|
1584
1604
|
...[...fileServers.values()].map(({ route }) => route),
|
|
@@ -1778,6 +1798,7 @@ function stackApps(workspace, manifest, plan, options) {
|
|
|
1778
1798
|
kind: declaration.kind,
|
|
1779
1799
|
...declaration.kind === "site" ? { variant: declaration.variant } : {},
|
|
1780
1800
|
replicas: declaration.kind === "websocket-api" ? declaration.replicas ?? 1 : 1,
|
|
1801
|
+
...declaration.kind === "websocket-api" && declaration.limits ? { limits: declaration.limits } : {},
|
|
1781
1802
|
runtime: !site || runsServer(declaration),
|
|
1782
1803
|
path: app.path,
|
|
1783
1804
|
port: app.port,
|
|
@@ -2232,4 +2253,4 @@ function envFile(env) {
|
|
|
2232
2253
|
//#endregion
|
|
2233
2254
|
export { traefikStaticFile as C, parseDigests as D, assertImagesExist as E, pinImages as O, readEdgeClaims as S, RegistryRequired as T, EDGE_NETWORK as _, composeProject as a, claimsOverlap as b, derivedCredentials as c, stackDir as d, stackPlan as f, EDGE_DYNAMIC_DIR as g, EDGE_CERTS_DIR as h, LOOPBACK_SERVICES as i, pinnedRef as k, envFile as l, EDGE_AWS_CREDENTIALS as m, LOGS_PORT_ENV as n, composeStack as o, withCaddyConfigs as p, LOG_ROTATION as r, deployedInboxEnv as s, EDGE_PORT_ENV as t, replicaNames as u, EDGE_PROJECT as v, assertSitePasswords as w, edgeComposeFile as x, EDGE_SERVICE as y };
|
|
2234
2255
|
|
|
2235
|
-
//# sourceMappingURL=stack-
|
|
2256
|
+
//# sourceMappingURL=stack-BrqdoNWg.mjs.map
|