@rebasepro/cli 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/README.md +2 -1
  2. package/bin/rebase.js +143 -4
  3. package/dist/{agent-setup-B5AKHOgt.js → agent-setup-D9mHRZ5R.js} +125 -3
  4. package/dist/agent-setup-D9mHRZ5R.js.map +1 -0
  5. package/dist/{api-keys-Tm7zvAPe.js → api-keys-CyJ26KEJ.js} +41 -10
  6. package/dist/api-keys-CyJ26KEJ.js.map +1 -0
  7. package/dist/{apps-BsU_ILbP.js → apps-CnLDV5b6.js} +6 -7
  8. package/dist/{apps-BsU_ILbP.js.map → apps-CnLDV5b6.js.map} +1 -1
  9. package/dist/{atlas-dev-database-OWtqnG7W.js → atlas-dev-database-BODqdCWt.js} +4 -4
  10. package/dist/{atlas-dev-database-OWtqnG7W.js.map → atlas-dev-database-BODqdCWt.js.map} +1 -1
  11. package/dist/{auth-Vl2hFKXP.js → auth-dII2jCO1.js} +10 -8
  12. package/dist/auth-dII2jCO1.js.map +1 -0
  13. package/dist/{branch-pointer-9DnwkFJJ.js → branch-pointer-BQUF6lYa.js} +1 -1
  14. package/dist/{build-BBgT8EJZ.js → build-Cza7ZQrp.js} +6 -7
  15. package/dist/{build-BBgT8EJZ.js.map → build-Cza7ZQrp.js.map} +1 -1
  16. package/dist/{bundle-DtCCCr4w.js → bundle-C6yEtMJ-.js} +53 -5
  17. package/dist/bundle-C6yEtMJ-.js.map +1 -0
  18. package/dist/bundle.d.ts +14 -0
  19. package/dist/{cloud-BpH0_bmV.js → cloud-BdnmqQaZ.js} +8528 -4342
  20. package/dist/cloud-BdnmqQaZ.js.map +1 -0
  21. package/dist/collections-dir-DlvDhime.js +69 -0
  22. package/dist/collections-dir-DlvDhime.js.map +1 -0
  23. package/dist/commands/agent-setup.d.ts +58 -0
  24. package/dist/commands/api-keys.d.ts +13 -0
  25. package/dist/commands/cloud/activity.d.ts +25 -0
  26. package/dist/commands/cloud/app-key.d.ts +18 -0
  27. package/dist/commands/cloud/auth.d.ts +1 -0
  28. package/dist/commands/cloud/billing-invoices.d.ts +39 -0
  29. package/dist/commands/cloud/claim.d.ts +7 -0
  30. package/dist/commands/cloud/context.d.ts +115 -6
  31. package/dist/commands/cloud/deploy-summary.d.ts +162 -0
  32. package/dist/commands/cloud/deploy.d.ts +64 -0
  33. package/dist/commands/cloud/env.d.ts +24 -0
  34. package/dist/commands/cloud/index.d.ts +13 -1
  35. package/dist/commands/cloud/init.d.ts +143 -0
  36. package/dist/commands/cloud/login-flow.d.ts +51 -0
  37. package/dist/commands/cloud/notifications.d.ts +28 -0
  38. package/dist/commands/cloud/orgs.d.ts +13 -0
  39. package/dist/commands/cloud/previews.d.ts +123 -0
  40. package/dist/commands/cloud/resources.d.ts +68 -14
  41. package/dist/commands/cloud/runtime-logs.d.ts +176 -0
  42. package/dist/commands/cloud/service-key.d.ts +15 -0
  43. package/dist/commands/cloud/token-capabilities.d.ts +61 -8
  44. package/dist/commands/cloud/tokens.d.ts +18 -3
  45. package/dist/commands/cloud/usage.d.ts +63 -0
  46. package/dist/commands/dev.d.ts +22 -0
  47. package/dist/commands/doctor.d.ts +1 -1
  48. package/dist/commands/generate-view.d.ts +94 -0
  49. package/dist/commands/generate_sdk.d.ts +19 -2
  50. package/dist/commands/init.d.ts +20 -0
  51. package/dist/commands/skills.d.ts +4 -3
  52. package/dist/commands/start.d.ts +10 -0
  53. package/dist/commands/storage.d.ts +4 -0
  54. package/dist/commands/upgrade.d.ts +12 -0
  55. package/dist/commands/verify.d.ts +96 -0
  56. package/dist/{consent-ClRHmcxf.js → consent-BD7F29T3.js} +2 -2
  57. package/dist/{consent-ClRHmcxf.js.map → consent-BD7F29T3.js.map} +1 -1
  58. package/dist/{console-CEGm0XNc.js → console-BXB6-8GT.js} +12 -6
  59. package/dist/console-BXB6-8GT.js.map +1 -0
  60. package/dist/{context-CyflUrKg.js → context-GUxkZm-S.js} +482 -26
  61. package/dist/context-GUxkZm-S.js.map +1 -0
  62. package/dist/{daemon-CknkDjd6.js → daemon-Cp7oNXth.js} +160 -5
  63. package/dist/daemon-Cp7oNXth.js.map +1 -0
  64. package/dist/{daemon-entry-CbLRrgzy.js → daemon-entry-zOC1revO.js} +6 -3
  65. package/dist/daemon-entry-zOC1revO.js.map +1 -0
  66. package/dist/{db-CRNpA5mH.js → db-KzlqddGD.js} +101 -54
  67. package/dist/db-KzlqddGD.js.map +1 -0
  68. package/dist/{derive-CsoFGAnK.js → derive-ae9UOoOB.js} +2 -2
  69. package/dist/{derive-CsoFGAnK.js.map → derive-ae9UOoOB.js.map} +1 -1
  70. package/dist/{dev-C0pbMmhS.js → dev-DTqVMgB3.js} +231 -44
  71. package/dist/dev-DTqVMgB3.js.map +1 -0
  72. package/dist/dev-db/daemon.d.ts +41 -0
  73. package/dist/dev-db/pull.d.ts +33 -5
  74. package/dist/dev-db/state.d.ts +9 -0
  75. package/dist/{dev-preflight-unHpiYO1.js → dev-preflight-Cxv3TiD1.js} +73 -27
  76. package/dist/dev-preflight-Cxv3TiD1.js.map +1 -0
  77. package/dist/{dev-server-B1UYifZJ.js → dev-server-OJsUGZEB.js} +14 -3
  78. package/dist/dev-server-OJsUGZEB.js.map +1 -0
  79. package/dist/{doctor-CATRdWm6.js → doctor-BRWOlqeG.js} +14 -12
  80. package/dist/doctor-BRWOlqeG.js.map +1 -0
  81. package/dist/{eject-DuasTr-F.js → eject-DABcDnPN.js} +3 -4
  82. package/dist/{eject-DuasTr-F.js.map → eject-DABcDnPN.js.map} +1 -1
  83. package/dist/{fold-static-hDHtDfTq.js → fold-static-BnAK-anQ.js} +3 -3
  84. package/dist/{fold-static-hDHtDfTq.js.map → fold-static-BnAK-anQ.js.map} +1 -1
  85. package/dist/generate-view-IFwCADvb.js +662 -0
  86. package/dist/generate-view-IFwCADvb.js.map +1 -0
  87. package/dist/{generate_sdk-Cvg5jjJF.js → generate_sdk-BvcWvoUh.js} +49 -13
  88. package/dist/generate_sdk-BvcWvoUh.js.map +1 -0
  89. package/dist/index.es.js +58 -40
  90. package/dist/index.es.js.map +1 -1
  91. package/dist/{init-BWAwHPtz.js → init-CaU6GhwI.js} +50 -62
  92. package/dist/init-CaU6GhwI.js.map +1 -0
  93. package/dist/invoked-command-CG_rIa_o.js +55 -0
  94. package/dist/invoked-command-CG_rIa_o.js.map +1 -0
  95. package/dist/last-dev-database-DpW5dfoX.js +2 -0
  96. package/dist/{manifest-DRp0UVTj.js → manifest-BtzDy7KQ.js} +36 -3
  97. package/dist/{manifest-DRp0UVTj.js.map → manifest-BtzDy7KQ.js.map} +1 -1
  98. package/dist/{normalize-imports-BoBVh5tU.js → normalize-imports-D0zXlM6g.js} +3 -3
  99. package/dist/{normalize-imports-BoBVh5tU.js.map → normalize-imports-D0zXlM6g.js.map} +1 -1
  100. package/dist/{path-flags-BFgG9V6y.js → path-flags-DNvtEi2-.js} +5 -4
  101. package/dist/path-flags-DNvtEi2-.js.map +1 -0
  102. package/dist/{prepare-DdnU70z8.js → prepare-CTw9NEkh.js} +5 -4
  103. package/dist/{prepare-DdnU70z8.js.map → prepare-CTw9NEkh.js.map} +1 -1
  104. package/dist/project-CasK56vN.js +701 -0
  105. package/dist/project-CasK56vN.js.map +1 -0
  106. package/dist/{pull-C3PXduzl.js → pull-DDMpsZ5r.js} +131 -24
  107. package/dist/pull-DDMpsZ5r.js.map +1 -0
  108. package/dist/refusal-ReeeGP8a.js +26 -0
  109. package/dist/refusal-ReeeGP8a.js.map +1 -0
  110. package/dist/resolve-D647F1LA.js +2 -0
  111. package/dist/{resources-BdNRDEAy.js → resources-CPSC5Kcu.js} +4 -5
  112. package/dist/{resources-BdNRDEAy.js.map → resources-CPSC5Kcu.js.map} +1 -1
  113. package/dist/{schema-B0-p6T1O.js → schema-BSXwZSiI.js} +9 -8
  114. package/dist/schema-BSXwZSiI.js.map +1 -0
  115. package/dist/{skills-DfnTeyRz.js → skills-BU2flMOy.js} +52 -8
  116. package/dist/skills-BU2flMOy.js.map +1 -0
  117. package/dist/{start-BmEZkS0n.js → start-mVb6upwY.js} +20 -7
  118. package/dist/start-mVb6upwY.js.map +1 -0
  119. package/dist/{state-CCB-FAQ9.js → state-CYdBvnwA.js} +3 -2
  120. package/dist/state-CYdBvnwA.js.map +1 -0
  121. package/dist/static-syntax-check.d.ts +64 -0
  122. package/dist/{status-BJ26yZOo.js → status-BREvtzJm.js} +8 -9
  123. package/dist/{status-BJ26yZOo.js.map → status-BREvtzJm.js.map} +1 -1
  124. package/dist/{storage-DKPUBTWG.js → storage-DtOXGflp.js} +159 -16
  125. package/dist/storage-DtOXGflp.js.map +1 -0
  126. package/dist/{telemetry-EMFRVRQi.js → telemetry-CgwJPVMO.js} +2 -2
  127. package/dist/{telemetry-EMFRVRQi.js.map → telemetry-CgwJPVMO.js.map} +1 -1
  128. package/dist/{telemetry-m9czTNGR.js → telemetry-DwK5RQJl.js} +4 -4
  129. package/dist/{telemetry-m9czTNGR.js.map → telemetry-DwK5RQJl.js.map} +1 -1
  130. package/dist/{upgrade-DjihWuZL.js → upgrade-B7sVwL8S.js} +26 -4
  131. package/dist/{upgrade-DjihWuZL.js.map → upgrade-B7sVwL8S.js.map} +1 -1
  132. package/dist/utils/args.d.ts +32 -3
  133. package/dist/utils/boot-retry.d.ts +41 -0
  134. package/dist/utils/collections-dir.d.ts +14 -0
  135. package/dist/utils/dev-preflight.d.ts +34 -1
  136. package/dist/utils/dev-server.d.ts +11 -0
  137. package/dist/utils/path-flags.d.ts +2 -1
  138. package/dist/utils/project.d.ts +5 -1
  139. package/dist/utils/tool-stdio.d.ts +1 -1
  140. package/dist/utils/unknown-command.d.ts +4 -0
  141. package/dist/verify-D7UsV_qe.js +730 -0
  142. package/dist/verify-D7UsV_qe.js.map +1 -0
  143. package/package.json +9 -7
  144. package/templates/eject/backend/src/index.ts +9 -1
  145. package/templates/generated-schemas/ecommerce.ts +3 -0
  146. package/templates/overlays/baas/ai-instructions.md +13 -0
  147. package/templates/resource-graphs/blank.json +25 -0
  148. package/templates/resource-graphs/blog.json +28 -0
  149. package/templates/resource-graphs/ecommerce.json +28 -0
  150. package/templates/resource-graphs/headless.json +22 -0
  151. package/templates/template/.claude/hooks/post-edit-collection.sh +99 -0
  152. package/templates/template/.claude/settings.json +17 -0
  153. package/templates/template/.env.example +15 -5
  154. package/templates/template/ai-instructions.md +21 -1
  155. package/templates/template/config/collections/presets/ecommerce/index.ts +23 -0
  156. package/templates/template/docker-compose.yml +4 -1
  157. package/templates/template/frontend/package.json +1 -0
  158. package/templates/template/frontend/src/App.tsx +10 -9
  159. package/templates/views/AppView.tsx.tmpl +138 -0
  160. package/templates/views/EntityView.tsx.tmpl +64 -0
  161. package/templates/views/index.ts.tmpl +8 -0
  162. package/dist/agent-setup-B5AKHOgt.js.map +0 -1
  163. package/dist/api-keys-Tm7zvAPe.js.map +0 -1
  164. package/dist/args-BX0YD14a.js +0 -266
  165. package/dist/args-BX0YD14a.js.map +0 -1
  166. package/dist/auth-Vl2hFKXP.js.map +0 -1
  167. package/dist/bundle-DtCCCr4w.js.map +0 -1
  168. package/dist/cloud-BpH0_bmV.js.map +0 -1
  169. package/dist/console-CEGm0XNc.js.map +0 -1
  170. package/dist/context-CyflUrKg.js.map +0 -1
  171. package/dist/daemon-CknkDjd6.js.map +0 -1
  172. package/dist/daemon-entry-CbLRrgzy.js.map +0 -1
  173. package/dist/db-CRNpA5mH.js.map +0 -1
  174. package/dist/dev-C0pbMmhS.js.map +0 -1
  175. package/dist/dev-preflight-unHpiYO1.js.map +0 -1
  176. package/dist/dev-server-B1UYifZJ.js.map +0 -1
  177. package/dist/doctor-CATRdWm6.js.map +0 -1
  178. package/dist/generate_sdk-Cvg5jjJF.js.map +0 -1
  179. package/dist/init-BWAwHPtz.js.map +0 -1
  180. package/dist/last-dev-database-c_dKz1S3.js +0 -2
  181. package/dist/path-flags-BFgG9V6y.js.map +0 -1
  182. package/dist/project-Wp2zoyeN.js +0 -349
  183. package/dist/project-Wp2zoyeN.js.map +0 -1
  184. package/dist/pull-C3PXduzl.js.map +0 -1
  185. package/dist/resolve-CNQjsatH.js +0 -2
  186. package/dist/schema-B0-p6T1O.js.map +0 -1
  187. package/dist/skills-DfnTeyRz.js.map +0 -1
  188. package/dist/start-BmEZkS0n.js.map +0 -1
  189. package/dist/state-CCB-FAQ9.js.map +0 -1
  190. package/dist/storage-DKPUBTWG.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-BdnmqQaZ.js","names":[],"sources":["../src/commands/cloud/login-flow.ts","../src/commands/cloud/tokens.ts","../src/commands/cloud/auth.ts","../src/commands/cloud/link.ts","../src/commands/cloud/billing-invoices.ts","../src/commands/cloud/resources.ts","../src/commands/cloud/db-connect.ts","../src/commands/cloud/databases.ts","../src/commands/cloud/projects.ts","../src/commands/cloud/debug.ts","../src/commands/cloud/cron.ts","../src/commands/cloud/env.ts","../src/commands/cloud/init.ts","../src/commands/cloud/claim.ts","../src/commands/cloud/bundle-deploy.ts","../src/commands/cloud/deploy-summary.ts","../src/utils/temp-archive.ts","../src/commands/cloud/rebuild-source.ts","../src/commands/cloud/previews.ts","../src/commands/cloud/runtime-logs.ts","../src/static-syntax-check.ts","../src/commands/cloud/deploy.ts","../src/commands/cloud/orgs.ts","../src/commands/cloud/domains.ts","../src/commands/cloud/extensions.ts","../src/commands/cloud/settings.ts","../src/commands/cloud/deployments.ts","../src/commands/cloud/power.ts","../src/commands/cloud/usage.ts","../src/commands/cloud/app-key.ts","../src/commands/cloud/service-key.ts","../src/commands/cloud/activity.ts","../src/commands/cloud/notifications.ts","../src/commands/cloud/declared-resources.ts","../src/commands/cloud/action-help.ts","../src/commands/cloud/index.ts"],"sourcesContent":["/**\n * The two steps of `rebase cloud login` that are not a password: an emailed\n * sign-in code, and the second factor of an account with 2FA on.\n *\n * ## Why a code\n *\n * Every console account made through Google, GitHub or LinkedIn has no\n * password, so a password-only login could never sign it in — it answered\n * \"Invalid email or password\" to an account that has never had one. The\n * control plane mails a six-digit code (`POST /auth/otp`) when it can send\n * mail; the person types it here. A magic link would open the session in the\n * browser that has the mail, not in this terminal, which is why it is a code.\n *\n * ## Why the second factor is handled on every path\n *\n * The server gates every way of minting a session — password, code, provider —\n * behind the account's verified factors, answering `401 MFA_REQUIRED` with a\n * five-minute token that only the two challenge routes accept. A CLI that does\n * not know that reads the 401 as \"wrong password\", which for an account with\n * 2FA is both false and a dead end.\n *\n * Both steps need a person at a terminal. Without one they refuse with the\n * route that does not: an access token in `REBASE_TOKEN`.\n */\nimport inquirer from \"inquirer\";\nimport {\n fail,\n isJsonMode,\n note,\n warn,\n TOKEN_ENV,\n type CloudClient\n} from \"./context\";\n\ntype CloudAuth = CloudClient[\"auth\"];\ntype SignedIn = Awaited<ReturnType<CloudAuth[\"signInWithEmail\"]>>;\n\n/** How many codes one login takes before it gives up. The server limits verification per address too. */\nexport const CODE_ATTEMPTS = 3;\n\n/**\n * The remedy for a step that needs a terminal when there is none: a token,\n * which needs neither a password nor a code. Minted in the console because a\n * person who cannot log in to the CLI cannot run `rebase cloud tokens create`.\n */\nexport const TOKEN_REMEDY =\n `Create an access token in the console (Settings → Access tokens) and set ${TOKEN_ENV} to it.`;\n\n/** What the password refusal adds, for the accounts that never had a password. */\nexport const NO_PASSWORD_HINT =\n `Signed up with Google or GitHub? Run \\`rebase cloud login --code\\`, or ${TOKEN_REMEDY.charAt(0).toLowerCase()}${TOKEN_REMEDY.slice(1)}`;\n\nfunction atTerminal(): boolean {\n return !isJsonMode() && process.stdin.isTTY === true;\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === \"object\" && error !== null && \"code\" in error ? error.code : undefined;\n}\n\nfunction errorStatus(error: unknown): unknown {\n return typeof error === \"object\" && error !== null && \"status\" in error ? error.status : undefined;\n}\n\n/** A sign-in waiting for its second factor. */\nexport interface PendingSecondFactor {\n mfaToken: string;\n factors: Array<{ id: string; factorType: string; friendlyName?: string }>;\n}\n\n/**\n * The pending sign-in an `MFA_REQUIRED` refusal describes, or `null` for any\n * other error — including one with no token or no factor, which no code step\n * could finish. The same reading the console's login view makes.\n */\nexport function readMfaRequired(error: unknown): PendingSecondFactor | null {\n if (errorCode(error) !== \"MFA_REQUIRED\") return null;\n const details = typeof error === \"object\" && error !== null && \"details\" in error ? error.details : undefined;\n if (typeof details !== \"object\" || details === null) return null;\n const mfaToken = \"mfaToken\" in details ? details.mfaToken : undefined;\n const rawFactors = \"factors\" in details && Array.isArray(details.factors) ? details.factors : [];\n const factors = rawFactors.flatMap((f: unknown) => {\n if (typeof f !== \"object\" || f === null) return [];\n const id = \"id\" in f ? f.id : undefined;\n const factorType = \"factorType\" in f ? f.factorType : undefined;\n const friendlyName = \"friendlyName\" in f && typeof f.friendlyName === \"string\" ? f.friendlyName : undefined;\n return typeof id === \"string\" && id && typeof factorType === \"string\"\n ? [{ id, factorType, friendlyName }]\n : [];\n });\n if (typeof mfaToken !== \"string\" || !mfaToken || factors.length === 0) return null;\n return { mfaToken, factors };\n}\n\n/**\n * Whether the control plane mails sign-in codes, as its `/auth/config` says.\n * `false` when it cannot be asked: an older control plane has no such door,\n * and offering one that 404s is worse than not offering it.\n */\nexport async function offersSignInCodes(auth: CloudAuth): Promise<boolean> {\n try {\n return (await auth.getAuthConfig()).emailOtp === true;\n } catch {\n return false;\n }\n}\n\n/** Ask \"password or code?\" at a terminal. */\nexport async function askSignInMethod(): Promise<\"password\" | \"code\"> {\n const { method } = await inquirer.prompt([{\n type: \"list\",\n name: \"method\",\n message: \"Sign in with:\",\n choices: [\n { name: \"Password\", value: \"password\" },\n { name: \"Email me a code (for accounts made with Google, GitHub or LinkedIn)\", value: \"code\" }\n ]\n }]);\n return method === \"code\" ? \"code\" : \"password\";\n}\n\n/** Refuse a code step with no terminal to type it at. Never returns when there is none. */\nexport function requireTerminalForCode(): void {\n if (atTerminal()) return;\n fail(\n \"A sign-in code is typed at a terminal, and there is none.\",\n TOKEN_REMEDY,\n \"input_required\"\n );\n}\n\n/**\n * Mail a code to `email` and trade what the person types for a session.\n *\n * Throws what `verifyEmailOtp` throws for anything but a wrong code —\n * `MFA_REQUIRED` included, which the caller's {@link withSecondFactor} answers.\n */\nexport async function signInWithCode(auth: CloudAuth, email: string): Promise<SignedIn> {\n requireTerminalForCode();\n try {\n await auth.sendEmailOtp(email);\n } catch (e) {\n const code = errorCode(e);\n if (code === \"EMAIL_NOT_CONFIGURED\" || errorStatus(e) === 404) {\n fail(\n \"This control plane does not send sign-in codes.\",\n `Sign in with your password, or: ${TOKEN_REMEDY}`,\n \"otp_unavailable\"\n );\n }\n throw e;\n }\n // The server answers the same for an address with no account, on purpose:\n // it will not say which addresses are customers. Neither does this.\n note(`If ${email} has a Rebase Cloud account, a 6-digit code is on its way. It expires in 10 minutes.`);\n\n for (let attempt = 1; attempt <= CODE_ATTEMPTS; attempt++) {\n const { code } = await inquirer.prompt([{\n type: \"input\",\n name: \"code\",\n message: \"Code from the email:\",\n validate: (value: string) => /^\\d{6}$/.test(value.replace(/\\s+/g, \"\")) || \"The code is six digits.\"\n }]);\n try {\n return await auth.verifyEmailOtp(email, String(code).replace(/\\s+/g, \"\"));\n } catch (e) {\n if (errorCode(e) !== \"INVALID_CODE\") throw e;\n if (attempt < CODE_ATTEMPTS) warn(\"That code is not right, or it has expired.\", \"Check the newest email and try again.\");\n }\n }\n fail(\n \"That code was not accepted.\",\n \"Run `rebase cloud login --code` again for a new one.\",\n \"invalid_code\"\n );\n}\n\n/**\n * Run a sign-in, and when the account has 2FA on, ask for the second factor\n * and finish it there.\n */\nexport async function withSecondFactor(auth: CloudAuth, signIn: () => Promise<SignedIn>): Promise<SignedIn> {\n try {\n return await signIn();\n } catch (e) {\n const pending = readMfaRequired(e);\n if (!pending) throw e;\n return answerSecondFactor(auth, pending);\n }\n}\n\nasync function answerSecondFactor(auth: CloudAuth, pending: PendingSecondFactor): Promise<SignedIn> {\n if (!atTerminal()) {\n fail(\n \"This account has two-factor authentication on, and there is no terminal to ask for the code on.\",\n TOKEN_REMEDY,\n \"mfa_required\"\n );\n }\n note(\"Two-factor authentication is on for this account.\");\n\n let factorId = pending.factors[0].id;\n if (pending.factors.length > 1) {\n ({ factorId } = await inquirer.prompt([{\n type: \"list\",\n name: \"factorId\",\n message: \"Verify with:\",\n choices: pending.factors.map(f => ({ name: f.friendlyName || f.factorType, value: f.id }))\n }]));\n }\n\n const options = { mfaToken: pending.mfaToken };\n let challengeId: string | undefined;\n for (let attempt = 1; attempt <= CODE_ATTEMPTS; attempt++) {\n try {\n challengeId ??= (await auth.mfa.challenge(factorId, options)).challengeId;\n const { code } = await inquirer.prompt([{\n type: \"input\",\n name: \"code\",\n message: \"Code from your authenticator app (or a recovery code):\",\n validate: (value: string) => value.trim() !== \"\" || \"Enter the code.\"\n }]);\n return await auth.mfa.verifyChallenge(challengeId, String(code).replace(/\\s+/g, \"\"), options);\n } catch (e) {\n const code = errorCode(e);\n if (code === \"INVALID_CODE\") {\n if (attempt < CODE_ATTEMPTS) warn(\"That code is not right.\");\n continue;\n }\n if (code === \"CHALLENGE_EXHAUSTED\") {\n // The challenge has had its attempts; the next code needs a new one.\n challengeId = undefined;\n continue;\n }\n if (code === \"INVALID_CHALLENGE\" || code === \"SESSION_REVOKED\" || errorStatus(e) === 401) {\n // The pending token lasts five minutes from the first factor.\n fail(\"The sign-in timed out before the second factor was entered.\", \"Run `rebase cloud login` again.\", \"mfa_expired\");\n }\n throw e;\n }\n }\n fail(\n \"The two-factor code was not accepted.\",\n \"Run `rebase cloud login` again, or use one of your recovery codes.\",\n \"mfa_failed\"\n );\n}\n","/**\n * `rebase cloud tokens` — API tokens for CI and agents.\n *\n * A token is a personal API key on the control plane (`/api/auth/keys`): it\n * acts as the account that created it, holds only the scopes it was minted\n * with, and never more than that account can do at the moment it is used. With\n * `REBASE_TOKEN` set, every `rebase cloud` command authenticates with it\n * instead of the `cloud login` session — see `requireClient`.\n *\n * What a token may do is asked for as capabilities (`--can deploy,logs`) on one\n * project, and turned into scopes by `token-capabilities.ts`, the map the\n * console reads too. Three capabilities act on one organization instead —\n * `billing`, `audit`, `notifications` — and are given only when `--can` names\n * them: on `--org`, else the project's organization, else the selected one.\n *\n * Managing tokens takes the signed-in session, never a token: the control\n * plane refuses every key on these routes, because a key that could mint keys\n * could mint its own successor.\n */\nimport chalk from \"chalk\";\nimport type arg from \"arg\";\nimport type { ApiKeyMasked, ApiKeyWithSecret } from \"@rebasepro/types\";\nimport {\n ALWAYS_SCOPES,\n capabilitiesInScopes,\n isOrgCapability,\n isTokenCapability,\n ORG_CAPABILITY_NAMES,\n orgCapabilitiesInScopes,\n scopesForCapabilities,\n scopesForOrgCapabilities,\n TOKEN_CAPABILITY_NAMES,\n type OrgCapability,\n type TokenCapability\n} from \"./token-capabilities\";\nimport {\n confirmDestructive,\n displayProjectRef,\n emit,\n fail,\n getContextOrg,\n keyValues,\n parseCloudArgs,\n reportError,\n requireKnownAction,\n requireProject,\n requireSessionClient,\n success,\n TOKEN_ENV,\n type CloudClient\n} from \"./context\";\n\n/** Every action the group dispatches. */\nexport const TOKENS_ACTIONS = [\"list\", \"create\", \"revoke\"] as const;\n\n/** What `rebase cloud tokens create` parses, beside the global flags (`--project` among them). */\nexport const CREATE_TOKEN_FLAGS = {\n \"--can\": [String],\n \"--name\": String,\n \"--expires-in\": String,\n \"--org\": String\n} satisfies arg.Spec;\n\nexport async function tokensCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n requireKnownAction(\"tokens\", action, TOKENS_ACTIONS);\n switch (action ?? \"list\") {\n case \"create\":\n await createToken(rawArgs);\n break;\n case \"revoke\":\n await revokeToken(rawArgs);\n break;\n default:\n await listTokens(rawArgs);\n }\n}\n\n/* ─── create ───────────────────────────────────────────────────── */\n\nconst DAY_MS = 86_400_000;\n\n/** Every word `--can` takes, project capabilities first. */\nconst CAN_WORDS = [...TOKEN_CAPABILITY_NAMES, ...ORG_CAPABILITY_NAMES].join(\", \");\n\n/** What `--can` names: capabilities on one project, and on one organization. */\nexport interface RequestedCapabilities {\n project: TokenCapability[];\n org: OrgCapability[];\n}\n\n/**\n * The capabilities `--can` names, comma-separated or repeated, each once —\n * split into the project's and the organization's.\n *\n * Exported so its tests can drive it without a session.\n */\nexport function parseCapabilities(values: readonly string[] | undefined): RequestedCapabilities {\n const words = [...new Set((values ?? []).flatMap(value => value.split(/[\\s,]+/)).filter(Boolean))];\n if (words.length === 0) {\n fail(\n \"Say what the token may do: --can deploy,logs.\",\n `Capabilities: ${CAN_WORDS}.`,\n \"usage\"\n );\n }\n const unknown = words.filter(word => !isTokenCapability(word) && !isOrgCapability(word));\n if (unknown.length > 0) {\n fail(\n `--can takes capabilities, and ${unknown.map(word => `\"${word}\"`).join(\", \")} is not one.`,\n `Capabilities: ${CAN_WORDS}.`,\n \"usage\"\n );\n }\n return { project: words.filter(isTokenCapability), org: words.filter(isOrgCapability) };\n}\n\n/** The organization a project belongs to, or undefined when its row does not say. */\nasync function projectOrganization(client: CloudClient, projectId: string): Promise<string | undefined> {\n try {\n const row = (await client.data.collection(\"projects\").findById(projectId)) as Record<string, unknown> | undefined;\n const raw = row?.organization ?? row?.organizationId ?? row?.organization_id;\n if (raw && typeof raw === \"object\" && \"id\" in raw) return String((raw as { id: unknown }).id);\n return raw == null || raw === \"\" ? undefined : String(raw);\n } catch {\n return undefined;\n }\n}\n\n/**\n * `--expires-in <days>` as an ISO timestamp, or null for a token that does not\n * expire.\n *\n * Exported so its tests can drive it without a session.\n */\nexport function resolveTokenExpiry(value: string | undefined, now: Date = new Date()): string | null {\n if (value === undefined) return null;\n const days = /^\\d+$/.test(value.trim()) ? Number(value.trim()) : NaN;\n if (!Number.isSafeInteger(days) || days < 1) {\n fail(`--expires-in takes a whole number of days, e.g. --expires-in 90 (got \"${value}\").`, undefined, \"usage\");\n }\n return new Date(now.getTime() + days * DAY_MS).toISOString();\n}\n\nasync function createToken(rawArgs: string[]): Promise<void> {\n const { flags } = parseCloudArgs({\n spec: CREATE_TOKEN_FLAGS,\n rawArgs,\n commandWords: 3, // cloud tokens create\n command: \"cloud tokens create\",\n maxPositionals: 0\n });\n // Both refused before the session is asked for: an unusable line is\n // unusable whoever is signed in.\n const { project: capabilities, org: orgCapabilities } = parseCapabilities(flags[\"--can\"]);\n const expiresAt = resolveTokenExpiry(flags[\"--expires-in\"]);\n\n const { client, url } = await requireSessionClient(rawArgs);\n // A project only when a project capability asks for one: a token for an\n // organization's billing alone needs none.\n const projectId = capabilities.length > 0 ? await requireProject(rawArgs, client) : undefined;\n const projectRef = projectId ? displayProjectRef(rawArgs) || projectId : undefined;\n // The organization: --org, else the project's own, else the selected one.\n let organizationId: string | undefined;\n if (orgCapabilities.length > 0) {\n organizationId = flags[\"--org\"]?.trim()\n || (projectId ? await projectOrganization(client, projectId) : undefined)\n || getContextOrg(url);\n if (!organizationId) {\n fail(\n `Say which organization ${orgCapabilities.join(\", \")} ${orgCapabilities.length === 1 ? \"is\" : \"are\"} for.`,\n \"Pass --org <id>, or select one with `rebase cloud use`.\",\n \"no_org\"\n );\n }\n }\n const reach = projectRef ?? `org ${organizationId}`;\n const name = flags[\"--name\"]?.trim() || `${reach} ${[...capabilities, ...orgCapabilities].join(\"+\")}`;\n const scopes = [...new Set([\n ...(projectId ? scopesForCapabilities(projectId, capabilities) : ALWAYS_SCOPES),\n ...(organizationId ? scopesForOrgCapabilities(organizationId, orgCapabilities) : [])\n ])];\n\n let created: ApiKeyWithSecret;\n try {\n ({ key: created } = await client.personalKeys.createKey({ name, scopes, expires_at: expiresAt }));\n } catch (e) {\n reportError(e, \"Failed to create the token\");\n }\n\n success(`Token created: ${chalk.bold(created.name)}`);\n emit(\n () => {\n keyValues([\n [\"ID\", created.id],\n [\"Project\", !projectId ? undefined : projectRef === projectId ? projectId : `${projectRef} (${projectId})`],\n [\"Organization\", organizationId],\n [\"Can\", [...capabilities, ...orgCapabilities].join(\", \")],\n [\"Expires\", created.expires_at ? new Date(created.expires_at).toLocaleDateString() : \"never\"]\n ]);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy it now — it is not shown again:\"));\n console.log(\"\");\n console.log(` export ${TOKEN_ENV}=${chalk.cyan(created.key)}`);\n console.log(\"\");\n console.log(chalk.gray(` With ${TOKEN_ENV} set, every \\`rebase cloud\\` command uses the token instead of your login.`));\n console.log(chalk.gray(\" In CI, store it as a secret and expose it under that name.\"));\n console.log(\"\");\n },\n {\n success: true,\n id: created.id,\n name: created.name,\n token: created.key,\n env: TOKEN_ENV,\n projectId: projectId ?? null,\n capabilities,\n organizationId: organizationId ?? null,\n orgCapabilities,\n scopes: created.scopes,\n expiresAt: created.expires_at\n }\n );\n}\n\n/* ─── list ─────────────────────────────────────────────────────── */\n\nfunction tokenStatus(key: ApiKeyMasked, now: Date): \"revoked\" | \"expired\" | \"active\" {\n if (key.revoked_at) return \"revoked\";\n if (key.expires_at && new Date(key.expires_at) < now) return \"expired\";\n return \"active\";\n}\n\n/**\n * What a token was created for, read back from its scopes:\n * `deploy, logs on proj_1; billing on organization org_1`. Undefined when no\n * capability explains them.\n *\n * Exported for `whoami`, which reads a token back the same way.\n */\nexport function describeGrants(scopes: readonly string[]): string | undefined {\n const parts = [\n ...capabilitiesInScopes(scopes)\n .filter(grant => grant.capabilities.length > 0)\n .map(grant => `${grant.capabilities.join(\", \")} on ${grant.projectId}`),\n ...orgCapabilitiesInScopes(scopes)\n .filter(grant => grant.capabilities.length > 0)\n .map(grant => `${grant.capabilities.join(\", \")} on organization ${grant.organizationId}`)\n ];\n return parts.length > 0 ? parts.join(\"; \") : undefined;\n}\n\nfunction describeGrant(scopes: readonly string[]): string {\n return describeGrants(scopes) ?? `${scopes.length} scope${scopes.length === 1 ? \"\" : \"s\"}`;\n}\n\nasync function listTokens(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {}, rawArgs, commandWords: 3, command: \"cloud tokens list\", maxPositionals: 0 });\n const { client } = await requireSessionClient(rawArgs);\n\n let keys: ApiKeyMasked[];\n try {\n ({ keys } = await client.personalKeys.listKeys());\n } catch (e) {\n reportError(e, \"Failed to list tokens\");\n }\n\n const now = new Date();\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Tokens\"));\n console.log(\"\");\n if (keys.length === 0) {\n console.log(chalk.gray(\" None yet. Create one with `rebase cloud tokens create --can deploy`.\"));\n console.log(\"\");\n return;\n }\n for (const key of keys) {\n const status = tokenStatus(key, now);\n const colored = status === \"active\" ? chalk.green(status) : status === \"expired\" ? chalk.yellow(status) : chalk.red(status);\n console.log(` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${colored}`);\n keyValues([\n [\"ID\", key.id],\n [\"Can\", describeGrant(key.scopes)],\n [\"Expires\", key.expires_at ? new Date(key.expires_at).toLocaleDateString() : \"never\"],\n [\"Last used\", key.last_used_at ? new Date(key.last_used_at).toLocaleString() : \"never\"]\n ]);\n console.log(\"\");\n }\n },\n {\n tokens: keys.map(key => ({\n id: key.id,\n name: key.name,\n prefix: key.key_prefix,\n status: tokenStatus(key, now),\n grants: capabilitiesInScopes(key.scopes),\n orgGrants: orgCapabilitiesInScopes(key.scopes),\n scopes: key.scopes,\n expiresAt: key.expires_at,\n lastUsedAt: key.last_used_at,\n createdAt: key.created_at\n }))\n }\n );\n}\n\n/* ─── revoke ───────────────────────────────────────────────────── */\n\nasync function revokeToken(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud tokens revoke\n command: \"cloud tokens revoke\",\n maxPositionals: 1\n });\n const id = positionals[0];\n if (!id) fail(\"Usage: rebase cloud tokens revoke <id>\", \"`rebase cloud tokens list` shows the ids.\", \"usage\");\n\n const { client } = await requireSessionClient(rawArgs);\n await confirmDestructive({\n yes: Boolean(flags[\"--yes\"]),\n prompt: `Revoke token ${id}? Anything using it stops working.`\n });\n\n try {\n await client.personalKeys.revokeKey(id);\n } catch (e) {\n reportError(e, \"Failed to revoke the token\");\n }\n\n success(`Token ${chalk.bold(id)} revoked`);\n emit(() => {}, { success: true, id });\n}\n","/**\n * `rebase cloud` auth subcommands: login, logout, whoami.\n */\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport { NO_PASSWORD_HINT, askSignInMethod, offersSignInCodes, requireTerminalForCode, signInWithCode, withSecondFactor } from \"./login-flow\";\nimport {\n resolveCloudUrl,\n resolveCloudTarget,\n isKnownControlPlane,\n isJsonMode,\n refuseDirectLink,\n parseCloudArgs,\n createCloudClient,\n requireClient,\n setCurrentContext,\n setContextOrg,\n getContextOrg,\n readLink,\n success,\n fail,\n keyValues,\n reportError,\n emit,\n note,\n noteBlank,\n warn,\n requireInteractive,\n envToken,\n linkedEphemeralGrant,\n grantProjectOf,\n appKeyExpiryNote,\n projectDotenvSetsAppKey,\n TOKEN_ENV,\n type CloudClient,\n type EphemeralGrant\n} from \"./context\";\nimport { capabilitiesInScopes, orgCapabilitiesInScopes } from \"./token-capabilities\";\nimport { describeGrants } from \"./tokens\";\n\n/**\n * Every flag `rebase cloud login` accepts.\n *\n * Hoisted out of the `arg` call so one declaration serves the parser,\n * `action-help.ts`'s page for this command, and the test that holds the two to\n * each other — the same arrangement `DEPLOY_FLAGS` and `CREATE_PROJECT_FLAGS`\n * already use.\n */\nexport const LOGIN_FLAGS = {\n \"--email\": String,\n \"--password\": String,\n \"--code\": Boolean,\n \"-e\": \"--email\"\n} as const;\n\n/**\n * Where credentials may come from, in the order this command prefers them.\n *\n * The environment is the non-interactive route, and it exists so `--password`\n * does not have to be. A password written as an argument is in the shell's\n * history file and in the process table for as long as the command runs, and\n * neither is something this CLI can redact after the fact — the same reasoning\n * `rls-check` states for its connection string, which carries one too.\n *\n * CI should not need a password at all: `rebase cloud tokens create` mints a\n * token narrowed to one project, and `REBASE_TOKEN` hands it to every cloud\n * command. Where a login is still wanted, `REBASE_CLOUD_PASSWORD` is how a\n * secret store hands the password over without it appearing on a command line.\n */\nexport const PASSWORD_ENV = \"REBASE_CLOUD_PASSWORD\";\nexport const EMAIL_ENV = \"REBASE_CLOUD_EMAIL\";\n\n/**\n * Whether this line put a password in the shell's history.\n *\n * Exported for its test: the warning is the whole feature, so \"it warns exactly\n * when the flag was used\" is the thing worth pinning.\n */\nexport function passwordOnTheCommandLine(args: { \"--password\"?: string }): boolean {\n return typeof args[\"--password\"] === \"string\" && args[\"--password\"] !== \"\";\n}\n\nexport async function loginCommand(rawArgs: string[]): Promise<void> {\n // Strictly, through the family's own parser. `arg(…, { permissive: true })`\n // dropped an undeclared flag on the floor, so `rebase cloud login --emial\n // me@example.com` prompted for an email as though nothing had been typed.\n const { flags: args } = parseCloudArgs({\n spec: LOGIN_FLAGS,\n rawArgs,\n commandWords: 2, // cloud login\n command: \"cloud login\",\n maxPositionals: 0\n });\n // `login` builds its own client, so it does not pass through\n // `requireClient`'s guard — and it is the one command where getting this\n // wrong sends a password somewhere it should never go.\n refuseDirectLink(rawArgs);\n const { url, source } = resolveCloudTarget(rawArgs);\n if (source === \"link\" && !isKnownControlPlane(url)) await confirmLinkedControlPlane(url);\n\n noteBlank();\n note(`Signing in to ${chalk.cyan(url)}`);\n noteBlank();\n\n if (args[\"--code\"] && passwordOnTheCommandLine(args)) {\n fail(\"--code and --password are two ways to sign in. Pass one of them.\", undefined, \"usage\");\n }\n\n // Once, and before the request: by the time this succeeds the password is\n // already in the history file, and a warning after the fact is advice about\n // something that has happened.\n if (passwordOnTheCommandLine(args)) {\n warn(\n \"--password puts your password in your shell history and in the process table.\",\n `Prefer the prompt, or pass it as ${PASSWORD_ENV} from a secret store.`\n );\n }\n\n const envEmail = (process.env[EMAIL_ENV] ?? \"\").trim();\n const envPassword = process.env[PASSWORD_ENV] ?? \"\";\n\n // Which way in. `--code` asks for an emailed code; a password from the flag\n // or the environment is a choice already made; otherwise a terminal is\n // asked, and offered a code only when this control plane mails them.\n // Accounts made with Google, GitHub or LinkedIn have no password, so for\n // them the code is the only way in that a terminal can reach.\n let method: \"password\" | \"code\" | undefined = args[\"--code\"]\n ? \"code\"\n : (args[\"--password\"] || envPassword) ? \"password\" : undefined;\n if (method === \"code\") requireTerminalForCode();\n\n // Collect anything missing interactively — but only where a terminal can\n // supply it. Piped, this used to hang on a password prompt.\n let email = (args[\"--email\"] || envEmail).trim();\n if (!email || method === undefined) {\n requireInteractive(\"credentials\", `--email and --password, or ${EMAIL_ENV} and ${PASSWORD_ENV}`);\n }\n if (!email) {\n const answers = await inquirer.prompt([{ type: \"input\", name: \"email\", message: \"Email:\" }]);\n email = String(answers.email ?? \"\").trim();\n }\n if (!email) fail(\"An email is required.\", undefined, \"input_required\");\n\n const client = createCloudClient(url);\n if (method === undefined) {\n method = await offersSignInCodes(client.auth) ? await askSignInMethod() : \"password\";\n }\n\n let password = args[\"--password\"] || envPassword;\n if (method === \"password\" && !password) {\n const answers = await inquirer.prompt([{ type: \"password\", name: \"password\", message: \"Password:\", mask: \"•\" }]);\n password = String(answers.password ?? \"\");\n }\n if (method === \"password\" && !password) {\n fail(\"Email and password are required.\");\n }\n\n try {\n // An account with 2FA on answers either door with MFA_REQUIRED; the\n // second factor is asked for here and the sign-in finished with it.\n const { user } = await withSecondFactor(client.auth, () => method === \"code\"\n ? signInWithCode(client.auth, email)\n : client.auth.signInWithEmail(email, password));\n setCurrentContext(url);\n\n // Convenience: if the account belongs to exactly one org, make it active.\n try {\n const orgs = await client.data.collection(\"organizations\").find({ limit: 2 });\n if (orgs.data.length === 1 && !getContextOrg(url)) {\n setContextOrg(url, String(orgs.data[0].id));\n }\n } catch {\n // non-fatal — org selection is optional\n }\n\n success(`Logged in as ${chalk.bold(user.email ?? email)}`);\n emit(\n () => {\n keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"Active org\", getContextOrg(url)]\n ]);\n console.log(\"\");\n },\n {\n success: true,\n host: url,\n user: user.email ?? null,\n activeOrg: getContextOrg(url) ?? null\n }\n );\n } catch (e) {\n // Auth failures are the common case — give a clean message, not a stack.\n const err = e as { status?: number; message?: string };\n if (err?.status === 401 && method === \"password\") {\n // Most often an account that never had a password: a console\n // sign-up through Google, GitHub or LinkedIn.\n fail(\"Invalid email or password.\", NO_PASSWORD_HINT, \"invalid_credentials\");\n }\n reportError(e, \"Login failed\");\n }\n}\n\n/**\n * Ask before sending a password to a control plane a repository named.\n *\n * `.rebase/cloud.json` is committed with the code, so a cloned repository can\n * point its cloud commands at any host — and \"Not logged in to <host>\" invites\n * the login that would hand that host the user's email and password. A host\n * the user has signed in to before, or the platform's own, is theirs; any other\n * one is named and confirmed at a terminal, and refused without one: `--url`\n * is how a script says it means that host.\n */\nasync function confirmLinkedControlPlane(url: string): Promise<void> {\n const message = `This directory's .rebase/cloud.json names the control plane ${url}, which you have not signed in to before.`;\n if (isJsonMode() || process.stdin.isTTY !== true) {\n fail(\n message,\n `Your email and password would be sent there. To sign in to it on purpose, pass --url ${url}.`,\n \"unknown_control_plane\"\n );\n }\n warn(message, \"Your Rebase Cloud email and password will be sent to it.\");\n const { confirmed } = await inquirer.prompt([\n { type: \"confirm\", name: \"confirmed\", default: false, message: `Sign in to ${url}?` }\n ]);\n if (!confirmed) {\n console.error(chalk.gray(\" Aborted.\"));\n process.exit(0);\n }\n}\n\nexport async function logoutCommand(rawArgs: string[]): Promise<void> {\n // Only the globals, but parsed. `rebase cloud logout --frobnicate` exited 0\n // and signed the session out anyway — the one shape of this bug that also\n // destroys something.\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 2,\ncommand: \"cloud logout\",\nmaxPositionals: 0 });\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n if (!client.auth.getSession()) {\n // Not an error: `logout` is idempotent and a script should be able to\n // run it unconditionally. `wasLoggedIn` is how a caller tells the two\n // outcomes apart without reading the prose.\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.gray(` Not logged in to ${url}.`));\n console.log(\"\");\n },\n { success: true,\nhost: url,\nwasLoggedIn: false }\n );\n return;\n }\n try {\n await client.auth.signOut();\n } catch {\n // signOut clears local state even if the network call fails\n }\n success(`Logged out of ${url}`);\n emit(() => {}, { success: true,\nhost: url,\nwasLoggedIn: true });\n}\n\nexport async function whoamiCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 2,\ncommand: \"cloud whoami\",\nmaxPositionals: 0 });\n const { client, url } = await requireClient(rawArgs);\n // A token is not a session: `/auth/me` takes only a person's login, so the\n // question a token can answer is what it holds.\n // Unless `requireClient` set REBASE_TOKEN aside for the linked project's\n // own token, because it holds nothing on that project.\n if (envToken() && !grantProjectOf(client)) {\n await whoamiToken(client, url);\n return;\n }\n // Nor is the token `rebase cloud init --claim` stored for this directory's\n // project, which `requireClient` picked over the login. Asking `/auth/me`\n // with it used to be refused, and the refusal deleted the token and the\n // only stored copy of the claim link. What it can answer is what it holds,\n // and the claim link a person needs.\n const linked = linkedEphemeralGrant(url);\n if (linked) {\n await whoamiGrant(client, url, linked);\n return;\n }\n try {\n const user = await client.auth.getUser();\n if (!user) {\n fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\", \"session_invalid\");\n }\n const link = readLink();\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(\" 🔐 Rebase Cloud session\"));\n console.log(\"\");\n keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"User ID\", user.uid],\n [\"Roles\", user.roles?.length ? user.roles.join(\", \") : undefined],\n [\"Active org\", getContextOrg(url)],\n [\n \"Linked project\",\n link ? `${link.projectName ?? \"\"} (${link.projectId})`.trim() : undefined\n ]\n ]);\n console.log(\"\");\n },\n {\n host: url,\n user: {\n email: user.email ?? null,\n uid: user.uid,\n roles: user.roles ?? []\n },\n activeOrg: getContextOrg(url) ?? null,\n linkedProject: link\n ? { id: link.projectId,\nname: link.projectName ?? null,\nslug: link.slug ?? null }\n : null\n }\n );\n } catch (e) {\n reportError(e, \"Failed to fetch session\");\n }\n}\n\n/**\n * `whoami` in a directory linked to a project `rebase cloud init --claim`\n * provisioned: the project's own token, what it may do, the claim URL and\n * when the project expires unless someone claims it.\n */\nasync function whoamiGrant(\n client: CloudClient,\n url: string,\n linked: { projectId: string; grant: EphemeralGrant }\n): Promise<void> {\n let held: string[];\n try {\n ({ held } = await client.personalKeys.listScopes());\n } catch (e) {\n reportError(e, \"Failed to read the project token's scopes\");\n }\n const grants = capabilitiesInScopes(held).filter(grant => grant.capabilities.length > 0);\n const link = readLink();\n const expires = new Date(linked.grant.expiresAt);\n const appKeyNote = projectDotenvSetsAppKey() ? appKeyExpiryNote(linked.grant.expiresAt) : undefined;\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(\" 🔐 Unclaimed project token\"));\n console.log(\"\");\n keyValues([\n [\"Host\", url],\n [\"Credential\", \"the token `rebase cloud init --claim` stored (~/.rebase/credentials.json)\"],\n [\"Project\", link ? `${link.projectName ?? \"\"} (${linked.projectId})`.trim() : linked.projectId],\n [\"Can\", grants.length ? grants.map(g => g.capabilities.join(\", \")).join(\"; \") : undefined],\n [\"Claim URL\", chalk.bold(linked.grant.claimUrl)],\n [\"Expires\", `${expires.toLocaleString()} unless claimed`]\n ]);\n console.log(\"\");\n console.log(chalk.gray(\" Open the claim URL and sign in to keep the project. Unclaimed, it is deleted when it expires.\"));\n if (appKeyNote) console.log(chalk.gray(` ${appKeyNote}`));\n console.log(\"\");\n },\n {\n host: url,\n credential: \"ephemeral\",\n projectId: linked.projectId,\n claimUrl: linked.grant.claimUrl,\n expiresAt: linked.grant.expiresAt,\n appKeyNote: appKeyNote ?? null,\n grants,\n scopes: held,\n linkedProject: link\n ? { id: link.projectId, name: link.projectName ?? null, slug: link.slug ?? null }\n : null\n }\n );\n}\n\n/** `whoami` under `REBASE_TOKEN`: the host, the token, and what it may do. */\nasync function whoamiToken(client: CloudClient, url: string): Promise<void> {\n let held: string[];\n try {\n ({ held } = await client.personalKeys.listScopes());\n } catch (e) {\n reportError(e, \"Failed to read the token's scopes\");\n }\n const grants = capabilitiesInScopes(held).filter(grant => grant.capabilities.length > 0);\n const orgGrants = orgCapabilitiesInScopes(held).filter(grant => grant.capabilities.length > 0);\n const link = readLink();\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(\" 🔐 Rebase Cloud token\"));\n console.log(\"\");\n keyValues([\n [\"Host\", url],\n [\"Credential\", TOKEN_ENV],\n [\"Can\", describeGrants(held)],\n [\"Scopes\", held.join(\", \")],\n [\n \"Linked project\",\n link ? `${link.projectName ?? \"\"} (${link.projectId})`.trim() : undefined\n ]\n ]);\n console.log(\"\");\n },\n {\n host: url,\n credential: \"token\",\n grants,\n orgGrants,\n scopes: held,\n linkedProject: link\n ? { id: link.projectId, name: link.projectName ?? null, slug: link.slug ?? null }\n : null\n }\n );\n}\n","/**\n * `rebase cloud` context subcommands: link, unlink, use, open.\n *\n * `link` associates the current directory with a cloud project by writing\n * `.rebase/cloud.json`; deploy/logs/status then operate on it with no flags.\n */\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n resolveCloudUrl,\n parseCloudArgs,\n writeLink,\n removeLink,\n readLink,\n projectLinkPath,\n setContextOrg,\n getContextOrg,\n openUrl,\n success,\n fail,\n reportError,\n emit,\n note,\n noteBlank,\n warn,\n requireInteractive,\n cloudRows,\n grantForLink\n} from \"./context\";\n\ninterface ProjectRow {\n id: string | number;\n name?: string;\n subdomain?: string;\n organization?: string | number;\n status?: string;\n}\n\n/**\n * Link this checkout straight at a running backend.\n *\n * No control plane, no authentication, no project id — just the URL of a Rebase\n * API. This is what makes the multi-repo workflow available to self-hosters: a\n * frontend repository links to `https://api.example.com` and then generates its\n * typed SDK from that project exactly as a cloud-linked repository would.\n *\n * The URL is verified before it is written. Recording an unreachable address and\n * failing later, in a different command, would be a worse experience than\n * failing here where the user can see what they typed.\n */\nasync function linkDirect(target: string, rawArgs: string[]): Promise<void> {\n let base: URL;\n try {\n base = new URL(target);\n } catch {\n fail(`\"${target}\" is not a valid URL.`, undefined, \"invalid_url\");\n return;\n }\n\n if (base.protocol !== \"http:\" && base.protocol !== \"https:\") {\n fail(\"A project URL must be http or https.\", undefined, \"invalid_url\");\n }\n\n const apiUrl = base.toString().replace(/\\/+$/, \"\");\n const probe = `${apiUrl}/api/meta/schema-version`;\n\n let reachable = false;\n let detail = \"\";\n try {\n const response = await fetch(probe, { headers: { accept: \"application/json\" } });\n reachable = response.ok;\n if (!response.ok) detail = `responded ${response.status}`;\n } catch (err) {\n detail = err instanceof Error ? err.message : String(err);\n }\n\n if (!reachable) {\n // A real warning, not narration: the link is being written against an\n // address that did not answer, and that is as worth saying when piped as\n // when watched. It used to be `console.log(chalk.yellow(…))` — a caution\n // rendered in warning colours on the results stream, which put it inside\n // whatever a caller was parsing.\n warn(\n `Could not reach ${probe}${detail ? ` (${detail})` : \"\"}.`,\n \"Linking anyway — the server may not be running yet. It must be a Rebase backend of version 0.11 or newer.\"\n );\n }\n\n writeLink({\n url: apiUrl,\n projectId: \"\",\n apiUrl,\n mode: \"direct\",\n projectName: base.host\n });\n\n success(`Linked to ${apiUrl}`);\n emit(\n () => {\n note(chalk.dim(`Written to ${projectLinkPath()}`));\n noteBlank();\n note(`Next: ${chalk.cyan(\"rebase generate-sdk --from link\")}`, \"\");\n },\n {\n success: true,\n mode: \"direct\",\n apiUrl,\n reachable,\n projectName: base.host,\n linkPath: projectLinkPath()\n }\n );\n void rawArgs;\n}\n\nexport async function linkCommand(rawArgs: string[]): Promise<void> {\n // `--project` is a global, so the spec is empty: declaring it here would\n // replace the global in the merge while the global's other readers went on\n // reading the raw line. Strict rather than permissive — a mistyped flag\n // used to be dropped, and `link` then opened the interactive picker as\n // though nothing had been asked for.\n const { flags: args, positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 2, // cloud link\n command: \"cloud link\",\n maxPositionals: 1 // [url]\n });\n\n // A positional URL means \"this exact backend\", which needs no login and no\n // control plane. `rebase cloud link https://api.example.com`\n const positional = positionals.find(value => /^https?:\\/\\//i.test(value));\n if (positional) {\n await linkDirect(positional, rawArgs);\n return;\n }\n\n const { client, url } = await requireClient(rawArgs);\n\n try {\n let project: ProjectRow | undefined;\n\n if (args[\"--project\"]) {\n const projectId = await resolveProjectRef(args[\"--project\"], client);\n project = (await client.data.collection(\"projects\").findById(projectId)) as ProjectRow | undefined;\n if (!project) {\n fail(`Project ${args[\"--project\"]} not found.`, undefined, \"project_not_found\");\n }\n } else {\n // The picker needs a terminal. Without this, `rebase cloud link`\n // run by an agent parked on a select prompt forever.\n requireInteractive(\"a project to link\", \"--project <slug>\");\n const org = getContextOrg(url);\n const projects = cloudRows<ProjectRow>((await client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n limit: 100\n })).data);\n\n if (projects.length === 0) {\n fail(\n \"No projects found for your account.\",\n `Create one with ${chalk.bold(\"rebase cloud projects create\")}.`,\n \"no_projects\"\n );\n }\n\n const { picked } = await inquirer.prompt([\n {\n type: \"select\",\n name: \"picked\",\n message: \"Select a project to link:\",\n choices: projects.map((p) => ({\n name: `${p.name ?? \"(unnamed)\"} ${chalk.gray(String(p.subdomain ?? \"\"))}`,\n value: p\n }))\n }\n ] as Parameters<typeof inquirer.prompt>[0]);\n project = picked as ProjectRow;\n }\n\n if (!project) fail(\"No project selected.\", undefined, \"no_project\");\n\n const orgId = project.organization !== undefined ? String(project.organization) : undefined;\n writeLink({\n url,\n projectId: String(project.id),\n slug: project.subdomain,\n projectName: project.name,\n orgId\n });\n\n success(`Linked to ${chalk.bold(project.name ?? project.subdomain ?? \"\")}`);\n emit(\n () => {\n note(chalk.gray(`Wrote ${projectLinkPath()}`));\n noteBlank();\n },\n {\n success: true,\n mode: \"cloud\",\n host: url,\n projectId: String(project.id),\n slug: project.subdomain ?? null,\n projectName: project.name ?? null,\n org: orgId ?? null,\n linkPath: projectLinkPath()\n }\n );\n } catch (e) {\n reportError(e, \"Failed to link project\");\n }\n}\n\nexport function unlinkCommand(rawArgs: string[]): void {\n // It took no arguments at all, so `rebase cloud unlink --frobnicate`\n // removed the link and exited 0.\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 2,\ncommand: \"cloud unlink\",\nmaxPositionals: 0 });\n const link = readLink();\n if (!link) {\n // Idempotent, like `logout`: `unlinked: false` is how a caller tells\n // \"there was nothing to remove\" from \"removed it\".\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.gray(\" This directory is not linked to a cloud project.\"));\n console.log(\"\");\n },\n { success: true,\nunlinked: false,\nlinkPath: projectLinkPath() }\n );\n return;\n }\n // An unclaimed project outlives its link: it keeps running until it\n // expires, and this directory was the only place its claim URL was read\n // back from. Say so, with the URL, before the link goes.\n const grant = grantForLink(link);\n removeLink();\n if (grant) {\n warn(\n `Project ${link.slug ?? link.projectId} is unclaimed. Unlinking does not delete it: it runs until ${new Date(grant.expiresAt).toLocaleString()}, then it is deleted.`,\n `To keep it, open ${grant.claimUrl} and sign in.`\n );\n }\n success(\"Unlinked from cloud project\");\n emit(() => {}, { success: true,\nunlinked: true,\nlinkPath: projectLinkPath(),\nunclaimed: grant ? { projectId: link.projectId, claimUrl: grant.claimUrl, expiresAt: grant.expiresAt } : null });\n}\n\nexport async function selectOrgCommand(rawArgs: string[]): Promise<void> {\n // Was `rawArgs.slice(3).filter(a => !a.startsWith(\"-\"))[1]` — a hand-rolled\n // positional scan that skipped flag-shaped tokens and therefore accepted\n // any flag at all, including the value of one it did not declare.\n const { positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 2, // cloud use\n command: \"cloud use\",\n maxPositionals: 1 // [org]\n });\n const target = positionals[0];\n const { client, url } = await requireClient(rawArgs);\n\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as Array<{\n id: string | number;\n name?: string;\n slug?: string;\n }>;\n\n if (orgs.length === 0) {\n fail(\"You are not a member of any organization.\", undefined, \"no_orgs\");\n }\n\n let chosen = target\n ? orgs.find((o) => String(o.id) === target || o.slug === target)\n : undefined;\n\n if (!chosen && !target) {\n requireInteractive(\"an organization\", \"rebase cloud use <org-id|slug>\");\n const { picked } = await inquirer.prompt([\n {\n type: \"select\",\n name: \"picked\",\n message: \"Select the active organization:\",\n choices: orgs.map((o) => ({\n name: `${o.name ?? \"(unnamed)\"} ${chalk.gray(`${o.slug ?? \"\"} · ${o.id}`)}`,\n value: o\n }))\n }\n ] as Parameters<typeof inquirer.prompt>[0]);\n chosen = picked;\n }\n\n if (!chosen) fail(`Organization \"${target}\" not found.`, undefined, \"org_not_found\");\n\n setContextOrg(url, String(chosen.id));\n success(`Active organization set to ${chalk.bold(chosen.name ?? chosen.id)}`);\n emit(() => {}, {\n success: true,\n host: url,\n org: { id: String(chosen.id),\nname: chosen.name ?? null,\nslug: chosen.slug ?? null }\n });\n } catch (e) {\n reportError(e, \"Failed to set organization\");\n }\n}\n\n/** Open the Rebase Cloud dashboard (or the linked project) in a browser. */\nexport function openCommand(rawArgs: string[]): void {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 2,\ncommand: \"cloud open\",\nmaxPositionals: 0 });\n const url = resolveCloudUrl(rawArgs);\n const link = readLink();\n const target = link ? `${url}/projects/${link.projectId}` : url;\n openUrl(target);\n // The URL is the result. `openUrl` only narrates it (on stderr, and not at\n // all in JSON mode), so it has to be emitted here or a piped `cloud open`\n // produces nothing at all to act on.\n emit(() => {}, { url: target,\nprojectId: link?.projectId ?? null });\n}\n","/**\n * `rebase cloud billing invoices` and `rebase cloud billing upcoming`: what the\n * selected organization has been invoiced, and what it will be invoiced next.\n *\n * Both read Stripe through the control plane (`GET /stripe-billing/invoices/:org`\n * and `/upcoming/:org`) — the same reads as the console's Billing page, behind\n * the same gate: an owner or admin of the organization. Read-only; the hosted\n * invoice URL is where a person views, downloads or pays one.\n *\n * Amounts arrive in the currency's minor unit (cents) and stay that way in\n * `--json`, exactly as Stripe and the control plane send them; the human output\n * formats them.\n */\nimport chalk from \"chalk\";\nimport { emit, note, noteBlank, type CloudClient } from \"./context\";\n\n/** One issued invoice, as the control plane sends it. */\nexport interface CliInvoice {\n id: string;\n number: string | null;\n status: string | null;\n created: string | null;\n periodStart: string | null;\n periodEnd: string | null;\n total: number;\n amountDue: number;\n currency: string;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n}\n\n/** What one subscription will invoice next. */\nexport interface CliUpcomingInvoice {\n subscriptionId: string;\n kind: \"project\" | \"usage\";\n projectId: string | null;\n projectName: string | null;\n total: number;\n amountDue: number;\n currency: string;\n expectedAt: string | null;\n periodStart: string | null;\n periodEnd: string | null;\n lines: { description: string | null; amount: number; currency: string; quantity: number | null }[];\n moreLines: boolean;\n}\n\n/** The control plane's answer when there is no Stripe behind it. */\ninterface BillingFlags {\n simulated?: boolean;\n billingUnavailable?: boolean;\n}\n\n/** An amount in a currency's minor unit, for a person. The divisor is the currency's own. */\nexport function formatMinor(amount: number, currency: string): string {\n const code = (currency || \"eur\").toUpperCase();\n try {\n const format = new Intl.NumberFormat(\"en\", { style: \"currency\", currency: code });\n const digits = format.resolvedOptions().maximumFractionDigits ?? 2;\n return format.format(amount / 10 ** digits);\n } catch {\n return `${(amount / 100).toFixed(2)} ${code}`;\n }\n}\n\n/** A date as YYYY-MM-DD in UTC — Stripe's periods are UTC. */\nfunction day(iso: string | null): string {\n return iso ? iso.slice(0, 10) : \"—\";\n}\n\nconst UNAVAILABLE = \"Billing is not configured on this control plane, so there are no invoices to read.\";\n\nexport async function billingInvoices(client: CloudClient, org: string, limit?: number): Promise<void> {\n const query = limit !== undefined ? `?limit=${encodeURIComponent(String(limit))}` : \"\";\n const res = await client.functions.invoke<{ invoices?: CliInvoice[]; hasMore?: boolean } & BillingFlags>(\n \"stripe-billing\",\n undefined,\n { method: \"GET\", path: `invoices/${encodeURIComponent(org)}${query}` }\n );\n const invoices = res.invoices ?? [];\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🧾 Invoices — org ${org}`));\n console.log(\"\");\n if (res.billingUnavailable) {\n note(chalk.yellow(UNAVAILABLE));\n } else if (invoices.length === 0) {\n note(chalk.gray(\"No invoices yet.\"));\n } else {\n for (const inv of invoices) {\n const status = inv.status === \"paid\"\n ? chalk.green(\"paid\")\n : inv.status === \"open\"\n ? chalk.yellow(\"awaiting payment\")\n : chalk.gray(inv.status ?? \"unknown\");\n console.log(\n ` ${day(inv.created)} ${(inv.number ?? inv.id).padEnd(16)} `\n + `${formatMinor(inv.total, inv.currency).padStart(12)} ${status}`\n );\n if (inv.hostedInvoiceUrl) console.log(chalk.gray(` ${inv.hostedInvoiceUrl}`));\n }\n if (res.hasMore) {\n noteBlank();\n note(chalk.gray(`Showing the latest ${invoices.length}; pass --limit (up to 100) for more.`));\n }\n }\n console.log(\"\");\n },\n {\n org,\n invoices,\n hasMore: Boolean(res.hasMore),\n billingUnavailable: Boolean(res.billingUnavailable)\n }\n );\n}\n\nexport async function billingUpcoming(client: CloudClient, org: string): Promise<void> {\n const res = await client.functions.invoke<{ upcoming?: CliUpcomingInvoice[]; truncated?: boolean } & BillingFlags>(\n \"stripe-billing\",\n undefined,\n { method: \"GET\", path: `upcoming/${encodeURIComponent(org)}` }\n );\n const upcoming = res.upcoming ?? [];\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🧾 Next invoice (preview) — org ${org}`));\n console.log(\"\");\n if (res.billingUnavailable) {\n note(chalk.yellow(UNAVAILABLE));\n } else if (upcoming.length === 0) {\n note(chalk.gray(\"Nothing is due next: no active subscription will invoice.\"));\n } else {\n for (const u of upcoming) {\n const name = u.kind === \"usage\" ? \"Usage beyond the allowance\" : u.projectName ?? u.projectId ?? \"project\";\n console.log(` ${day(u.expectedAt)} ${name.padEnd(28)} ${formatMinor(u.total, u.currency).padStart(12)}`);\n for (const line of u.lines) {\n console.log(chalk.gray(` ${line.description ?? \"—\"} ${formatMinor(line.amount, line.currency)}`));\n }\n }\n noteBlank();\n note(chalk.gray(\"A preview computed by Stripe, not an invoice: metered usage keeps adding up until the period closes.\"));\n }\n console.log(\"\");\n },\n {\n org,\n upcoming,\n truncated: Boolean(res.truncated),\n billingUnavailable: Boolean(res.billingUnavailable)\n }\n );\n}\n","import fs from \"fs\";\n/**\n * `rebase cloud` resource subcommands: status, metrics, webhooks, storage,\n * clusters, billing.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n lookupProjectId,\n displayProjectRef,\n getContextOrg,\n readLink,\n colorStatus,\n emit,\n printGroupHelp,\n keyValues,\n fetchTenantBaseDomain,\n projectHost,\n openUrl,\n parseCloudArgs,\n requireKnownAction,\n success,\n fail,\n reportError,\n note,\n noteBlank,\n billingAccountIdOf,\n grantForLink,\n appKeyExpiryNote,\n projectDotenvSetsAppKey,\n warn\n} from \"./context\";\nimport { DEFAULT_STORAGE_SOURCE_KEY } from \"@rebasepro/types\";\nimport { firstRow, latestDeployment, fmtDate } from \"./projects\";\nimport { wantsRawError } from \"./errors\";\nimport { billingInvoices, billingUpcoming } from \"./billing-invoices\";\nimport { switchOn } from \"../../utils/args\";\n\n/* ─── status: quick project dashboard ──────────────────────────── */\n\n/** The control plane's verdict on what a tenant's uploads actually do. */\ninterface StorageState {\n effective?: { kind?: string; summary?: string; storageType?: string; missing?: string[] };\n source?: string;\n configured?: string;\n overridden?: boolean;\n}\n\n/**\n * One line describing this project's storage — or `undefined` when the control\n * plane could not be asked, which prints as a blank rather than a guess.\n *\n * `status` used to render the `storages` row and nothing else, so a project\n * whose bucket is configured through its own `STORAGE_TYPE`/`S3_*` variables —\n * the supported path, and the one `mergeStorageEnv` deliberately lets WIN over\n * the row — was reported as `Storage: none` while its pod logged `Initialized\n * storage backends count: 1` against a live bucket. Storage is the thing an app\n * refuses to boot without, so that false negative sends someone off to\n * provision a bucket they already have. The row is not the answer; the tenant's\n * resolved environment is, and the control plane computes it with the same two\n * functions the build log uses.\n */\nexport function describeStorageState(state: StorageState | undefined): string | undefined {\n const verdict = state?.effective;\n if (!verdict?.kind) return undefined;\n const via = state?.overridden ? chalk.gray(\" · from env vars\") : \"\";\n switch (verdict.kind) {\n case \"durable\":\n return `${chalk.green(\"durable\")}${verdict.summary ? ` · ${verdict.summary}` : \"\"}${via}`;\n case \"ephemeral\":\n // Not \"none\": nothing is configured, so uploads land on the pod\n // filesystem and are lost at the next restart. That is a state, and\n // a bad one — saying \"none\" makes it sound merely unset.\n return `${chalk.yellow(\"ephemeral\")} ${chalk.gray(\"· uploads are lost on restart\")}`;\n case \"incomplete\":\n return `${chalk.red(\"incomplete\")} ${chalk.gray(`· missing ${(verdict.missing ?? []).join(\", \")}`)}`;\n case \"unrecognized\":\n return `${chalk.red(\"unrecognized\")} ${chalk.gray(`· STORAGE_TYPE=${verdict.storageType ?? \"?\"}`)}`;\n default:\n return undefined;\n }\n}\n\n/**\n * One line describing the database.\n *\n * `connectionStatus` is written `\"untested\"` at creation and only ever changed\n * by `rebase cloud db test`, so `managed (untested)` was reporting the absence\n * of a manual test as though it were the database's condition — on a project\n * that had just deployed against it. A never-tested database says only its\n * type; the verdict appears once there is one.\n */\nexport function describeDatabaseState(db: Record<string, unknown> | undefined): string | undefined {\n if (!db) return undefined;\n const type = typeof db.type === \"string\" ? db.type : \"database\";\n const connection = db.connectionStatus;\n if (connection === \"connected\" || connection === \"failed\") {\n return `${type} (${colorStatus(connection)})`;\n }\n return `${type} ${chalk.gray(\"· not tested (`rebase cloud db test`)\")}`;\n}\n\n/* ─── what a project is waiting for ────────────────────────────── */\n\n/**\n * The one thing standing between this project and a live URL, if anything is.\n *\n * `status` alone cannot answer that, and the gap is not cosmetic. A project\n * created through `projects create` is written `status: \"provisioning\"` and has\n * no database until one is attached — so the platform is not provisioning\n * anything, it is waiting for a second command that nothing in the output names.\n * \"Provisioning\" reads as *work in progress*, and the correct response to work\n * in progress is to wait. So the correct response to this state, for a person\n * and an agent alike, is the one thing that is guaranteed never to resolve it.\n *\n * That cost 43 minutes of polling on a first deploy, and an unattended agent\n * would still be polling: nothing about the state changes, ever, so there is no\n * timeout short enough to be wrong and no timeout long enough to be right.\n *\n * `blockedOn: null` is therefore load-bearing — it is the CLI saying \"waiting is\n * the correct thing to do here\", which is the only condition under which a\n * caller should poll. Everything else names a command.\n */\nexport interface BlockedState {\n /** A stable slug, or `null` when the platform genuinely is working. */\n blockedOn: string | null;\n /** The exact command that unblocks it. `null` when nothing is blocked. */\n nextAction: string | null;\n}\n\n/** Deployment states that mean the platform is still doing something. */\nconst IN_FLIGHT = new Set([\"deploying\", \"building\", \"pending\", \"queued\"]);\n\n/**\n * Did this deploy get past its build and die booting?\n *\n * Matched on the control plane's own sentence, which is text this project emits\n * (`awaitRolloutOrRollback`) rather than anything a customer's build can produce\n * — so it is a signal about our state machine, not a guess about a log. Being\n * wrong points a reader at the other log, which is recoverable; not answering at\n * all pointed everyone at the empty one.\n */\nfunction bootFailed(logs: string | null | undefined): boolean {\n return typeof logs === \"string\" && /did not become ready within/i.test(logs);\n}\n\nexport function resolveBlockedState(input: {\n projectStatus?: string | null;\n /** The project's database row, or undefined when none is attached. */\n database?: { connectionStatus?: string | null } | undefined;\n lastDeploy?: { status?: string | null; logs?: string | null } | undefined;\n}): BlockedState {\n // First, because it is the state that never resolves itself. A project\n // with no database cannot deploy, and no amount of waiting attaches one.\n //\n // Unless it already did. A project whose last deploy SUCCEEDED has a\n // database by definition — the deploy path provisions the managed stack and\n // the runtime ensures the schema at boot, neither of which can happen\n // without one. For a long time that path wrote no `databases` row, so this\n // branch fired on projects that were serving traffic: it reported\n // `blockedOn: no_database` beside `status: active`, and named `db create`\n // as the remedy — the one command that could provision a SECOND database\n // and repoint the app at it, away from the rows.\n //\n // So the absence of a row is only conclusive before anything has deployed.\n // Afterwards it describes the control plane's bookkeeping, not the project,\n // and `db create` must never be suggested for it.\n if (!input.database && input.lastDeploy?.status !== \"success\") {\n return {\n blockedOn: \"no_database\",\n nextAction: \"rebase cloud db create --type managed\"\n };\n }\n\n // A deploy in flight is the one case where waiting is right. Said\n // explicitly rather than by omission, so a caller can tell \"nothing to do\"\n // apart from \"this CLI has no opinion\".\n if (input.lastDeploy && IN_FLIGHT.has(String(input.lastDeploy.status))) {\n return { blockedOn: null,\nnextAction: null };\n }\n\n if (!input.lastDeploy) {\n return { blockedOn: \"never_deployed\",\nnextAction: \"rebase cloud deploy\" };\n }\n\n // A failed deploy is not a wait either: the project stays exactly as it is\n // until someone reads the log and deploys again. WHICH log is the whole\n // question, and `rebase cloud logs` is the build one.\n //\n // A readiness timeout means the build succeeded — the image was pushed and\n // the pod was started — and the process then died on boot. So the build log\n // this named is clean, and reads as a deploy that failed for no reason. The\n // reason is in the container's log, behind a flag nothing mentioned. Four\n // failures on one project were diagnosed that way, at five minutes each.\n if (input.lastDeploy.status && input.lastDeploy.status !== \"success\") {\n return {\n blockedOn: \"last_deploy_failed\",\n nextAction: bootFailed(input.lastDeploy.logs)\n ? \"rebase cloud logs --runtime\"\n : \"rebase cloud logs\"\n };\n }\n\n // A database that has been attached but never reached — the deploy\n // succeeded and the app cannot talk to its own store.\n if (input.database?.connectionStatus === \"failed\") {\n return { blockedOn: \"database_unreachable\",\nnextAction: \"rebase cloud db test\" };\n }\n\n return { blockedOn: null,\nnextAction: null };\n}\n\n/**\n * One line describing what engine is serving this project.\n *\n * Three numbers are in play and they are easy to conflate — I have watched it\n * happen. The **runtime version** (`1.2.0`) is the contract line a bundle's\n * range resolves against; its major IS the contract major. The **framework\n * version** (`0.11.0`) is the `@rebasepro` release the runtime image ships. They\n * move independently on purpose: tying the contract line to the framework would\n * make `^1` become `^0.11`, and pre-1.0 caret is restrictive, so every framework\n * minor would fall outside every project's range and force a rebuild to receive\n * an engine upgrade — the opposite of what the bundle/runtime split is for.\n *\n * So both are printed, rather than leaving anyone to infer one from a Docker tag.\n */\nexport function describeRuntime(project: {\n runtimeMode?: string | null;\n runtimeVersion?: string | null;\n runtimeFrameworkVersion?: string | null;\n runtimeVersionPin?: string | null;\n}): string {\n // Absent is a third state, not a synonym for custom. `runtime_mode` stopped\n // defaulting to `custom` in migration 0040, so a project that has never\n // deployed has no mode at all — and \"your own image\" about one of those\n // asserts a container that was never built. The first deploy decides.\n if (project.runtimeMode == null || project.runtimeMode.trim() === \"\") {\n return `not deployed yet ${chalk.gray(\"· the first deploy decides (`--bundle` keeps it managed)\")}`;\n }\n if (project.runtimeMode !== \"managed\") {\n return `custom ${chalk.gray(\"· your own image\")}`;\n }\n const version = project.runtimeVersion ?? \"unknown\";\n const framework = project.runtimeFrameworkVersion;\n const pin = project.runtimeVersionPin ? chalk.gray(` · pinned to ${project.runtimeVersionPin}`) : \"\";\n // \"image framework\", not \"framework\". This one is what the IMAGE ships (the\n // server half); `cloud deployments` reports what each BUNDLE installed (the\n // driver half). Two facts about the two sides of the boundary the intake\n // floor exists to police — and while both were printed as \"framework\n // version\", the only way to read them was as one number contradicting\n // itself, which is exactly how it was reported.\n //\n // Absent rather than guessed: a release whose image tag is not a semver\n // (a `latest`, a branch build) records no framework version, and inventing\n // one here would defeat the point of storing it.\n const frameworkPart = framework ? chalk.gray(` · image framework ${framework}`) : \"\";\n return `managed ${version}${frameworkPart}${pin}`;\n}\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 2,\ncommand: \"cloud status\",\nmaxPositionals: 0 });\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const project = (await client.data.collection(\"projects\").findById(projectId)) as\n | {\n id: string | number; name?: string; subdomain?: string; host?: string; status?: string;\n gitBranch?: string; runtimeMode?: string | null; runtimeVersion?: string | null;\n runtimeFrameworkVersion?: string | null; runtimeContract?: number | null;\n runtimeRange?: string | null; runtimeVersionPin?: string | null;\n }\n | undefined;\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`, undefined, \"not_found\");\n\n const [db, storage, deploy, baseDomain] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n // A control plane that does not have this route yet, or a lookup\n // that fails, yields `undefined` — which prints as a blank. A blank\n // is a better answer than a wrong one for exactly this field.\n client.functions\n .invoke<StorageState>(\"storage-provision\", undefined, { method: \"GET\",\npath: projectId })\n .catch(() => undefined),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url)\n ]);\n\n const storageLine = describeStorageState(storage);\n const databaseLine = describeDatabaseState(db);\n // An unclaimed project's claim URL, read back from where `init --claim`\n // kept it: the only other copy was that command's output.\n const link = readLink();\n const grant = link?.projectId === projectId ? grantForLink(link) : undefined;\n const appKeyNote = grant && projectDotenvSetsAppKey() ? appKeyExpiryNote(grant.expiresAt) : undefined;\n const blocked = resolveBlockedState({\n projectStatus: project.status,\n database: db as { connectionStatus?: string | null } | undefined,\n lastDeploy: deploy as { status?: string | null; logs?: string | null } | undefined\n });\n\n emit(\n () => {\n console.log(\"\");\n console.log(` ${chalk.bold(project.name ?? project.subdomain ?? \"\")} ${chalk.gray(`[${project.subdomain ?? displayProjectRef(rawArgs)}]`)} ${colorStatus(project.status)}`);\n console.log(\"\");\n keyValues([\n [\"URL\", projectHost(project, baseDomain)],\n [\"Branch\", project.gitBranch],\n [\"Last deploy\", deploy ? `${colorStatus(deploy.status)} · ${fmtDate(deploy.createdAt)}` : \"never\"],\n [\"Runtime\", describeRuntime(project)],\n [\"Database\", databaseLine],\n [\"Storage\", storageLine],\n [\"Claim URL\", grant ? chalk.bold(grant.claimUrl) : undefined],\n [\"Expires\", grant ? `${new Date(grant.expiresAt).toLocaleString()} unless claimed, then deleted` : undefined]\n ]);\n // The same fact the JSON carries, in the place a person reads.\n // Below the rows rather than inside them: it is not another\n // property of the project, it is what to do next.\n if (appKeyNote) {\n console.log(\"\");\n console.log(chalk.gray(` ${appKeyNote}`));\n }\n if (blocked.blockedOn) {\n console.log(\"\");\n console.log(` ${chalk.yellow(\"Waiting on you\")} ${chalk.gray(`— ${blocked.blockedOn}`)}`);\n console.log(` ${chalk.bold(blocked.nextAction ?? \"\")}`);\n }\n console.log(\"\");\n },\n {\n projectId: String(project.id),\n name: project.name ?? null,\n subdomain: project.subdomain ?? null,\n status: project.status ?? null,\n // Siblings of `status` on purpose: a caller reading `status`\n // has to read these to know what it means. `blockedOn: null` is\n // the only value under which polling `status` is correct.\n blockedOn: blocked.blockedOn,\n nextAction: blocked.nextAction,\n url: projectHost(project, baseDomain) ?? null,\n branch: project.gitBranch ?? null,\n lastDeploy: deploy ? { id: String(deploy.id),\nstatus: deploy.status ?? null,\ncreatedAt: deploy.createdAt ?? null } : null,\n runtime: {\n mode: project.runtimeMode ?? \"custom\",\n version: project.runtimeVersion ?? null,\n // `imageFrameworkVersion`, not `frameworkVersion`: this is\n // the framework the IMAGE ships, while a row from\n // `cloud deployments` carries `builtAgainst`, the framework\n // that BUNDLE installed. They are routinely different (the\n // image supplies the server, the bundle supplies the\n // driver) and were both called `frameworkVersion`, so the\n // two commands read as the control plane contradicting\n // itself about one number.\n imageFrameworkVersion: project.runtimeFrameworkVersion ?? null,\n contract: project.runtimeContract ?? null,\n range: project.runtimeRange ?? null,\n pin: project.runtimeVersionPin ?? null\n },\n database: db ? { type: db.type ?? null,\nconnectionStatus: db.connectionStatus ?? null } : null,\n storage: storage ?? null,\n // Present while the project is unclaimed: open `claimUrl` and\n // sign in to keep it, before `expiresAt`.\n unclaimed: grant\n ? { claimUrl: grant.claimUrl, expiresAt: grant.expiresAt, appKeyNote: appKeyNote ?? null }\n : null\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load status\");\n }\n}\n\n/* ─── metrics: live compute metrics ────────────────────────────── */\n\n/** What `/api/functions/metrics/:projectId` returns. Mirrors saas metrics.ts. */\ninterface TenantMetrics {\n status?: string;\n cpu?: string;\n memory?: string;\n memoryPercent?: string;\n disk?: string | null;\n /** What the figures are OF — a project is not one machine. */\n subject?: { workload?: string; kind?: string; sampledInstances?: number } | null;\n /** The ceiling the percentages are measured against, per instance. */\n allocation?: {\n cpuLimitMillicores?: number | null;\n memoryLimitBytes?: number | null;\n cpuRequestMillicores?: number | null;\n memoryRequestBytes?: number | null;\n } | null;\n instances?: {\n name?: string;\n phase?: string;\n ready?: boolean;\n restarts?: number;\n cpuMillicores?: number | null;\n memoryBytes?: number | null;\n /** Why the previous container died. The whole story of a crashloop. */\n lastTerminationReason?: string | null;\n lastTerminationExitCode?: number | null;\n /** Why it has not started yet — ImagePullBackOff, CreateContainerError. */\n waitingReason?: string | null;\n }[] | null;\n condition?: { reason?: string; message?: string } | null;\n}\n\n/**\n * CPU with the ceiling it is a percentage of.\n *\n * A bare \"0.2%\" is unreadable without knowing 0.2% of what, and on a burstable\n * pod the answer is not obvious: these request 250m and may burst to 2 vCPU, so\n * a pod at 40% of its LIMIT is at over three times its guaranteed share and may\n * still be throttled. Naming both is the difference between a number and a\n * number that means something.\n */\nfunction cpuLine(m: TenantMetrics): string | undefined {\n if (!m.cpu) return undefined;\n const limit = m.allocation?.cpuLimitMillicores;\n const request = m.allocation?.cpuRequestMillicores;\n if (limit == null && request == null) return m.cpu;\n const parts = [\n request != null ? `${request}m guaranteed` : null,\n limit != null ? `bursts to ${limit}m` : null\n ].filter(Boolean).join(\", \");\n return `${m.cpu} ${chalk.gray(`(${parts}, per instance)`)}`;\n}\n\nexport async function metricsCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 2,\ncommand: \"cloud metrics\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const m = await client.functions.invoke<TenantMetrics>(\n \"metrics\", undefined, { method: \"GET\", path: projectId }\n );\n\n // What the numbers are OF. The endpoint has reported this since it\n // learned to, and this command threw it away — printing bare\n // \"CPU / Memory\" over figures that only ever cover the backend\n // Deployment. A reader had every reason to think the database was in\n // them; `metrics.ts` says in its own comment that it is not.\n const of = m.subject?.workload\n ? `${m.subject.workload}${m.subject.kind === \"deployment\" ? \" (backend only — not the database)\" : \"\"}`\n : undefined;\n\n // Sampled, not desired. A pod that has not reported to metrics-server\n // yet is absent from the sum, so \"89 MiB\" across one instance of two is\n // half a picture and should say so.\n const sampled = m.subject?.sampledInstances;\n const coverage = sampled === undefined\n ? undefined\n : sampled === 0\n ? chalk.yellow(\"no instances reported yet\")\n : `${sampled} instance${sampled === 1 ? \"\" : \"s\"}`;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 📊 Metrics — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n keyValues([\n [\"Status\", m.status ? colorStatus(m.status === \"running\" ? \"active\" : m.status) : undefined],\n [\"Measuring\", of],\n [\"Sampled\", coverage],\n [\"CPU\", cpuLine(m)],\n [\"Memory\", m.memory ? `${m.memory}${m.memoryPercent ? ` (${m.memoryPercent})` : \"\"}` : undefined],\n [\"Disk\", m.disk]\n ]);\n\n // Why it is unhealthy, when it is. Straight from the workload's\n // own conditions — the endpoint does not interpret it and\n // neither does this.\n if (m.condition) {\n console.log(\"\");\n console.error(chalk.red(` ✗ ${m.condition.reason ?? \"Not healthy\"}`));\n if (m.condition.message) note(` ${m.condition.message}`);\n }\n\n // Per instance, because an average hides the pod that is hot.\n if (m.instances?.length) {\n console.log(\"\");\n note(\" Instances\");\n for (const i of m.instances) {\n const cpu = i.cpuMillicores != null ? `${Math.round(i.cpuMillicores)}m` : \"—\";\n const mem = i.memoryBytes != null ? `${(i.memoryBytes / 1024 / 1024).toFixed(0)} MiB` : \"—\";\n const health = i.ready === false ? chalk.yellow(\" not ready\") : \"\";\n // Restarts are the first thing anyone wants when a\n // tenant is misbehaving, and a silent 0 is noise — so it\n // only appears when there are any.\n const restarts = i.restarts ? chalk.yellow(` ${i.restarts}×restarted`) : \"\";\n note(` ${(i.name ?? \"?\").padEnd(34)} ${cpu.padStart(6)} ${mem.padStart(9)}${health}${restarts}`);\n // Why the last one died, when one did. This is the line\n // that turns \"it keeps restarting\" into a diagnosis, and\n // it was being fetched and discarded.\n if (i.lastTerminationReason) {\n note(chalk.gray(\n ` last exit: ${i.lastTerminationReason}` +\n (i.lastTerminationExitCode != null ? ` (code ${i.lastTerminationExitCode})` : \"\")\n ));\n }\n if (i.waitingReason) note(chalk.gray(` waiting: ${i.waitingReason}`));\n }\n }\n console.log(\"\");\n },\n {\n projectId,\n status: m.status ?? null,\n cpu: m.cpu ?? null,\n memory: m.memory ?? null,\n memoryPercent: m.memoryPercent ?? null,\n disk: m.disk ?? null,\n // Passed through rather than reshaped: a script that wants the\n // ceiling to compute its own percentage should get the same\n // numbers the server sent.\n subject: m.subject ?? null,\n allocation: m.allocation ?? null,\n instances: m.instances ?? null,\n condition: m.condition ?? null\n }\n );\n } catch (e) {\n reportError(e, \"Failed to fetch metrics\");\n }\n}\n\n/* ─── webhooks (retired) ───────────────────────────────────────── */\n\n/**\n * `rebase cloud webhooks` is retired, and says where to go instead.\n *\n * It never worked. It wrote rows to a data collection named `webhooks` on the\n * control plane, whose real slug is `database-webhooks` — and nothing on the\n * control plane ever delivered those rows anyway. What people reached for it\n * to do is now two other things:\n *\n * - a project's own events (a deploy failed, backups stopped, a payment was\n * declined, usage passed 80%) to Slack, Discord or any URL:\n * `rebase cloud notifications`;\n * - a POST when rows of your app's own tables change: a `WebhookDispatcher`\n * in your app's code, which your backend delivers itself.\n *\n * Every action answers the same refusal, exit 1, code `command_retired`, with\n * both routes — a retired command that still exits 0 would tell a script its\n * webhook exists.\n */\nexport const WEBHOOKS_RETIRED_HINT =\n \"For a project's events (deploy failed, backups, billing, usage) to Slack, Discord or any URL: \"\n + \"`rebase cloud notifications add <url>`. For row changes in your app's own tables: a WebhookDispatcher \"\n + \"in your app's code — https://rebase.pro/docs/recipes/webhooks/\";\n\nexport async function webhooksCommand(_subcommand: string | undefined, _rawArgs: string[]): Promise<void> {\n fail(\n \"`rebase cloud webhooks` is retired: it never delivered anything.\",\n WEBHOOKS_RETIRED_HINT,\n \"command_retired\"\n );\n}\n\n/* ─── storage ──────────────────────────────────────────────────── */\n\n/** The action words `rebase cloud storage` dispatches. No word means `list`. */\nexport const STORAGE_ACTIONS = [\"list\", \"create\", \"attach\"] as const;\n\nexport async function storageCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n // `rebase cloud storage` used to only ever list. A tenant could therefore\n // reach durable storage only by creating a bucket by hand in a cloud\n // console, minting credentials, and pasting them into the web UI — and\n // until they did, the project simply had no file storage. These make it a\n // thing the platform can do for you.\n //\n // `action` is the positional the dispatcher already resolved, as for every\n // other resource group. Re-deriving it here by index was wrong — the group\n // sits at rawArgs[3], so rawArgs[2] is always the literal \"cloud\" and no\n // subcommand ever matched.\n if (action === \"create\") return storageCreateCommand(rawArgs);\n if (action === \"attach\") return storageAttachCommand(rawArgs);\n if (action === \"help\") return printStorageHelp();\n // Everything that is not one of those, and is not `list` or nothing, is a\n // typo — and used to LIST, exit 0, and read as a bucket that was created.\n requireKnownAction(\"storage\", action, STORAGE_ACTIONS);\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud storage\",\nmaxPositionals: 0 });\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const stores = (await client.data.collection(\"storages\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data as Array<{\n id: string | number;\n sourceKey?: string;\n type?: string;\n provider?: string;\n bucketName?: string;\n s3Bucket?: string;\n status?: string;\n }>;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🪣 Storage — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (stores.length === 0) {\n console.log(chalk.gray(\" No storage buckets attached.\"));\n console.log(\"\");\n return;\n }\n for (const s of stores) {\n // `bucketName` is written by managed provisioning only, so\n // a bucket attached from the console or by `attach` listed\n // as \"byos\" — the type, printed where the name goes. The\n // name the tenant actually reads is `s3Bucket`.\n const name = s.bucketName || s.s3Bucket || \"(no bucket)\";\n const key = s.sourceKey || DEFAULT_STORAGE_SOURCE_KEY;\n console.log(` ${chalk.bold(name)} ${chalk.gray(`[${s.id}]`)} ${colorStatus(s.status)}`);\n keyValues([[\"Source\", key], [\"Provider\", s.provider], [\"Type\", s.type]]);\n }\n console.log(\"\");\n },\n {\n projectId,\n stores: stores.map((s) => ({\n id: String(s.id),\n sourceKey: s.sourceKey || DEFAULT_STORAGE_SOURCE_KEY,\n bucketName: s.bucketName || s.s3Bucket || null,\n type: s.type ?? null,\n provider: s.provider ?? null,\n status: s.status ?? null\n }))\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list storage\");\n }\n}\n\nexport function printStorageHelp(): void {\n printGroupHelp({\n command: \"cloud storage\",\n title: \"The project's object storage\",\n actions: [\n { action: \"list\",\ndescription: \"The buckets this project has, and their state\" },\n { action: \"create\",\ndescription: \"Provision platform-managed storage. Takes no options\" },\n {\n action: \"attach\",\n description: \"Attach your own S3-compatible bucket\",\n flags: [\n [\"--bucket <name>\", \"Bucket name. Required\"],\n [\"--access-key-id <id>\", \"Access key ID. Required\"],\n [\"--secret-access-key <s>\", \"Secret access key. Required\"],\n [\"--endpoint <url>\", \"S3 endpoint. Omit for AWS\"],\n [\"--region <region>\", \"Region\"],\n [\"--force-path-style\", \"Required by MinIO and some gateways\"],\n [\"--source <key>\", \"Which declared bucket. Default: the default one\"]\n ]\n }\n ],\n notes: [\n \"Without either, file storage stays off: uploads are refused with 501\",\n \"STORAGE_NOT_CONFIGURED rather than written to a container filesystem that is\",\n \"erased on the next restart.\",\n \"Redeploy after `attach` for the tenant to pick the credentials up.\"\n ]\n });\n}\n\n/* ─── storage create: platform-managed ─────────────────────────── */\n\nasync function storageCreateCommand(rawArgs: string[]): Promise<void> {\n // Takes no options of its own, and provisions billable infrastructure: an\n // unrecognised flag here (`storage create --region eu`, borrowed from\n // `attach`) provisioned in the default region and said nothing.\n parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud storage create\n command: \"cloud storage create\",\n maxPositionals: 0\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n noteBlank();\n note(chalk.gray(\"Provisioning managed storage — this creates a bucket and its credentials...\"));\n\n const res = await client.functions.invoke<{\n data: { bucketName: string; region: string; endpoint: string; accessKeyId: string };\n // The project id is a SUB-PATH, not part of the function name.\n // `invoke` runs `encodeURIComponent` over the name — correct, since\n // a function name is one path segment — so folding the id into it\n // sent `POST /api/functions/storage-provision%2F<id>`, which matches\n // no route. The control plane answered a bare 404 and\n // `rebase cloud storage create` read as an unimplemented feature for\n // six weeks. `invoke` now refuses a name containing `/` outright.\n }>(\"storage-provision\", undefined, { method: \"POST\", path: projectId });\n\n // `res.data`, once. What stood here was\n // `(res as unknown as { data?: typeof res.data }).data ?? res.data` —\n // both halves read the same property off the same object, so the `??`\n // could never reach its right-hand side. The cast made it look like a\n // fallback between two response shapes by making `data` optional on one\n // of them; `invoke<T>` returns `T`, and `T` here declares `data`.\n const info = res.data;\n\n success(`Managed storage provisioned for ${displayProjectRef(rawArgs)}.`);\n emit(\n () => {\n keyValues([\n [\"Bucket\", info.bucketName],\n [\"Region\", info.region],\n [\"Endpoint\", info.endpoint],\n [\"Access key\", info.accessKeyId]\n ]);\n noteBlank();\n // The secret is never returned by the endpoint — it goes to the\n // row and to the tenant's environment. Say so, or the absence\n // reads as a bug.\n note(chalk.gray(\"The secret key is stored encrypted and injected at deploy time; it is not displayed.\"));\n note(chalk.gray(\"Redeploy for the tenant to pick it up: \") + chalk.bold(\"rebase cloud deploy\"));\n noteBlank();\n },\n {\n success: true,\n projectId,\n bucketName: info.bucketName,\n region: info.region,\n endpoint: info.endpoint,\n accessKeyId: info.accessKeyId,\n // Stated, not omitted: a caller that finds no secret in the\n // payload should know it was withheld, not lost.\n secretAccessKey: null,\n pendingRedeploy: true\n }\n );\n } catch (e) {\n reportError(e, \"Failed to provision managed storage\");\n }\n}\n\n/* ─── storage attach: bring your own ───────────────────────────── */\n\nasync function storageAttachCommand(rawArgs: string[]): Promise<void> {\n // Strict: every value here is credentials or the bucket they open, and the\n // permissive parse turned a mistyped `--acces-key-id` into the \"missing\n // --access-key-id\" refusal below — the right refusal for the wrong reason,\n // and one that says nothing about the flag that was actually wrong.\n const { flags: parsed } = parseCloudArgs({\n spec: {\n \"--bucket\": String,\n \"--access-key-id\": String,\n \"--secret-access-key\": String,\n \"--endpoint\": String,\n \"--region\": String,\n \"--force-path-style\": Boolean,\n // Which declared bucket this configures. A project has one row per\n // source, and without this the command took `limit: 1` off an\n // unordered find and updated whichever row came back — so\n // attaching a bucket to a two-bucket project could overwrite\n // `media`'s credentials while reporting success.\n \"--source\": String\n },\n rawArgs,\n commandWords: 3, // cloud storage attach\n command: \"cloud storage attach\",\n maxPositionals: 0\n });\n\n const bucket = parsed[\"--bucket\"];\n const accessKeyId = parsed[\"--access-key-id\"];\n const secretAccessKey = parsed[\"--secret-access-key\"];\n\n // All three or none. A bucket carrying no credentials is the state that\n // reads as configured in the console and fails on the first upload.\n const missing = [\n !bucket && \"--bucket\",\n !accessKeyId && \"--access-key-id\",\n !secretAccessKey && \"--secret-access-key\"\n ].filter(Boolean) as string[];\n if (missing.length > 0) {\n fail(\n `Missing ${missing.join(\", \")}.`,\n \"A bucket without credentials cannot be used, and would be stored as though it could. \" +\n \"Run `rebase cloud storage --help` for the full list.\",\n \"usage\"\n );\n }\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n const sourceKey = (parsed[\"--source\"] ?? \"\").trim() || DEFAULT_STORAGE_SOURCE_KEY;\n\n try {\n const existing = (await client.data.collection(\"storages\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data.find((r) => {\n const key = (r as { sourceKey?: unknown }).sourceKey;\n return (typeof key === \"string\" && key ? key : DEFAULT_STORAGE_SOURCE_KEY) === sourceKey;\n }) as { id?: string | number } | undefined;\n\n const row: Record<string, unknown> = {\n project: projectId,\n // Written, not left to the column default: a row that does not say\n // which source it configures is a row the console and the deploy\n // path both have to guess about.\n sourceKey,\n type: \"byos\",\n status: \"active\",\n s3Bucket: bucket,\n s3AccessKeyId: accessKeyId,\n s3SecretAccessKey: secretAccessKey,\n bucketName: bucket\n };\n if (parsed[\"--endpoint\"]) row.s3Endpoint = parsed[\"--endpoint\"];\n if (parsed[\"--region\"]) {\n row.s3Region = parsed[\"--region\"];\n row.region = parsed[\"--region\"];\n }\n // Only when set: AWS rejects path style, so an unconditional false\n // would be noise in every project that does not need it.\n if (parsed[\"--force-path-style\"]) row.s3ForcePathStyle = true;\n\n const replaced = Boolean(existing?.id);\n if (existing?.id) {\n await client.data.collection(\"storages\").update(String(existing.id), row);\n } else {\n await client.data.collection(\"storages\").create(row);\n }\n\n success(`Storage attached to ${displayProjectRef(rawArgs)}.`);\n emit(\n () => {\n keyValues([\n [\"Bucket\", bucket],\n [\"Endpoint\", parsed[\"--endpoint\"] ?? \"AWS S3\"],\n [\"Region\", parsed[\"--region\"] ?? \"(default)\"]\n ]);\n noteBlank();\n note(chalk.gray(\"Redeploy for the tenant to pick it up: \") + chalk.bold(\"rebase cloud deploy\"));\n noteBlank();\n },\n {\n success: true,\n projectId,\n bucket,\n endpoint: parsed[\"--endpoint\"] ?? null,\n region: parsed[\"--region\"] ?? null,\n forcePathStyle: Boolean(parsed[\"--force-path-style\"]),\n // The one fact the human rendering does not carry: `attach` over\n // an existing row is an overwrite, and a caller re-running it in\n // a script should be able to tell that it replaced something.\n replaced,\n pendingRedeploy: true\n }\n );\n } catch (e) {\n reportError(e, \"Failed to attach storage\");\n }\n}\n\n/* ─── clusters ─────────────────────────────────────────────────── */\n\n/** The action words `rebase cloud clusters` dispatches. No word means `list`. */\nexport const CLUSTERS_ACTIONS = [\"list\", \"add\", \"verify\", \"registry\"] as const;\n\n/**\n * `rebase cloud clusters` — list, register and verify the clusters tenants run on.\n *\n * Registration is deliberately an operator action: the `clusters` collection is\n * admin-only, and a cluster record carries a credential with enough power to\n * create namespaces and read every secret in them. A self-serve \"bring your own\n * cluster\" flow is a different feature with a different threat model.\n */\nexport async function clustersCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n if (action === \"verify\") return clustersVerifyCommand(rawArgs);\n if (action === \"add\") return clustersAddCommand(rawArgs);\n if (action === \"registry\") return clustersRegistryCommand(rawArgs);\n // `clusters verifyy` used to LIST the clusters and exit 0 — the one command\n // whose whole purpose is to answer a yes/no question about a specific one.\n requireKnownAction(\"clusters\", action, CLUSTERS_ACTIONS);\n return clustersListCommand(rawArgs);\n}\n\n/**\n * Ask a registered cluster whether it can actually host a tenant.\n *\n * The question this exists to answer early is the one that otherwise gets\n * answered by a customer's first deploy failing halfway through provisioning,\n * with an error they cannot act on and half a tenant already created.\n */\n/**\n * Which cluster `clusters verify` was asked about, and whether `--baseline`\n * was given.\n *\n * Resolved against a real spec, not scanned out of `rawArgs` by hand — and this\n * is not a tidy-up. `rawArgs` is the whole `process.argv`, so the old scan\n * (\"the first token that is not `--…` and is neither `clusters` nor `verify`\")\n * matched `argv[0]`, the **node binary path**. Every `rebase cloud clusters\n * verify <id>` therefore asked the control plane about a cluster called\n * `/usr/local/bin/node`, and came back 404.\n *\n * So the one diagnostic that reports `permissions.allowed` /\n * `permissions.denied` was unreachable, and its 404 read as \"this command is\n * not deployed yet\" rather than \"the id never left this machine intact\". It is\n * the command that names a missing `cronjobs.batch` grant in a single call\n * instead of a twenty-minute A/B against a live project.\n *\n * Same failure as `cloud deploy` reading `_[0]` as `\"cloud\"`, and the same fix:\n * one parser, exported so its test drives the real thing rather than a copy.\n */\nexport function resolveClusterVerifyArgs(rawArgs: string[]): { id?: string; baseline: boolean } {\n const { flags, positionals } = parseCloudArgs({\n spec: { \"--baseline\": Boolean },\n rawArgs,\n commandWords: 2, // cloud clusters — `verify` is the action positional\n command: \"cloud clusters verify\",\n maxPositionals: 2\n });\n return { id: positionals[1],\nbaseline: flags[\"--baseline\"] === true };\n}\n\nasync function clustersVerifyCommand(rawArgs: string[]): Promise<void> {\n const { id, baseline: withBaseline } = resolveClusterVerifyArgs(rawArgs);\n if (!id) fail(\"Usage: rebase cloud clusters verify <cluster-id> [--baseline]\", undefined, \"bad_request\");\n\n // Parsed before authenticating: a usage error is answerable without a\n // session, and asking for one first turns \"you forgot the id\" into \"log in\".\n const { client } = await requireClient(rawArgs);\n\n let report: {\n reachable: boolean; version?: string; unreachableReason?: string;\n permissions: { allowed: string[]; denied: { permission: string; consequence: string }[];\n unknown: { permission: string; error: string }[] };\n verdict: \"ready\" | \"degraded\" | \"unusable\"; blockers: string[];\n };\n try {\n report = await client.functions.invoke(\"cluster-baseline\", undefined, {\n method: \"GET\",\n // Encoded: the id is user input landing in a URL path, and `path`\n // is appended verbatim by the SDK (only the *function name* is\n // encoded for it).\n path: `verify/${encodeURIComponent(id)}${withBaseline ? \"?baseline=1\" : \"\"}`\n }) as never;\n } catch (error: unknown) {\n reportError(error, \"Could not verify the cluster\");\n return;\n }\n\n emit(\n () => {\n console.log(\"\");\n const tone = report.verdict === \"ready\" ? chalk.green\n : report.verdict === \"degraded\" ? chalk.yellow : chalk.red;\n console.log(` ${tone(chalk.bold(report.verdict.toUpperCase()))} ${chalk.gray(String(id))}`);\n console.log(\"\");\n keyValues([\n [\"Reachable\", report.reachable ? \"yes\" : chalk.red(\"no\")],\n [\"Permissions\", `${report.permissions.allowed.length} allowed, ${report.permissions.denied.length} denied`]\n ]);\n if (report.blockers.length > 0) {\n console.log(\"\");\n // Each blocker already says what breaks, so they are printed\n // whole rather than summarised into a count.\n for (const b of report.blockers) console.log(` ${chalk.red(\"✗\")} ${b}`);\n }\n console.log(\"\");\n if (!withBaseline && report.verdict !== \"unusable\") {\n note(\"Add --baseline to also check ingress-nginx, cert-manager and CloudNativePG.\");\n console.log(\"\");\n }\n },\n report\n );\n\n // Non-zero so this is usable as a gate in a script or a runbook step.\n if (report.verdict === \"unusable\") process.exitCode = 1;\n}\n\n/**\n * Register a cluster from a kubeconfig file.\n *\n * Verifies immediately rather than reporting a successful insert: a row that\n * names an unreachable cluster is worse than no row, because a project pointed\n * at it fails at deploy instead of at registration.\n */\n/** The columns a `clusters` row is registered with. Exported for its test. */\nexport interface ClusterAddArgs {\n name: string;\n provider: \"gcp\" | \"aws\" | \"hetzner\";\n region: string;\n kubeconfigPath: string;\n baseDomain?: string;\n ingressAddress?: string;\n /** This is capacity we operate: projects placed in its region deploy here. */\n platformCapacity: boolean;\n backupBucket?: string;\n backupEndpoint?: string;\n backupAccessKeyId?: string;\n backupSecretAccessKey?: string;\n}\n\n/**\n * What `clusters add` was asked to register.\n *\n * Everything a row needs to serve tenants is settable HERE, at insert, because\n * the control plane installs the cluster baseline on insert and reads the row\n * to do it: the name is what the Hetzner load balancer is adopted by, the\n * address is what the ingress is pinned to. Registering with the four\n * required flags and patching the rest afterwards would install a baseline\n * that knew neither.\n *\n * The backup fields travel together: a bucket with no key, or a key with no\n * bucket, is a row `resolveBackupStore` deliberately treats as \"no store\" —\n * so it is refused here, where the operator can still fix the command.\n */\nexport function resolveClusterAddArgs(rawArgs: string[]): ClusterAddArgs {\n const { flags } = parseCloudArgs({\n spec: {\n \"--name\": String,\n \"--provider\": String,\n \"--region\": String,\n \"--kubeconfig\": String,\n \"--base-domain\": String,\n \"--ingress-address\": String,\n \"--platform-capacity\": Boolean,\n \"--backup-bucket\": String,\n \"--backup-endpoint\": String,\n \"--backup-access-key-id\": String,\n \"--backup-secret-access-key\": String\n },\n rawArgs,\n commandWords: 2, // cloud clusters — `add` is the action positional\n command: \"cloud clusters add\",\n maxPositionals: 1\n });\n\n const name = flags[\"--name\"];\n const provider = flags[\"--provider\"];\n const region = flags[\"--region\"];\n const kubeconfigPath = flags[\"--kubeconfig\"];\n if (!name || !provider || !region || !kubeconfigPath) {\n fail(\n \"Usage: rebase cloud clusters add --name <n> --provider <gcp|aws|hetzner> --region <r> --kubeconfig <path> \" +\n \"[--base-domain <d>] [--ingress-address <ip>] [--platform-capacity] \" +\n \"[--backup-bucket <b> --backup-endpoint <url> --backup-access-key-id <k> --backup-secret-access-key <s>]\",\n undefined,\n \"bad_request\"\n );\n }\n if (provider !== \"gcp\" && provider !== \"aws\" && provider !== \"hetzner\") {\n fail(`--provider must be gcp, aws or hetzner (got \"${provider}\")`, undefined, \"bad_request\");\n }\n\n const backup = {\n backupBucket: flags[\"--backup-bucket\"],\n backupEndpoint: flags[\"--backup-endpoint\"],\n backupAccessKeyId: flags[\"--backup-access-key-id\"],\n backupSecretAccessKey: flags[\"--backup-secret-access-key\"]\n };\n const anyBackup = Boolean(backup.backupBucket || backup.backupAccessKeyId || backup.backupSecretAccessKey);\n if (anyBackup && !(backup.backupBucket && backup.backupAccessKeyId && backup.backupSecretAccessKey)) {\n fail(\n \"--backup-bucket, --backup-access-key-id and --backup-secret-access-key go together: a bucket \" +\n \"without a key, or a key without a bucket, is a cluster with NO backup store.\",\n undefined,\n \"bad_request\"\n );\n }\n if (provider === \"hetzner\" && flags[\"--platform-capacity\"] && !backup.backupBucket) {\n fail(\n \"A Hetzner cluster we operate needs its own backup store (--backup-bucket ... on Hetzner Object \" +\n \"Storage): without one its databases archive nowhere, or — worse — into the GCP default from \" +\n \"another provider.\",\n undefined,\n \"bad_request\"\n );\n }\n\n return {\n name: name!,\n provider,\n region: region!,\n kubeconfigPath: kubeconfigPath!,\n baseDomain: flags[\"--base-domain\"],\n ingressAddress: flags[\"--ingress-address\"],\n platformCapacity: flags[\"--platform-capacity\"] === true,\n ...(anyBackup ? backup : {})\n };\n}\n\nasync function clustersAddCommand(rawArgs: string[]): Promise<void> {\n const args = resolveClusterAddArgs(rawArgs);\n // Parsed before authenticating: a usage error is answerable without a\n // session, and asking for one first turns \"you forgot the id\" into \"log in\".\n const { client } = await requireClient(rawArgs);\n\n let kubeConfigData: string;\n try {\n kubeConfigData = fs.readFileSync(args.kubeconfigPath, \"utf8\");\n } catch {\n fail(`Could not read ${args.kubeconfigPath}`, undefined, \"bad_request\");\n return;\n }\n\n const { kubeconfigPath: _path, ...columns } = args;\n let created: { id: string | number };\n try {\n created = await client.data.collection(\"clusters\").create({\n ...columns,\n authType: \"kubeconfig\",\n kubeConfigData\n }) as never;\n } catch (error: unknown) {\n reportError(error, \"Could not register the cluster\");\n return;\n }\n\n emit(\n () => {\n success(`Registered ${args.name} (${created.id}).`);\n noteBlank();\n note(\"The cluster baseline (ingress, certificates, the database operator) is installing in the background.\");\n note(\"Verify it can host tenants:\");\n note(chalk.cyan(` rebase cloud clusters verify ${created.id} --baseline`));\n if (args.platformCapacity) {\n noteBlank();\n note(`Projects placed in ${args.region} now deploy here. Point *.${args.baseDomain ?? \"<baseDomain>\"} at ${args.ingressAddress ?? \"its ingress address\"} first.`);\n }\n },\n { id: created.id, name: args.name, provider: args.provider, region: args.region, platformCapacity: args.platformCapacity }\n );\n}\n\n/** The flags `clusters registry` declares; exported for its help page's test. */\nexport const CLUSTER_REGISTRY_FLAGS = {\n \"--repository\": String,\n \"--push-service-account\": String,\n \"--pull-key-file\": String,\n \"--clear\": Boolean\n};\n\n/**\n * What `clusters registry` was asked to record: a customer cluster's own image\n * repository, the account its builds push as, and the file holding the key of\n * its read-only account — or `--clear`, to go back to the shared registry.\n */\nexport type ClusterRegistryArgs =\n | { id: string; clear: true }\n | { id: string; clear: false; repository: string; pushServiceAccount: string; pullKeyFile: string };\n\n/**\n * Parse `rebase cloud clusters registry <id> …`.\n *\n * All three values or `--clear`, never a part: the control plane ignores a\n * partial set (and keeps handing the cluster the shared credentials), so a\n * command that wrote one would look done and change nothing.\n */\nexport function resolveClusterRegistryArgs(rawArgs: string[]): ClusterRegistryArgs {\n const { flags, positionals } = parseCloudArgs({\n spec: CLUSTER_REGISTRY_FLAGS,\n rawArgs,\n commandWords: 2, // cloud clusters — `registry` is the action positional\n command: \"cloud clusters registry\",\n maxPositionals: 2\n });\n const usage =\n \"Usage: rebase cloud clusters registry <cluster-id> --repository <host/project/repo> \" +\n \"--push-service-account <email> --pull-key-file <key.json> (or --clear)\";\n const id = positionals[1];\n if (!id) fail(usage, undefined, \"bad_request\");\n const repository = flags[\"--repository\"]?.trim();\n const pushServiceAccount = flags[\"--push-service-account\"]?.trim();\n const pullKeyFile = flags[\"--pull-key-file\"];\n if (flags[\"--clear\"] === true) {\n if (repository || pushServiceAccount || pullKeyFile) {\n fail(\"--clear takes no other registry flag.\", undefined, \"bad_request\");\n }\n return { id: id!, clear: true };\n }\n if (!repository || !pushServiceAccount || !pullKeyFile) {\n fail(`${usage}\\nAll three go together: the control plane ignores a partial set.`, undefined, \"bad_request\");\n }\n if (!/^[a-z0-9.-]+(:[0-9]+)?(\\/[a-z0-9]+([._-][a-z0-9]+)*){2,}$/.test(repository!.replace(/\\/+$/, \"\"))) {\n fail(`--repository must be <host>/<project>/<repository> (got \"${repository}\").`, undefined, \"bad_request\");\n }\n return { id: id!, clear: false, repository: repository!.replace(/\\/+$/, \"\"), pushServiceAccount: pushServiceAccount!, pullKeyFile: pullKeyFile! };\n}\n\n/**\n * The reader's key from `--pull-key-file`, checked before it leaves this\n * machine: a service-account key, and not the pusher's — the pull secret sits\n * where the customer's cluster admin can read it, so it must not be able to\n * write. Returns the key text and the account it belongs to.\n */\nexport function readPullKey(text: string, pushServiceAccount: string): { key: string; account: string } {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n fail(\"--pull-key-file is not JSON; it must be the reader service account's key file.\", undefined, \"bad_request\");\n }\n const record = typeof parsed === \"object\" && parsed !== null ? parsed as Record<string, unknown> : {};\n const account = record.client_email;\n if (typeof account !== \"string\" || typeof record.private_key !== \"string\") {\n fail(\"--pull-key-file has no client_email/private_key; it must be a service-account key file.\", undefined, \"bad_request\");\n }\n if ((account as string).toLowerCase() === pushServiceAccount.toLowerCase()) {\n fail(\"--pull-key-file is the push account's key. Use the cluster's read-only account (rlc-<key>-pull).\", undefined, \"bad_request\");\n }\n return { key: text.trim(), account: account as string };\n}\n\n/**\n * Record (or clear) a cluster's own image registry. Platform-admin only, like\n * the rest of `clusters`: the collection is admin-only. The key is sealed by\n * the control plane at write and never read back.\n */\nasync function clustersRegistryCommand(rawArgs: string[]): Promise<void> {\n const args = resolveClusterRegistryArgs(rawArgs);\n let columns: Record<string, string | null>;\n let pullAccount: string | null = null;\n if (args.clear) {\n columns = { tenantRegistry: null, registryPushServiceAccount: null, registryPullKey: null };\n } else {\n let text: string;\n try {\n text = fs.readFileSync(args.pullKeyFile, \"utf8\");\n } catch {\n fail(`Could not read ${args.pullKeyFile}`, undefined, \"bad_request\");\n return;\n }\n const pull = readPullKey(text, args.pushServiceAccount);\n pullAccount = pull.account;\n columns = { tenantRegistry: args.repository, registryPushServiceAccount: args.pushServiceAccount, registryPullKey: pull.key };\n }\n\n const { client } = await requireClient(rawArgs);\n try {\n await client.data.collection(\"clusters\").update(args.id, columns);\n } catch (error: unknown) {\n reportError(error, \"Could not record the cluster's registry\");\n return;\n }\n\n emit(\n () => {\n if (args.clear) {\n success(`Cluster ${args.id} uses the shared registry again.`);\n note(\"Deploys to it warn again if it is not platform capacity.\");\n return;\n }\n success(`Cluster ${args.id} now builds into ${args.repository}.`);\n noteBlank();\n note(`Builds push as ${args.pushServiceAccount}; pods pull with ${pullAccount}'s key (sealed, never shown).`);\n note(\"Takes effect on each project's next deploy to it.\");\n },\n args.clear\n ? { id: args.id, tenantRegistry: null, registryPushServiceAccount: null, pullServiceAccount: null }\n : { id: args.id, tenantRegistry: args.repository, registryPushServiceAccount: args.pushServiceAccount, pullServiceAccount: pullAccount }\n );\n}\n\nasync function clustersListCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud clusters\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n try {\n const clusters = (await client.data.collection(\"clusters\").find({ limit: 100 })).data as Array<{\n id: string | number;\n name?: string;\n provider?: string;\n region?: string;\n status?: string;\n }>;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(\" ☸ Clusters\"));\n console.log(\"\");\n if (clusters.length === 0) {\n console.log(chalk.gray(\" No clusters registered.\"));\n console.log(\"\");\n return;\n }\n for (const c of clusters) {\n console.log(` ${chalk.bold(c.name ?? \"(unnamed)\")} ${chalk.gray(`[${c.id}]`)} ${colorStatus(c.status)}`);\n keyValues([[\"Provider\", c.provider], [\"Region\", c.region]]);\n }\n console.log(\"\");\n },\n {\n clusters: clusters.map((c) => ({\n id: String(c.id),\n name: c.name ?? null,\n provider: c.provider ?? null,\n region: c.region ?? null,\n status: c.status ?? null\n }))\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list clusters\");\n }\n}\n\n/* ─── billing ──────────────────────────────────────────────────── */\n\n/**\n * The action words `rebase cloud billing` dispatches. No word at all is the\n * account view, which is why it is not in the list.\n *\n * Exported because `action-help.test.ts` holds the page's usage line to it: the\n * page said `cloud billing [portal|usage]` and the dispatch answered `setup` and\n * `checkout`, so both documented words fell through to the default and printed\n * the account — a help page describing a command that does not exist, and a typo\n * exiting 0.\n */\nexport const BILLING_ACTIONS = [\"setup\", \"checkout\", \"invoices\", \"upcoming\"] as const;\n\nexport async function billingCommand(rawArgs: string[]): Promise<void> {\n // Parsed before the client is built: an unusable line should be refused\n // without first spending a login round-trip on it.\n const parsed = parseCloudArgs({\n spec: { \"--limit\": Number },\n rawArgs,\n commandWords: 2, // cloud billing\n command: \"cloud billing\",\n maxPositionals: 1\n });\n const action = parsed.positionals[0];\n requireKnownAction(\"billing\", action, BILLING_ACTIONS);\n const limit = parsed.flags[\"--limit\"];\n if (limit !== undefined && action !== \"invoices\") {\n fail(\"`--limit` applies to `rebase cloud billing invoices` only.\", undefined, \"usage\");\n }\n\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n\n // `rebase cloud billing invoices|upcoming` — what Stripe has invoiced the\n // org, and what it will invoice next. Read-only; owner/admin only.\n if (action === \"invoices\" || action === \"upcoming\") {\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\", \"no_org\");\n try {\n if (action === \"invoices\") await billingInvoices(client, org, limit);\n else await billingUpcoming(client, org);\n } catch (e) {\n reportError(e, action === \"invoices\" ? \"Failed to load invoices\" : \"Failed to load the next invoice\");\n }\n return;\n }\n\n // `rebase cloud billing setup` — attach a card to the org (one-time, opens a\n // browser). Once done, project create/deploy work headlessly (off_session).\n if (action === \"setup\") {\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\", \"no_org\");\n try {\n const res = await client.functions.invoke<{ url?: string; simulated?: boolean }>(\n \"stripe-billing\",\n { organizationId: org },\n { path: \"setup-session\" }\n );\n if (!res.url) fail(\"Could not start billing setup.\", undefined, \"billing_setup_failed\");\n openUrl(res.url, \"Add a payment method in your browser:\");\n emit(\n () => {\n note(chalk.gray(res.simulated\n ? \"(dev mode — Stripe not configured; complete setup from the console)\"\n : \"Once you've added a card, `rebase cloud deploy` runs without further prompts.\"));\n noteBlank();\n },\n { url: res.url,\norg,\nsimulated: Boolean(res.simulated) }\n );\n } catch (e) {\n reportError(e, \"Failed to start billing setup\");\n }\n return;\n }\n\n // `rebase cloud billing checkout --project <slug>` opens a Stripe session.\n if (action === \"checkout\") {\n const projectId = await requireProject(rawArgs, client);\n try {\n const res = await client.functions.invoke<{ url?: string }>(\n \"stripe-billing\",\n { projectId },\n { path: \"session\" }\n );\n if (!res.url) fail(\"Billing session could not be created.\", undefined, \"checkout_failed\");\n emit(\n () => {\n console.log(\"\");\n console.log(\" Complete checkout in your browser:\");\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\n },\n { url: res.url,\nprojectId }\n );\n } catch (e) {\n reportError(e, \"Failed to start checkout\");\n }\n return;\n }\n\n // default: show the active org's billing account.\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\", \"no_org\");\n try {\n const billingId = billingAccountIdOf(await client.data.collection(\"organizations\").findById(org));\n if (!billingId) {\n // Not an error — an org simply may not have been billed yet.\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.gray(` Organization ${org} has no billing account yet.`));\n console.log(\"\");\n },\n { org,\naccount: null,\nmonthlyEur: null,\npaymentMethod: null }\n );\n return;\n }\n const acct = (await client.data.collection(\"billing-accounts\").findById(billingId)) as\n | { id: string | number; billingEmail?: string; status?: string; stripeCustomerId?: string }\n | undefined;\n\n // Card-on-file lives in Stripe; the control plane reports it for us.\n let card: { hasPaymentMethod?: boolean; brand?: string; last4?: string; expMonth?: number; expYear?: number } = {};\n try {\n card = await client.functions.invoke<typeof card>(\n \"stripe-billing\",\n undefined,\n { method: \"GET\",\npath: `payment-method/${org}` }\n );\n } catch {\n // status endpoint optional — fall back to the local account record\n }\n\n // Best-effort: what the linked/`--project` project costs per month.\n //\n // This used to name a plan, and before that a `compute_<provider>_<vmSize>`\n // price — a key for a machine on a price list this platform does not buy\n // from, which stopped resolving when `vmSize` was removed and printed a\n // bare label ever since. A project is priced from its dials now, so the\n // honest thing to show is the number the control plane would invoice.\n let monthly: string | undefined;\n try {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n const ref = parsed[\"--project\"] || readLink()?.projectId;\n const projectId = ref ? await lookupProjectId(ref, client) : undefined;\n if (projectId) {\n const proj = (await client.data.collection(\"projects\").findById(projectId)) as\n | Record<string, unknown>\n | undefined;\n const hasCluster = proj?.cluster_id != null || proj?.cluster != null;\n // `path` rather than a slash in the NAME: the SDK URL-encodes\n // the function name, so \"pricing/quote\" became \"pricing%2Fquote\"\n // and the route 404'd — every time, since this shipped. The\n // console's copy of this call carries the same note and gets it\n // right.\n const quote = await client.functions.invoke<ResourceQuote>(\n \"pricing\",\n proj,\n { method: \"POST\", path: \"quote\" }\n );\n monthly = `€${quote.totalEur.toFixed(2)}/mo`;\n if (hasCluster) monthly = `${monthly} — platform fee, your own cluster`;\n }\n } catch (err: unknown) {\n // Say which of the two it was. A bare `catch {}` reporting \"a\n // control plane without the quote endpoint\" is what made a\n // permanent 404 look like an expected condition for this command's\n // whole life.\n if (wantsRawError()) {\n console.error(` (no price: ${err instanceof Error ? err.message : String(err)})`);\n }\n }\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 💳 Billing — org ${org}`));\n console.log(\"\");\n keyValues([\n [\"Account\", acct ? String(acct.id) : undefined],\n [\"Email\", acct?.billingEmail],\n [\"Status\", acct?.status ? colorStatus(acct.status) : undefined],\n [\"Resources\", monthly],\n [\n \"Payment method\",\n card.hasPaymentMethod\n ? `${card.brand ?? \"card\"} •••• ${card.last4 ?? \"????\"}${card.expMonth ? ` (exp ${card.expMonth}/${card.expYear})` : \"\"}`\n : chalk.yellow(\"none — run `rebase cloud billing setup`\")\n ]\n ]);\n console.log(\"\");\n },\n {\n org,\n account: acct\n ? { id: String(acct.id),\nbillingEmail: acct.billingEmail ?? null,\nstatus: acct.status ?? null }\n : null,\n monthlyEur: monthly ?? null,\n paymentMethod: {\n hasPaymentMethod: Boolean(card.hasPaymentMethod),\n brand: card.brand ?? null,\n last4: card.last4 ?? null,\n expMonth: card.expMonth ?? null,\n expYear: card.expYear ?? null\n }\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load billing\");\n }\n}\n\n/* ─── compute: what this project reserves ───────────────────────── */\n\n/**\n * The action words `rebase cloud compute` dispatches. No word, or `show`,\n * prints the dials and the quote.\n */\nexport const COMPUTE_ACTIONS = [\"show\", \"set\"] as const;\n\n/** The dials, and the flag that sets each. */\nconst DIAL_FLAGS = {\n \"--cpu\": \"cpu\",\n \"--memory\": \"memory\",\n \"--replicas\": \"replicaCount\",\n \"--spot\": \"preemptible\",\n // No `--scale-to-zero`: see RETIRED_SCALE_TO_ZERO.\n // No `--db-mode`. The shared tier was retired, so a managed database is a\n // CloudNativePG cluster of the project's own and there is nothing left to\n // choose — a flag whose only legal value is the default is a flag that\n // changes nothing. The database is still dialable, by size and instances.\n \"--db-instances\": \"databaseInstances\",\n \"--db-cpu\": \"databaseCpu\",\n \"--db-memory\": \"databaseMemory\",\n \"--storage\": \"storageMode\",\n // Autoscaling is a RANGE, and `--replicas` is its floor rather than a\n // separate concept: with a max set, the floor is what always exists and what\n // the project is billed for at rest, and the max is the ceiling it may reach\n // and the worst case it may be billed. Deliberately not a `--autoscale\n // on|off` boolean — that would admit the incoherent state where autoscaling\n // is enabled and the range is a single point. A max at or below the floor\n // turns it off, which is the one rule `resolveAutoscaling` enforces.\n \"--autoscale-max\": \"autoscaleMaxReplicas\",\n \"--autoscale-cpu-target\": \"autoscaleTargetCpuPercent\"\n} as const;\n\n/**\n * The flags `resources set` accepts, in the shape a spec is written in.\n *\n * Derived from `DIAL_FLAGS` rather than written out beside it: `action-help.ts`\n * documents this command and `action-help.test.ts` pairs the page against this\n * constant, so a dial added above is a dial the help page has to describe on the\n * same commit. A hand-copied second list is how the page and the parser drift.\n *\n * `buildDialPatch` still scans `rawArgs` itself — it has to, because\n * `--no-autoscale` is value-less and a dial's value may not be consumed as one\n * — so this is a description of that line, not a second parser for it.\n */\nexport const COMPUTE_SET_FLAGS: Record<string, unknown> = {\n ...Object.fromEntries(Object.keys(DIAL_FLAGS).map((flag) => [flag, String])),\n \"--no-autoscale\": Boolean\n};\n\n/**\n * The flag that used to set `scaleToZero`. Still parsed, so a script that passes\n * it is told what happened rather than failing on an unknown option.\n *\n * The dial never did anything: it resolved to a request-billed substrate no\n * deploy built, and every backend kept running as an always-on pod. The control\n * plane refuses `true` now; this refuses it before the round trip, and lets\n * `false` — what every project already gets — through with a warning.\n */\nexport const RETIRED_SCALE_TO_ZERO = \"--scale-to-zero\";\n\n/** Dials whose column is a number, not the text a flag carries. */\nconst NUMERIC_DIALS = new Set([\n \"databaseInstances\",\n \"replicaCount\",\n \"autoscaleMaxReplicas\",\n \"autoscaleTargetCpuPercent\"\n]);\n/** Dials that are a yes/no. `--spot false` has to reach the row as `false`. */\nconst BOOLEAN_DIALS = new Set([\"preemptible\"]);\n\n/**\n * `rebase cloud compute` — show what a project reserves, and change it.\n *\n * Named for what it shows — CPU, memory, replicas, the database's shape, and\n * what those cost — because `rebase resources` already means the graph a\n * project declares, and two commands called \"resources\" that show different\n * things is a support ticket.\n *\n * ## Why nothing is validated here\n *\n * The rules are the *target cluster's*, not the CLI's: GKE Autopilot bills a\n * 250m/512Mi floor and rewrites anything outside a 1:1–6.5:1 memory:CPU band,\n * while a Hetzner or EKS node has neither constraint. A CLI that carried those\n * numbers would be wrong for two of the three providers the moment it shipped,\n * and would drift from the control plane the first time either changed.\n *\n * So the control plane validates and this reports what it said. The same\n * boundary refuses a raw PATCH and a console save, which is the property worth\n * having — a check in a client only covers the clients that run it.\n */\nexport async function computeCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n // `compute et --cpu 500m` used to SHOW the dials and exit 0, so a caller\n // that meant to change one was told what it currently is and nothing else.\n requireKnownAction(\"compute\", action, COMPUTE_ACTIONS);\n // `set` is described by `COMPUTE_SET_FLAGS`, which is derived from\n // `DIAL_FLAGS`; `buildDialPatch` still reads the values itself, because\n // `--no-autoscale` is value-less. This parse is only the refusal: without\n // it `compute set --cpu-request 500m` set nothing and reported success.\n parseCloudArgs({\n // The retired flag is parsed but not documented: `buildDialPatch` says\n // what became of it.\n spec: (action === \"set\" ? { ...COMPUTE_SET_FLAGS, [RETIRED_SCALE_TO_ZERO]: String } : {}) as Record<string, never>,\n rawArgs,\n commandWords: 3,\n command: action === \"set\" ? \"cloud compute set\" : \"cloud compute\",\n maxPositionals: 0\n });\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n const project = (await client.data.collection(\"projects\").findById(projectId)) as\n | Record<string, unknown>\n | undefined;\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`, undefined, \"not_found\");\n\n if (action !== \"set\") {\n // What this costs, priced by the control plane. Best-effort: an older\n // control plane has no quote endpoint, and a resources listing that\n // fails because a price could not be fetched would be worse than one\n // without the price.\n let quote: ResourceQuote | undefined;\n try {\n // See the note at the other call site: the name is \"pricing\" and the\n // sub-path is an option, because the SDK encodes the name.\n quote = await client.functions.invoke<ResourceQuote>(\n \"pricing\", project, { method: \"POST\", path: \"quote\" });\n } catch (err: unknown) {\n // No quote — the dials below are still the answer to the question\n // asked. Visible under REBASE_DEBUG, so a permanent failure cannot\n // masquerade as a control plane that simply does not price.\n if (wantsRawError()) {\n console.error(` (no price: ${err instanceof Error ? err.message : String(err)})`);\n }\n }\n\n emit(\n () => {\n console.log(\"\");\n console.log(` ${chalk.bold(String(project!.name ?? \"\"))} ${chalk.gray(`[${String(project!.subdomain ?? \"\")}]`)}`);\n console.log(\"\");\n keyValues([\n [\"App CPU\", dialLine(project!.cpu)],\n [\"App memory\", dialLine(project!.memory)],\n [\"App replicas\", dialLine(project!.replicaCount)],\n [\"Capacity\", dialLine(project!.preemptible, { true: \"spot\", false: \"on demand\" })],\n [\"Database instances\", dialLine(project!.databaseInstances)],\n [\"Database CPU\", dialLine(project!.databaseCpu)],\n [\"Database memory\", dialLine(project!.databaseMemory)],\n [\"Object storage\", dialLine(project!.storageMode)],\n [\"Per month\", quote ? `€${quote.totalEur.toFixed(2)}` : undefined]\n ]);\n // Itemised, because a total nobody can decompose is a number\n // someone has to trust rather than check.\n if (quote) {\n console.log(\"\");\n for (const line of quote.lines) {\n const qty = line.unit ? chalk.gray(`${line.quantity} × €${line.unitEur}`) : \"\";\n note(` ${line.label.padEnd(24)} ${qty.padEnd(28)} €${line.amountEur.toFixed(2)}`);\n }\n }\n console.log(\"\");\n noteBlank();\n note(\"Empty means the platform default. Change one with:\");\n note(chalk.cyan(\" rebase cloud compute set --cpu 500m --memory 2Gi\"));\n console.log(\"\");\n },\n {\n monthlyEur: quote?.totalEur ?? null,\n lines: quote?.lines ?? null,\n cpu: project!.cpu ?? null,\n memory: project!.memory ?? null,\n replicaCount: project!.replicaCount ?? null,\n preemptible: project!.preemptible ?? null,\n // Retired: always null since the control plane cleared the\n // column. Kept so a script reading the field does not break.\n scaleToZero: project!.scaleToZero ?? null,\n databaseInstances: project!.databaseInstances ?? null,\n databaseCpu: project!.databaseCpu ?? null,\n databaseMemory: project!.databaseMemory ?? null,\n storageMode: project!.storageMode ?? null\n }\n );\n return;\n }\n\n const built = buildDialPatch(rawArgs);\n if (built.error) fail(built.error, undefined, \"bad_request\");\n const patch = built.patch;\n\n try {\n await client.data.collection(\"projects\").update(projectId, patch);\n } catch (error: unknown) {\n // The control plane's refusals are written to be read by whoever chose\n // the number — a ratio named, a field named — so they are surfaced\n // verbatim rather than replaced with a generic failure.\n reportError(error, \"Could not change resources\");\n return;\n }\n\n emit(\n () => {\n success(\"Resources updated.\");\n noteBlank();\n for (const [field, value] of Object.entries(patch)) {\n note(` ${field} → ${String(value)}`);\n }\n noteBlank();\n note(\"Applied now: the app rolls its pods and your subscription is prorated from today.\");\n note(\"A change that restarts the database waits for a maintenance window.\");\n },\n { updated: patch }\n );\n}\n\n/** What the control plane says a set of dials costs, itemised. */\ninterface ResourceQuote {\n lines: { lookupKey: string; label: string; quantity: number; unit?: string; unitEur: number; amountEur: number }[];\n totalEur: number;\n}\n\n/**\n * A dial's value, or a marker that the platform default decides it.\n *\n * The two are different states and the distinction is not cosmetic: an unset\n * dial follows the default and moves if it does, while one pinned to the same\n * number will not. Printing the inherited value would make them identical on\n * screen.\n */\nfunction dialLine(value: unknown, labels?: Record<string, string>): string {\n if (value === null || value === undefined || value === \"\") return chalk.gray(\"default\");\n const key = String(value);\n return labels?.[key] ?? key;\n}\n\n/**\n * Turn `--cpu 500m --db-instances 2` into the patch to send.\n *\n * Pure, and exported, so the flag handling is testable without a control plane —\n * the same shape `buildSettingsPatch` uses. Returns an error string rather than\n * throwing, because the caller owns how a refusal is printed in JSON mode.\n */\nexport function buildDialPatch(\n rawArgs: string[],\n /**\n * `requireOne: false` for `projects create`, where naming no dial is the\n * ordinary case — a new project takes the platform default. On\n * `compute set` a patch with nothing in it is a typo, and saying so beats\n * a success message for a change nobody made.\n */\n opts?: { requireOne?: boolean }\n): { patch: Record<string, unknown>; error?: string } {\n const patch: Record<string, unknown> = {};\n\n // A value-less flag, and the only way to turn autoscaling off.\n //\n // Setting the ceiling down to the floor would also disable it, but the\n // control plane refuses that now: a row naming a ceiling that resolves to no\n // autoscaler is a state nothing reads back correctly, and it used to happen\n // silently — `--replicas 5` on a project whose ceiling was 5 deleted the\n // HPA, left the ceiling on the row, and said nothing.\n // Read as the parser reads a switch: `=true`/`=1` on, `=false`/`=0` off.\n if (switchOn(rawArgs, \"--no-autoscale\")) {\n patch.autoscaleMaxReplicas = null;\n patch.autoscaleTargetCpuPercent = null;\n }\n\n const retired = rawArgs.indexOf(RETIRED_SCALE_TO_ZERO);\n if (retired !== -1) {\n const value = rawArgs[retired + 1];\n if (value === undefined || value.startsWith(\"--\")) {\n return { patch: {}, error: `${RETIRED_SCALE_TO_ZERO} needs a value.` };\n }\n if (!/^(false|0|no|off)$/i.test(value.trim())) {\n return {\n patch: {},\n error: \"Scale to zero is not available: every backend runs as an always-on pod. \"\n + \"Set the floor with --replicas and a ceiling with --autoscale-max.\"\n };\n }\n warn(`${RETIRED_SCALE_TO_ZERO} is no longer a setting and was ignored.`,\n \"Every backend runs as an always-on pod; drop the flag.\");\n }\n\n for (const [flag, field] of Object.entries(DIAL_FLAGS)) {\n const idx = rawArgs.indexOf(flag);\n if (idx === -1) continue;\n const value = rawArgs[idx + 1];\n // A flag followed by another flag is a missing value, not an empty one.\n // Silently sending \"\" would clear the dial — the opposite of what\n // someone who fumbled a flag meant.\n if (value === undefined || value.startsWith(\"--\")) {\n return { patch: {}, error: `${flag} needs a value.` };\n }\n if (NUMERIC_DIALS.has(field)) {\n const n = Number(value);\n if (!Number.isInteger(n)) {\n return { patch: {}, error: `${flag} takes a whole number, not \"${value}\".` };\n }\n // Sent as a number, not a string. The control plane decides whether\n // anything CHANGED by comparing against the stored value — and it\n // re-syncs a Stripe subscription and rolls a tenant's pods when\n // something did. \"2\" against 2 differs, so a string here would turn\n // every unrelated save into a resize.\n patch[field] = n;\n } else if (BOOLEAN_DIALS.has(field)) {\n if (value !== \"true\" && value !== \"false\") {\n return { patch: {}, error: `${flag} takes true or false, not \"${value}\".` };\n }\n // The string \"false\" is truthy, and would put a project that asked\n // for on-demand capacity onto preemptible nodes at a third of the\n // price — with restarts it explicitly declined.\n patch[field] = value === \"true\";\n } else {\n patch[field] = value;\n }\n }\n\n if (opts?.requireOne !== false && Object.keys(patch).length === 0) {\n return {\n patch: {},\n error: `Nothing to set. Pass one of: ${Object.keys(DIAL_FLAGS).join(\", \")}, --no-autoscale.`\n };\n }\n return { patch };\n}\n","/**\n * `rebase cloud db connect` — a local port that is your cloud database.\n *\n * ## What this replaces\n *\n * A managed database lives in a namespace of the platform's cluster, and its\n * address (`postgres-rw.rebase-tenant-….svc.cluster.local`) resolves to nothing\n * on a developer's machine. The console used to bridge that gap by printing\n *\n * kubectl port-forward svc/postgres-rw -n rebase-tenant-… 5432:5432\n *\n * which nobody outside the platform can run: a tenant of Rebase Cloud has no\n * kubeconfig for our cluster, and there is no product that sells one. So the\n * platform reaches into the cluster instead, and this command is the local end\n * of that reach.\n *\n * ## How it works\n *\n * A listener on 127.0.0.1. Every TCP connection it accepts opens its own\n * WebSocket to the control plane, authenticates in-band with the console session\n * this CLI already holds, and from `ready` onwards the two are a byte pipe. The\n * database still asks for a password — the tunnel is a network path, not a\n * credential — so `psql` behaves exactly as it would against a local Postgres.\n *\n * One WebSocket per connection rather than one multiplexed socket: `psql` is one\n * connection and a pool is a handful, and per-connection sockets keep the\n * framing at \"these bytes are those bytes\" with no stream ids to get wrong.\n *\n * Node's global `WebSocket` is used rather than `ws`, which is why the token\n * goes in the first frame instead of an `Authorization` header — the WHATWG\n * client cannot set request headers, and a header-only endpoint would be\n * unreachable from a browser too.\n */\nimport net from \"node:net\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n parseCloudArgs,\n emit,\n fail,\n freshAccessToken,\n note,\n noteBlank,\n reportError,\n warn,\n type SessionHolder\n} from \"./context\";\n\n/** Documented in `action-help.ts`, and paired with it by `action-help.test.ts`. */\nexport const DB_CONNECT_FLAGS = {\n \"--port\": Number,\n \"--reveal\": Boolean\n} as const;\n\n/** What `db-info` answers. Mirrors `saas/backend/functions/db-info.ts`. */\ninterface DbInfoResponse {\n type: \"managed\" | \"byodb\";\n host: string | null;\n port: string | null;\n database: string | null;\n username: string | null;\n passwordAvailable: boolean;\n directAccess: {\n via: \"tunnel\";\n kubectl?: { namespace: string; service: string; localPort: number; remotePort: number };\n } | null;\n unavailableReason: string | null;\n}\n\n/** The default, because it is what every Postgres client assumes. */\nconst DEFAULT_LOCAL_PORT = 5432;\n\n/**\n * The handshake, which is the only thing the tunnel says in words.\n *\n * After `ready` every frame is bytes, so a text frame arriving later is not a\n * frame of ours at all — it is a proxy answering in the control plane's place.\n */\ntype TunnelFrame =\n | { type: \"ready\" }\n | { type: \"error\"; code?: string; message?: string };\n\n/** `https://app.rebase.pro` → `wss://app.rebase.pro/api/db-tunnel/p1`. */\nexport function tunnelUrl(cloudUrl: string, projectId: string): string {\n const url = new URL(cloudUrl);\n url.protocol = url.protocol === \"http:\" ? \"ws:\" : \"wss:\";\n // Replaced rather than appended: a control-plane URL carrying a path would\n // otherwise produce `/base/api/db-tunnel/...`, and the route is mounted at\n // the root of the host.\n url.pathname = `/api/db-tunnel/${encodeURIComponent(projectId)}`;\n url.search = \"\";\n return url.toString();\n}\n\n/**\n * A local DSN for the tunnel, with the password only if the caller asked.\n *\n * Built here and nowhere else. The server reports the *cluster's* URI, which is\n * the one thing that must not be printed as the way to connect — it is exactly\n * the address that does not work from here.\n */\nexport function localDsn(opts: {\n port: number;\n username: string | null;\n database: string | null;\n password?: string;\n}): string {\n const user = opts.username ? encodeURIComponent(opts.username) : \"postgres\";\n const auth = opts.password ? `${user}:${encodeURIComponent(opts.password)}` : user;\n const database = opts.database ?? \"rebase\";\n return `postgresql://${auth}@127.0.0.1:${opts.port}/${database}`;\n}\n\nexport async function dbConnect(rawArgs: string[]): Promise<void> {\n const { flags: args } = parseCloudArgs({\n spec: DB_CONNECT_FLAGS,\n rawArgs,\n commandWords: 3, // cloud db connect\n command: \"cloud db connect\",\n maxPositionals: 0\n });\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n let info: DbInfoResponse;\n try {\n info = await client.functions.invoke<DbInfoResponse>(\"db-info\", undefined, {\n method: \"GET\",\n path: projectId\n });\n } catch (e) {\n return reportError(e, \"Failed to load database info\");\n }\n\n if (info.type === \"byodb\") {\n fail(\n \"This project uses your own database.\",\n \"Connect to it directly — there is nothing for the platform to tunnel.\",\n \"byodb\"\n );\n }\n if (!info.directAccess) {\n fail(\n \"The platform could not resolve this project's database, so it cannot open a path to it.\",\n info.unavailableReason ??\n \"A managed database is provisioned at the project's first deploy; before then there is nothing to connect to.\",\n \"db_unavailable\"\n );\n }\n\n // Asked for before the listener opens: a prompt-free failure is better than\n // a tunnel that works and a URL the caller cannot use.\n let password: string | undefined;\n if (args[\"--reveal\"]) {\n if (!info.passwordAvailable) {\n fail(\n \"No password is available to reveal for this database.\",\n info.unavailableReason ?? undefined,\n \"password_unavailable\"\n );\n }\n try {\n password = (\n await client.functions.invoke<{ password: string }>(\"db-info\", { projectId }, { path: \"reveal\" })\n ).password;\n } catch (e) {\n return reportError(e, \"Failed to reveal the database password\");\n }\n }\n\n const requested = args[\"--port\"] ?? DEFAULT_LOCAL_PORT;\n if (!Number.isInteger(requested) || requested < 0 || requested > 65535) {\n fail(`--port must be a port number, not ${requested}.`, undefined, \"bad_port\");\n }\n\n const server = tunnelListener(client, tunnelUrl(url, projectId));\n\n server.on(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\") {\n fail(\n `Port ${requested} on 127.0.0.1 is already in use.`,\n \"Pass --port to choose another, or stop whatever is listening there.\",\n \"port_in_use\"\n );\n }\n fail(`Could not open a local listener: ${err.message}`, undefined, \"listen_failed\");\n });\n\n await new Promise<void>((resolve) => {\n server.listen(requested, \"127.0.0.1\", () => resolve());\n });\n\n const address = server.address();\n const port = address && typeof address !== \"string\" ? address.port : requested;\n const dsn = localDsn({ port, username: info.username, database: info.database, password });\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔌 Tunnel open — project ${projectRef}`));\n console.log(\"\");\n console.log(` ${chalk.green(dsn)}`);\n console.log(\"\");\n if (!password) {\n console.log(\n chalk.gray(\" The password is hidden. Re-run with --reveal to print it in the URL,\")\n );\n console.log(chalk.gray(\" or read it with `rebase cloud db info --reveal`.\"));\n console.log(\"\");\n }\n console.log(chalk.gray(\" Leave this running, and point any Postgres client at it.\"));\n console.log(chalk.gray(\" Ctrl-C closes the tunnel.\"));\n console.log(\"\");\n },\n {\n projectId,\n host: \"127.0.0.1\",\n port,\n database: info.database,\n username: info.username,\n connectionString: dsn,\n // Only present when explicitly revealed, exactly as `db info` does.\n ...(password ? { password } : {})\n }\n );\n\n // The command IS the tunnel: it holds the terminal until the developer is\n // done. `once` rather than `on`, so a second Ctrl-C kills the process\n // instead of queueing another shutdown.\n await new Promise<void>((resolve) => {\n process.once(\"SIGINT\", () => {\n noteBlank();\n note(chalk.gray(\"Tunnel closed.\"));\n // Not awaited: `server.close` waits for established connections to\n // end, and the developer just asked to stop rather than to drain.\n server.close();\n resolve();\n });\n });\n}\n\n/**\n * The local listener: each connection it accepts gets its own tunnel, signed in\n * with a token that is current when the connection arrives.\n *\n * The command is left running for as long as the developer works, and the\n * access token it started with lapses within the hour. Every connection is\n * authenticated on its own, so each one reads the token then, refreshing it\n * first when it is close to expiry — rather than the one read at startup, which\n * the control plane refuses for every connection opened after it expires.\n *\n * The socket is paused while the token is read, so a client's first bytes wait\n * for the tunnel exactly as they do once it is being established.\n */\nexport function tunnelListener(client: SessionHolder, endpoint: string): net.Server {\n return net.createServer((socket) => {\n socket.pause();\n freshAccessToken(client).then(\n (token) => {\n if (!socket.destroyed) pipeThroughTunnel(socket, endpoint, token);\n },\n () => {\n warn(\n \"A connection was closed: the session this tunnel signs in with has expired and could not be refreshed.\",\n \"Run `rebase cloud login`, then connect again.\"\n );\n socket.destroy();\n }\n );\n });\n}\n\n/**\n * One accepted connection, carried over one WebSocket.\n *\n * The local socket is paused until the tunnel says `ready`, so a client that\n * sends its startup packet the instant it connects — which every Postgres\n * client does — cannot have those bytes arrive before there is a database to\n * send them to.\n *\n * Exported for `db-connect.pipe.test.ts`, which drives it with a real socket\n * against a real WebSocket: this is the half a developer's client actually\n * talks to, and a pipe is the one component whose bugs are silent — a dropped\n * or reordered chunk does not throw, it corrupts a Postgres message and\n * surfaces as a protocol error nowhere near here.\n */\nexport function pipeThroughTunnel(socket: net.Socket, endpoint: string, token: string): void {\n socket.pause();\n socket.setNoDelay(true);\n\n const ws = new WebSocket(endpoint);\n ws.binaryType = \"arraybuffer\";\n let ready = false;\n\n const closeBoth = (reason?: string) => {\n if (reason && !ready) {\n // Only worth saying while the tunnel is being established: after\n // that, a close is a client disconnecting and is not news. A\n // warning, so it reaches stderr in JSON mode too: the connection\n // that was dropped belongs to a client nobody else is watching.\n warn(`A connection was refused: ${reason}`);\n }\n try {\n if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) ws.close();\n } catch {\n /* already gone */\n }\n socket.destroy();\n };\n\n ws.onopen = () => {\n ws.send(JSON.stringify({ type: \"authenticate\", token }));\n };\n\n ws.onmessage = (event: MessageEvent) => {\n if (typeof event.data === \"string\") {\n // Text frames are the handshake, and the server sends none after\n // `ready` — so anything unparseable here is a proxy or a gateway\n // answering in place of the control plane.\n let frame: TunnelFrame | null = null;\n try {\n frame = JSON.parse(event.data) as TunnelFrame;\n } catch {\n return closeBoth(`the tunnel endpoint answered with ${event.data.slice(0, 80)}`);\n }\n if (frame.type === \"ready\") {\n ready = true;\n socket.resume();\n return;\n }\n const refusal = frame.type === \"error\" ? frame : null;\n return closeBoth(\n refusal?.message ?? `the tunnel was refused (${refusal?.code ?? \"unknown\"})`\n );\n }\n socket.write(Buffer.from(event.data as ArrayBuffer));\n };\n\n ws.onerror = () => {\n closeBoth(\"could not reach the control plane's tunnel endpoint\");\n };\n ws.onclose = () => {\n socket.destroy();\n };\n\n socket.on(\"data\", (chunk: Buffer) => {\n if (ws.readyState !== WebSocket.OPEN) return;\n // The Uint8Array view is copied rather than sent as-is: `chunk` is a\n // slice of a shared read buffer, and sending the underlying\n // ArrayBuffer would put the whole of it on the wire.\n ws.send(new Uint8Array(chunk));\n if (ws.bufferedAmount > 1024 * 1024) {\n socket.pause();\n const drain = setInterval(() => {\n if (ws.readyState !== WebSocket.OPEN) return clearInterval(drain);\n if (ws.bufferedAmount < 256 * 1024) {\n clearInterval(drain);\n socket.resume();\n }\n }, 5);\n }\n });\n socket.on(\"close\", () => closeBoth());\n socket.on(\"error\", () => closeBoth());\n}\n","/**\n * `rebase cloud db` — database + backup management for a project.\n *\n * db list List databases attached to the project\n * db create Attach a managed or bring-your-own database\n * db info Where the database is, and what it is called\n * db connect A local port that IS the project's database\n * db test Test connectivity to the project's database\n * db backup list|create|restore\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n requireProject,\n requireKnownAction,\n displayProjectRef,\n parseCloudArgs,\n emit,\n printGroupHelp,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError,\n note,\n noteBlank,\n requireInteractive,\n resolveTimeoutMs,\n type CloudClient,\n cloudRows,\n requireCloudRow\n} from \"./context\";\nimport { dbConnect } from \"./db-connect\";\n\ninterface DatabaseRow {\n id: string | number;\n type?: string;\n connectionStatus?: string;\n useSshTunnel?: boolean;\n pitrEnabled?: boolean;\n}\n\n/**\n * One backup, as the control plane's `backup` function describes it.\n *\n * `name` is the filename `restore` and `download` take. `size` arrives already\n * formatted — \"12.34 MB\", or \"unknown\" when the platform could not read it —\n * and is printed as given. `filename` and a numeric `size` are read too, so a\n * row from any control plane renders.\n */\ninterface BackupRow {\n id?: string;\n name?: string;\n filename?: string;\n size?: string | number;\n type?: string;\n date?: string;\n status?: string;\n}\n\n/** The filename a backup is restored and downloaded by. */\nfunction backupName(row: BackupRow | undefined): string | undefined {\n return row?.name ?? row?.filename;\n}\n\n/** A backup's size for a person: the control plane's own string, or bytes as MB. */\nfunction backupSize(row: BackupRow): string | undefined {\n if (typeof row.size === \"string\") return row.size;\n if (typeof row.size === \"number\" && Number.isFinite(row.size)) return `${(row.size / 1024 / 1024).toFixed(1)} MB`;\n return undefined;\n}\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n switch (subcommand) {\n case \"list\":\n case undefined:\n await listDatabases(rawArgs);\n break;\n case \"create\":\n await createDatabase(rawArgs);\n break;\n case \"info\":\n await dbInfo(rawArgs);\n break;\n case \"connect\":\n await dbConnect(rawArgs);\n break;\n case \"test\":\n await testDatabase(rawArgs);\n break;\n case \"backup\":\n await backupCommand(rawArgs);\n break;\n case \"pitr\":\n await pitrCommand(rawArgs);\n break;\n case \"--help\":\n printDbHelp();\n break;\n default:\n fail(`Unknown db command: ${subcommand}`, \"Run `rebase cloud db --help`.\", \"unknown_command\");\n }\n}\n\nasync function listDatabases(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud db\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const dbs = cloudRows<DatabaseRow>((await client.data.collection(\"databases\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data);\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🗄 Databases — project ${projectRef}`));\n console.log(\"\");\n if (dbs.length === 0) {\n console.log(chalk.gray(\" No database attached. Add one with `rebase cloud db create`.\"));\n console.log(\"\");\n return;\n }\n for (const d of dbs) {\n console.log(` ${chalk.bold(d.type ?? \"unknown\")} ${chalk.gray(`[${d.id}]`)} ${colorStatus(d.connectionStatus)}`);\n keyValues([\n [\"SSH tunnel\", d.useSshTunnel ? \"yes\" : undefined],\n [\"PITR\", d.pitrEnabled ? \"enabled\" : undefined]\n ]);\n }\n console.log(\"\");\n },\n {\n projectId,\n databases: dbs.map((d) => ({\n id: String(d.id),\n type: d.type ?? null,\n connectionStatus: d.connectionStatus ?? null,\n useSshTunnel: Boolean(d.useSshTunnel),\n pitrEnabled: Boolean(d.pitrEnabled)\n }))\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list databases\");\n }\n}\n\n/**\n * The database already attached to a project, if any.\n *\n * `limit: 1` deliberately mirrors what the control plane's own `db-test`,\n * `db-info` and `backup` do — asking the same question the same way is the\n * point, since the answer decides which row a deploy will actually use.\n */\nasync function firstAttachedDatabase(\n client: CloudClient,\n projectId: string\n): Promise<DatabaseRow | undefined> {\n const rows = cloudRows<DatabaseRow>((await client.data.collection(\"databases\").find({\n where: { project: [\"==\", projectId] },\n limit: 1\n })).data);\n return rows[0];\n}\n\n/**\n * Attach a database row to a project.\n *\n * Extracted so `rebase cloud projects create` can do it in the same breath as\n * creating the project — see `--db` there. Two call sites, one insert, so the\n * shape of the row cannot drift between \"attached at creation\" and \"attached\n * afterwards\".\n */\nexport async function attachDatabaseRow(\n client: CloudClient,\n input: { projectId: string; type: string; connectionString?: string }\n): Promise<DatabaseRow> {\n return requireCloudRow<DatabaseRow>(await client.data.collection(\"databases\").create({\n project: input.projectId,\n type: input.type,\n connectionString: input.type === \"byodb\" ? input.connectionString : undefined,\n connectionStatus: \"untested\"\n }), \"database\");\n}\n\n/** What `rebase cloud db create` parses. Exported so its help page cannot drift. */\nexport const CREATE_DATABASE_FLAGS = {\n \"--type\": String,\n \"--connection-string\": String,\n \"--wait\": Boolean,\n \"--timeout\": String,\n \"--project\": String,\n \"-p\": \"--project\"\n} as const;\n\nasync function createDatabase(rawArgs: string[]): Promise<void> {\n // Strict, and through the family's parser: an undeclared flag used to be\n // dropped, so `db create --typ managed` opened the interactive picker —\n // or, off a terminal, refused for a type that had been given.\n const { flags: args } = parseCloudArgs({\n spec: CREATE_DATABASE_FLAGS,\n rawArgs,\n commandWords: 3, // cloud db create\n command: \"cloud db create\",\n maxPositionals: 0\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // A project has exactly one database, and the platform is built on that:\n // `db-test`, `db-info` and `backup` all read `databases` with `limit: 1`\n // and take whichever row comes back first. A second row therefore does not\n // add a database — it makes it *undefined* which one the project is\n // deployed against, silently, with no error anywhere.\n //\n // Cheap to reach now that `projects create` attaches one by default: the\n // obvious way to move a project to a bring-your-own database was to run\n // `db create --type byodb`, which used to be the only row and is now the\n // second. So this refuses rather than inserts, and names what is already\n // there.\n const existing = await firstAttachedDatabase(client, projectId);\n if (existing) {\n fail(\n `Project ${projectRef} already has a ${existing.type ?? \"database\"} attached (${existing.id}).`,\n \"A project has exactly one database. Remove that one first, or run \"\n + \"`rebase cloud db info` to see what it points at.\",\n \"database_exists\"\n );\n }\n\n let type = args[\"--type\"];\n if (!type) {\n requireInteractive(\"a database type\", \"--type <managed|byodb>\");\n const { picked } = await inquirer.prompt([\n {\n type: \"select\",\n name: \"picked\",\n message: \"Database type:\",\n choices: [\n { name: \"SaaS Managed (provisioned for you)\",\nvalue: \"managed\" },\n { name: \"Bring Your Own DB (external PostgreSQL)\",\nvalue: \"byodb\" }\n ]\n }\n ] as Parameters<typeof inquirer.prompt>[0]);\n type = picked as string;\n }\n\n let connectionString = args[\"--connection-string\"];\n if (type === \"byodb\" && !connectionString) {\n requireInteractive(\"a connection string\", \"--connection-string <url>\");\n const { cs } = await inquirer.prompt([\n { type: \"input\",\nname: \"cs\",\nmessage: \"PostgreSQL connection string:\" }\n ] as Parameters<typeof inquirer.prompt>[0]);\n connectionString = (cs as string)?.trim();\n if (!connectionString) {\n fail(\n \"A connection string is required for bring-your-own databases.\",\n \"Pass `--connection-string <url>`.\",\n \"input_required\"\n );\n }\n }\n\n let created: DatabaseRow;\n try {\n created = await attachDatabaseRow(client, { projectId,\ntype: type!,\nconnectionString });\n } catch (e) {\n reportError(e, \"Failed to attach database\");\n }\n\n // `--wait`, and the one honest thing it can do per type.\n //\n // A managed database is NOT provisioned here: the CloudNativePG cluster is\n // materialised at the project's first deploy. So there is nothing to poll,\n // and a `--wait` that polled would be the same trap this flag exists to\n // remove — a loop over a value that cannot change. It reports that instead,\n // and exits 0, because the attach did succeed.\n //\n // A bring-your-own database is the opposite: it exists right now, and\n // whether it is reachable is a real question with a real answer, so `--wait`\n // asks it until it gets one.\n const waited = args[\"--wait\"] === true\n ? await waitForDatabase(client, {\n projectId,\n type: type!,\n timeoutMs: resolveTimeoutMs(args[\"--timeout\"], {\n fallbackMs: DEFAULT_WAIT_MS,\n command: \"cloud db create\"\n })\n })\n : undefined;\n\n success(`Attached ${type} database to project ${projectRef}`);\n emit(\n () => {\n keyValues([[\"ID\", String(created.id)]]);\n if (waited?.note) note(chalk.gray(waited.note));\n else if (type === \"byodb\") note(chalk.gray(\"Verify it with `rebase cloud db test`.\"));\n else note(chalk.gray(\"It is created at your first deploy — run `rebase cloud deploy` next.\"));\n noteBlank();\n },\n {\n success: true,\n id: String(created.id),\n projectId,\n type,\n connectionStatus: waited?.connectionStatus ?? \"untested\",\n // What `--wait` actually waited for, so a caller can tell an\n // answered question from an unanswerable one.\n waited: waited ? waited.waited : false,\n materializedAt: type === \"managed\" ? \"first_deploy\" : \"now\"\n }\n );\n}\n\n/** How long `db create --wait` waits by default, and `--timeout` overrides. */\nconst DEFAULT_WAIT_MS = 5 * 60 * 1000;\n\nconst WAIT_POLL_MS = 3000;\n\n/**\n * Wait for an attached database to become usable, where \"usable\" means\n * something.\n *\n * Returns `waited: false` for the managed case, and says why — the caller then\n * knows the state it is looking at is final rather than early.\n */\nexport async function waitForDatabase(\n client: CloudClient,\n opts: { projectId: string; type: string; timeoutMs: number; pollMs?: number }\n): Promise<{ waited: boolean; connectionStatus: string; note?: string }> {\n if (opts.type !== \"byodb\") {\n return {\n waited: false,\n connectionStatus: \"untested\",\n note: \"Nothing to wait for: a managed database is created at the project's first deploy. \"\n + \"Run `rebase cloud deploy` next; `rebase cloud db test` only answers after that.\"\n };\n }\n\n const started = Date.now();\n for (;;) {\n try {\n const res = await client.functions.invoke<{ success: boolean }>(\"db-test\", { projectId: opts.projectId });\n if (res.success) return { waited: true,\nconnectionStatus: \"connected\" };\n } catch {\n // A transport failure is indistinguishable from a database that is\n // not up yet, and both are answered by trying again until the\n // deadline. The deadline is what makes that safe.\n }\n if (Date.now() - started > opts.timeoutMs) {\n fail(\n `The database did not become reachable within ${Math.round(opts.timeoutMs / 1000)}s.`,\n \"Run `rebase cloud db test` for the connection log.\",\n \"timeout\"\n );\n }\n await new Promise(resolve => setTimeout(resolve, opts.pollMs ?? WAIT_POLL_MS));\n }\n}\n\nasync function testDatabase(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud db\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n noteBlank();\n note(`Testing database connectivity for project ${chalk.bold(projectRef)}...`);\n try {\n const res = await client.functions.invoke<{ success: boolean; logs?: string }>(\"db-test\", { projectId });\n\n // The connection log is diagnostics, not the result, so it goes to\n // stderr — in both modes. Echoing it to stdout put arbitrary\n // server-generated text in front of whatever was parsing the output,\n // and on the failure path it is the only thing that explains WHY, so\n // suppressing it in JSON mode would have left the refusal below\n // pointing at logs that were never printed.\n if (res.logs) console.error(`\\n${res.logs}`);\n\n if (!res.success) {\n fail(\n \"Database connection failed.\",\n \"The connection log above (stderr) has the reason.\",\n \"db_connection_failed\"\n );\n }\n success(\"Database connection succeeded\");\n emit(() => {}, { success: true,\nprojectId,\nlogs: res.logs ?? null });\n } catch (e) {\n reportError(e, \"Failed to test database\");\n }\n}\n\n/* ─── db info ──────────────────────────────────────────────────── */\n\ninterface DbInfoResponse {\n type: \"managed\" | \"byodb\";\n host: string | null;\n port: string | null;\n database: string | null;\n username: string | null;\n passwordAvailable: boolean;\n /**\n * How the customer reaches this database from their own machine.\n *\n * This replaced a `portForward` field that was rendered as a `kubectl\n * port-forward -n rebase-tenant-…` line — a command whose prerequisite is a\n * kubeconfig for the platform's cluster, which no customer has and which\n * nothing here has ever issued. `kubectl` is present now only when the\n * cluster is the customer's own.\n */\n directAccess: {\n via: \"tunnel\";\n kubectl?: { namespace: string; service: string; localPort: number; remotePort: number };\n } | null;\n unavailableReason: string | null;\n}\n\n/**\n * `rebase cloud db info [--reveal]` — where a project's database actually lives.\n *\n * The password is NEVER in the default output; `--reveal` fetches it through the\n * separate reveal call, and it appears in JSON only when `--reveal` is given.\n * Any field the server could not resolve comes back `null` and is rendered as\n * unavailable, never a placeholder.\n */\nasync function dbInfo(rawArgs: string[]): Promise<void> {\n // `--project`/`-p` are globals and are not redeclared. Strict, so\n // `db info --revel` refuses instead of quietly masking the password it\n // was asked to show.\n const { flags: args } = parseCloudArgs({\n spec: { \"--reveal\": Boolean },\n rawArgs,\n commandWords: 3, // cloud db info\n command: \"cloud db\",\n maxPositionals: 0\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n try {\n const info = await client.functions.invoke<DbInfoResponse>(\"db-info\", undefined, { method: \"GET\",\npath: projectId });\n\n let password: string | undefined;\n let connectionString: string | undefined;\n if (args[\"--reveal\"]) {\n if (!info.passwordAvailable) {\n fail(\"No password is available to reveal for this database.\", info.unavailableReason ?? undefined, \"password_unavailable\");\n }\n const revealed = await client.functions.invoke<{ password: string; connectionString: string }>(\n \"db-info\",\n { projectId },\n { path: \"reveal\" }\n );\n password = revealed.password;\n connectionString = revealed.connectionString;\n }\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🗄 Database — project ${projectRef}`) + chalk.gray(` (${info.type})`));\n console.log(\"\");\n keyValues([\n [\"Host\", info.host],\n [\"Port\", info.port],\n [\"Database\", info.database],\n [\"Username\", info.username],\n [\"Password\", info.passwordAvailable ? (password ?? chalk.gray(\"hidden — pass --reveal\")) : chalk.gray(\"unavailable\")],\n [\"Connection\", connectionString]\n ]);\n if (info.unavailableReason) {\n console.log(chalk.gray(` ${info.unavailableReason}`));\n }\n if (info.directAccess) {\n console.log(\"\");\n console.log(chalk.gray(\" The host above is inside the platform's cluster: it is the address your\"));\n console.log(chalk.gray(\" deployed backend uses, and it resolves to nothing from here. To reach this\"));\n console.log(chalk.gray(\" database from this machine, open a tunnel:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(\"rebase cloud db connect\")}`);\n const pf = info.directAccess.kubectl;\n if (pf) {\n // Only ever present for a cluster the customer owns,\n // where they hold the credentials this needs.\n console.log(\"\");\n console.log(chalk.gray(\" Or, on your own cluster:\"));\n console.log(chalk.gray(` kubectl -n ${pf.namespace} port-forward svc/${pf.service} ${pf.localPort}:${pf.remotePort}`));\n }\n }\n console.log(\"\");\n },\n {\n projectId,\n type: info.type,\n host: info.host,\n port: info.port,\n database: info.database,\n username: info.username,\n passwordAvailable: info.passwordAvailable,\n directAccess: info.directAccess,\n unavailableReason: info.unavailableReason,\n // Only present when explicitly revealed.\n ...(args[\"--reveal\"] ? { password,\nconnectionString } : {})\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load database info\");\n }\n}\n\n/* ─── backups ──────────────────────────────────────────────────── */\n\n/**\n * What `db backup` dispatches. `list` is the default for a bare invocation.\n *\n * Fed to `requireKnownAction` before the client is built, like every other\n * group in this family. Both dispatchers here used to end in an unguarded\n * default instead, so `db backup lst` and `db backup restre` listed the backups\n * and read as \"ran, nothing to do\" — on a command whose other actions overwrite\n * the live database. `db pitr` did have a refusal, but at the tail, behind a\n * login and a project lookup: a typo answered `not_logged_in` and never named\n * the typo.\n *\n * The lists are the ones each `--help` page's usage line carries;\n * `action-help.test.ts` holds the two together.\n */\nconst BACKUP_ACTIONS = [\"list\", \"create\", \"restore\", \"status\", \"download\"] as const;\n\n/** What `db pitr` dispatches. `status` is the default for a bare invocation. */\nconst PITR_ACTIONS = [\"status\", \"restore\", \"cutover\", \"discard\"] as const;\n\n/**\n * `db backup [action] [filename]`, resolved in one strict parse.\n *\n * Both halves were reachable by the old operand filter, and both are\n * destructive: `rebase cloud db backup -p acme` read `--project`'s value as the\n * ACTION (falling through to a list, so the flag silently changed what ran),\n * and `db backup restore -p acme` read it as the FILENAME — a restore staged\n * over the live database, named after the project slug. An undeclared flag was\n * dropped instead of refused, which is the same failure one step quieter: `db\n * backup --dry-run` ran a list, having silently discarded the flag that was\n * supposed to change what it did.\n *\n * Exported so its tests drive the real parser.\n */\nexport function resolveBackupArgs(rawArgs: string[]) {\n const { flags, positionals } = parseCloudArgs({\n // `--yes` is not declared here: `parseCloudArgs` merges the global spec\n // in, and a per-command key that repeats a global one OVERRIDES it in\n // that merge. Identical here, so it was harmless — but it is the same\n // shape as `webhooks create --url`, which was not.\n spec: {},\n rawArgs,\n commandWords: 3, // cloud db backup\n command: \"cloud db backup\",\n maxPositionals: 2 // <action> [filename]\n });\n return { flags,\naction: positionals[0] || \"list\",\nfilename: positionals[1] };\n}\n\nasync function backupCommand(rawArgs: string[]): Promise<void> {\n const { flags: args, action, filename: backupFile } = resolveBackupArgs(rawArgs);\n requireKnownAction(\"db backup\", action, BACKUP_ACTIONS);\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n try {\n if (action === \"create\") {\n const res = await client.functions.invoke<{ success: boolean; backup?: BackupRow; error?: string }>(\n \"backup\",\n { projectId,\ntype: \"manual\" },\n { path: \"create\" }\n );\n if (!res.success) fail(res.error || \"Backup failed.\");\n emit(\n () => success(`Backup created: ${backupName(res.backup) ?? \"(unnamed)\"}`),\n { success: true,\nbackup: res.backup ?? null }\n );\n return;\n }\n\n if (action === \"restore\") {\n const filename = backupFile;\n if (!filename) fail(\"Usage: rebase cloud db backup restore <filename>\", undefined, \"usage\");\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Restore \"${filename}\" over the current database for project ${projectRef}?`\n });\n const res = await client.functions.invoke<{ success: boolean; message?: string; error?: string }>(\n \"backup\",\n { projectId,\nfilename },\n { path: \"restore\" }\n );\n if (!res.success) fail(res.error || \"Restore failed.\");\n emit(() => success(res.message || \"Restore complete\"), { success: true,\nmessage: res.message ?? null });\n return;\n }\n\n if (action === \"status\") {\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", undefined, {\n method: \"GET\",\n path: `backup-status/${projectId}`\n });\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 💾 Automated backups — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Enabled\", res.enabled ? chalk.green(\"yes\") : chalk.yellow(\"no\")],\n [\"Reason\", String(res.reason ?? \"\")],\n [\"Database type\", String(res.databaseType ?? \"\")],\n [\"Last backup\", (res.lastSuccessfulBackup as string) ?? undefined],\n [\n \"Recovery window\",\n res.recoveryWindow\n ? `${(res.recoveryWindow as { from: string }).from} → ${(res.recoveryWindow as { to: string }).to}`\n : undefined\n ]\n ]);\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"download\") {\n const filename = backupFile;\n if (!filename) fail(\"Usage: rebase cloud db backup download <filename>\", undefined, \"usage\");\n const res = await client.functions.invoke<{ url: string; name: string; size: number }>(\"backup\", undefined, {\n method: \"GET\",\n path: `download/${projectId}/${encodeURIComponent(filename)}`\n });\n // Print the signed URL rather than downloading the file — downloading\n // is a user-consented action, and the URL is what the operator/agent\n // needs to fetch it themselves.\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ${res.name}`) + chalk.gray(` ${(res.size / 1024 / 1024).toFixed(1)} MB`));\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\n console.log(chalk.gray(\" Short-lived signed URL — fetch it with curl/wget.\"));\n console.log(\"\");\n },\n { name: res.name,\nsize: res.size,\nurl: res.url }\n );\n return;\n }\n\n // default: list — the only word that reaches here, because\n // `requireKnownAction` refused every other one before the client was\n // built.\n const res = await client.functions.invoke<{ backups: BackupRow[] }>(\n \"backup\",\n undefined,\n { method: \"GET\",\npath: `list/${projectId}` }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 💾 Backups — project ${projectRef}`));\n console.log(\"\");\n if (!res.backups?.length) {\n console.log(chalk.gray(\" No backups yet. Create one with `rebase cloud db backup create`.\"));\n console.log(\"\");\n return;\n }\n for (const b of res.backups) {\n const detail = [b.type, backupSize(b), b.date].filter(Boolean).join(\" \");\n console.log(` ${chalk.bold(backupName(b) ?? \"(unnamed)\")} ${chalk.gray(detail)}`);\n }\n console.log(\"\");\n },\n { projectId,\nbackups: res.backups ?? [] }\n );\n } catch (e) {\n reportError(e, \"Backup operation failed\");\n }\n}\n\n/* ─── PITR (point-in-time recovery) ────────────────────────────── */\n\n/**\n * `rebase cloud db pitr <status|restore|cutover|discard>`.\n *\n * A PITR restore is STAGED, not applied: `restore` creates a recovered copy of\n * the database beside the live one — the application is NOT repointed and the\n * original is left running and unchanged. `cutover` is the separate, explicit\n * step that repoints the app at the recovered copy (and restarts it). `discard`\n * removes a staged copy; the server refuses to discard a copy that has been cut\n * over to (it is now the live database). Every mutating step requires `--yes` in\n * non-interactive use, and the CLI surfaces these staged semantics honestly.\n */\nasync function pitrCommand(rawArgs: string[]): Promise<void> {\n // Same shape as `db backup`: `db pitr -p acme` used to read the project slug\n // as the action, and a PITR action decides between reporting, staging a\n // recovered copy, and repointing the live app at one.\n const { flags: args, positionals } = parseCloudArgs({\n // `--yes` comes from the global spec — see `resolveBackupArgs`.\n spec: { \"--target\": String },\n rawArgs,\n commandWords: 3, // cloud db pitr\n command: \"cloud db pitr\",\n maxPositionals: 1\n });\n const action = positionals[0] || \"status\";\n requireKnownAction(\"db pitr\", action, PITR_ACTIONS);\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n try {\n if (action === \"status\") {\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", undefined, {\n method: \"GET\",\n path: `pitr-status/${projectId}`\n });\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⏱ Point-in-time recovery — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Available\", res.available ? chalk.green(\"yes\") : chalk.yellow(\"no\")],\n [\"First recoverable\", (res.firstRecoverabilityPoint as string) ?? undefined],\n [\"Last backup\", (res.lastSuccessfulBackup as string) ?? undefined],\n [\"Message\", (res.message as string) ?? undefined]\n ]);\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"restore\") {\n const target = args[\"--target\"];\n if (!target) fail(\"Usage: rebase cloud db pitr restore --target <ISO timestamp>\", undefined, \"usage\");\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Stage a point-in-time recovery of project ${projectRef} at ${target}? (stages a copy; does not repoint your app)`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\n \"backup\",\n // acknowledgeNoCutover is required by the server: the caller must\n // affirm this only STAGES a copy. The confirm prompt above says so.\n { projectId,\ntargetTime: target,\nacknowledgeNoCutover: true },\n { path: \"pitr-restore\" }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.yellow(` ⏳ ${String(res.message ?? \"Recovery staged.\")}`));\n console.log(chalk.gray(\" Watch progress with `rebase cloud db pitr status`, then `rebase cloud db pitr cutover --yes`.\"));\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"cutover\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Cut project ${projectRef} over to the staged recovery? This repoints and restarts your application.`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", { projectId }, { path: \"pitr-restore-cutover\" });\n emit(\n () => {\n console.log(\"\");\n console.log(String(res.message ?? \"Cutover requested.\"));\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"discard\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Discard the staged recovery for project ${projectRef}? This deletes the staged copy and its storage.`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", { projectId }, { path: \"pitr-restore-discard\" });\n emit(\n () => success(String(res.message ?? \"Staged restore discarded.\")),\n res\n );\n return;\n }\n\n // No tail: `requireKnownAction` refused every word that is not one of\n // the four, before the client was built. The refusal that used to sit\n // here was behind a login and a project lookup, so a typo answered\n // `not_logged_in` rather than naming the typo.\n } catch (e) {\n reportError(e, \"PITR operation failed\");\n }\n}\n\nexport function printDbHelp(): void {\n printGroupHelp({\n command: \"cloud db\",\n title: \"Database & backups\",\n actions: [\n { action: \"list\",\nsection: \"Database\",\ndescription: \"List databases attached to the project\" },\n {\n action: \"create\",\n section: \"Database\",\n description: \"Attach a managed or bring-your-own database\",\n flags: [\n [\"--type <managed|byodb>\", \"Which kind to attach\"],\n [\"--connection-string <url>\", \"The external PostgreSQL URL, for byodb\"],\n [\"--wait\", \"Wait for the managed database to be reachable\"],\n [\"--timeout <seconds>\", \"Ceiling on that wait\"]\n ]\n },\n {\n action: \"info\",\n section: \"Database\",\n description: \"Connection details\",\n flags: [[\"--reveal\", \"Include the password (owner or admin). Without it, the value is masked\"]]\n },\n {\n action: \"connect\",\n section: \"Database\",\n description: \"Open a local port that IS the project's database\",\n flags: [\n [\"--port <n>\", \"Local port to listen on. Default: 5432\"],\n [\"--reveal\", \"Print the password in the connection URL\"]\n ]\n },\n { action: \"test\",\nsection: \"Database\",\ndescription: \"Test database connectivity\" },\n\n { action: \"backup list\",\nsection: \"Backups\",\ndescription: \"List backups\" },\n { action: \"backup create\",\nsection: \"Backups\",\ndescription: \"Create a manual backup\" },\n { action: \"backup restore\",\nargs: \"<file>\",\nsection: \"Backups\",\ndescription: \"Restore a backup\" },\n { action: \"backup status\",\nsection: \"Backups\",\ndescription: \"Automated-backup health\" },\n { action: \"backup download\",\nargs: \"<file>\",\nsection: \"Backups\",\ndescription: \"Signed URL for a backup\" },\n\n { action: \"pitr status\",\nsection: \"Point-in-time recovery\",\ndescription: \"The window a recovery can target\" },\n {\n action: \"pitr restore\",\n section: \"Point-in-time recovery\",\n description: \"Stage a recovery. Does NOT repoint the app\",\n flags: [[\"--target <ISO>\", \"The instant to recover to\"]]\n },\n { action: \"pitr cutover\",\nsection: \"Point-in-time recovery\",\ndescription: \"Repoint the app at the staged recovery\" },\n { action: \"pitr discard\",\nsection: \"Point-in-time recovery\",\ndescription: \"Delete a staged recovery\" }\n ],\n notes: [\n \"A project has exactly one database: `create` refuses rather than attaching a second, because\",\n \"which of two rows a deploy uses is undefined.\",\n \"A managed database is provisioned at the project's FIRST DEPLOY, so `test` failing before then\",\n \"is not a fault.\",\n \"The host `info` reports is inside the platform's cluster — your backend's address for it, not\",\n \"one your laptop can resolve. `connect` is what makes it reachable from here.\"\n ]\n });\n}\n","/**\n * `rebase cloud projects` — list / create / info / delete.\n */\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n parseCloudArgs,\n requireProjectRef,\n resolveProjectRef,\n getContextOrg,\n readLink,\n writeLink,\n colorStatus,\n keyValues,\n fetchTenantBaseDomain,\n fetchDeployTargets,\n type DeployTarget,\n projectHost,\n success,\n fail,\n warn,\n reportError,\n emit,\n note,\n noteBlank,\n confirmDestructive,\n type CloudClient,\n cloudRows,\n requireCloudRow\n} from \"./context\";\nimport { buildDialPatch } from \"./resources\";\nimport { attachDatabaseRow } from \"./databases\";\n\ninterface ProjectRow {\n id: string | number;\n name?: string;\n subdomain?: string;\n /**\n * Where the project is actually served. Computed by the control plane from\n * the project's cluster, which the CLI cannot read itself (admin-only RLS).\n * Absent on control planes older than that hook — `projectHost` falls back.\n */\n host?: string;\n customDomain?: string;\n gitRepoUrl?: string;\n gitBranch?: string;\n provider?: string;\n region?: string;\n status?: string;\n organization?: string | number;\n createdById?: string;\n}\n\n/* ─── list ─────────────────────────────────────────────────────── */\n\nexport async function listProjects(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud projects\",\nmaxPositionals: 0 });\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n try {\n const [projects, baseDomain] = await Promise.all([\n client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n orderBy: [\"name\", \"asc\"],\n limit: 100\n }).then((res) => cloudRows<ProjectRow>(res.data)),\n fetchTenantBaseDomain(client, url)\n ]);\n\n const linkedId = readLink()?.projectId;\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(\" 📦 Projects\") + (org ? chalk.gray(` (org ${org})`) : \"\"));\n console.log(\"\");\n\n if (projects.length === 0) {\n console.log(\n chalk.gray(\" No projects yet. Create one with `rebase cloud projects create`.\")\n );\n console.log(\"\");\n return;\n }\n\n for (const p of projects) {\n const marker = String(p.id) === linkedId ? chalk.green(\" ●\") : \" \";\n console.log(`${marker}${chalk.bold(p.name ?? \"(unnamed)\")} ${chalk.gray(`[${p.subdomain ?? p.id}]`)} ${colorStatus(p.status)}`);\n console.log(` ${chalk.gray(projectHost(p, baseDomain) ?? \"—\")}${p.provider ? chalk.gray(` · ${p.provider}`) : \"\"}`);\n }\n console.log(\"\");\n },\n {\n org: org ?? null,\n projects: projects.map((p) => ({\n id: String(p.id),\n name: p.name ?? null,\n slug: p.subdomain ?? null,\n host: projectHost(p, baseDomain) ?? null,\n status: p.status ?? null,\n provider: p.provider ?? null,\n linked: String(p.id) === linkedId\n }))\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list projects\");\n }\n}\n\n/* ─── create ───────────────────────────────────────────────────── */\n\n/**\n * Default region per provider. Required on create; the rest is dialled.\n *\n * There used to be a `vmSize` here too — `e2-small`, `cx21` — naming a machine\n * on a price list this platform does not buy from. The column was dropped on\n * 2026-08-20 and this went on sending it, which a control plane can only ignore\n * or refuse. What a project reserves is a set of dials now, and a project that\n * sets none takes the platform default.\n */\nfunction providerDefaults(provider: string): { region: string } {\n switch (provider) {\n case \"gcp\":\n return { region: \"europe-west1\" };\n case \"aws\":\n return { region: \"us-east-1\" };\n default:\n // fsn1, not nbg1: Falkenstein is the Hetzner region the control\n // plane prices and stands capacity in; Nuremberg is in neither list,\n // so a project defaulted there was refused as an unknown region.\n return { region: \"fsn1\" };\n }\n}\n\n/**\n * Where this project says it runs.\n *\n * `provider`/`region` are a *request*: no code downstream reads them to pick a\n * deploy target — that comes from the project's cluster record or the ambient\n * in-cluster context (saas/backend/src/k8s/resolve.ts). So a wrong value here is\n * never contradicted by a failure; it just sits in the record. The CLI used to\n * default to `hetzner`/`nbg1` unconditionally, which is how projects running on\n * our GKE cluster came to describe themselves as Hetzner in the console — and\n * `provider` also decides which substrate's rules a project's dials are clamped\n * to — Autopilot's 250m floor and 1:1-6.5:1 band do not apply on Hetzner or EKS\n * — so a wrong value here resizes pods, it is not a cosmetic slip.\n *\n * The control plane already publishes the infrastructure that actually exists,\n * and the console's create wizard reads it. Ask the same question here.\n *\n * Exported for tests: the decision is pure, so it can be pinned without a\n * control plane. The fetching and the exit live in `resolveRequestedTarget`.\n *\n * @param requested `--provider`, if the caller named one. An explicit flag wins:\n * it is the caller stating intent, and `deploy` corrects the record anyway.\n * @param targets What the control plane says exists, or `undefined` when it\n * cannot say — an older deployment with no `platform-config`, or a failed\n * request. That is different from an empty list, which is a control plane\n * stating it has no infrastructure at all.\n * @returns the target to record, or `null` when the control plane answered that\n * there is none.\n */\nexport function chooseRequestedTarget(\n requested: string | undefined,\n targets: DeployTarget[] | undefined\n): { provider: string; region?: string } | null {\n if (requested) {\n // An explicit provider takes the region of the first target the control\n // plane offers on it: `--provider hetzner` means \"the Hetzner region\n // we have capacity in\", which the control plane knows and a\n // per-provider guess does not. No such target, no region — the caller\n // may still name one, or the per-provider default applies.\n const offered = targets?.find((t) => t.provider === requested);\n return { provider: requested,\nregion: offered?.region?.trim() || undefined };\n }\n\n // Keep the historical default against a control plane that cannot answer,\n // rather than refusing to create a project against it.\n if (!targets) return { provider: \"hetzner\",\nregion: undefined };\n\n if (targets.length === 0) return null;\n\n // The resolver returns targets in its own preference order, and the first is\n // the one a deploy would use.\n const [target] = targets;\n return { provider: target.provider,\nregion: target.region?.trim() || undefined };\n}\n\nasync function resolveRequestedTarget(\n client: CloudClient,\n url: string,\n requested: string | undefined\n): Promise<{ provider: string; region?: string }> {\n const chosen = chooseRequestedTarget(requested, await fetchDeployTargets(client, url));\n if (!chosen) {\n fail(\n \"This control plane has no deploy targets configured.\",\n `Register a cluster, or pass ${chalk.bold(\"--provider\")} and ${chalk.bold(\"--region\")} to record one anyway.`,\n \"no_deploy_targets\"\n );\n }\n return chosen;\n}\n\n/** The flags `rebase cloud projects create` takes. */\nexport const CREATE_PROJECT_FLAGS = {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--provider\": String,\n \"--region\": String,\n \"--org\": String,\n \"--link\": Boolean,\n /**\n * Which database the new project gets — `managed` (the default), `byodb`,\n * or `none`.\n *\n * A default rather than a prompt, and `managed` rather than `none`, because\n * the state this removes is not a missing convenience: a project with no\n * database is written `status: \"provisioning\"` and can never deploy, and\n * nothing in that word says a second command is owed. Attaching one here\n * means the two-command sequence that every project needs is one command,\n * and `--db none` is there for the case that genuinely wants to decide later.\n *\n * Distinct from `--db-cpu`/`--db-instances` next to it, which are resource\n * dials on a database that exists. This is whether there is one.\n */\n \"--db\": String,\n /** For `--db byodb`. Same spelling as `rebase cloud db create` uses. */\n \"--connection-string\": String,\n \"-n\": \"--name\",\n // The resource dials, same spelling as `rebase cloud compute set`. Every\n // one is optional: a project that names none takes the platform default.\n // `--vm-size` used to sit here and named a machine on a price list this\n // platform does not buy from; the column it wrote was dropped on 2026-08-20.\n \"--cpu\": String,\n \"--memory\": String,\n \"--replicas\": String,\n \"--spot\": String,\n \"--scale-to-zero\": String,\n \"--db-instances\": String,\n \"--db-cpu\": String,\n \"--db-memory\": String,\n \"--storage\": String\n} as const;\n\nexport async function createProject(rawArgs: string[]): Promise<void> {\n // Strict: every value here ends up in the project record, and the permissive\n // parse dropped a mistyped one silently — `--subdomian shop` created a\n // project on a generated subdomain, and a subdomain is not editable in\n // passing afterwards.\n const { flags: args } = parseCloudArgs({\n spec: CREATE_PROJECT_FLAGS,\n rawArgs,\n commandWords: 3, // cloud projects create\n command: \"cloud projects create\",\n maxPositionals: 0\n });\n\n const { client, url } = await requireClient(rawArgs);\n const org = args[\"--org\"] || getContextOrg(url);\n if (!org) {\n fail(\n \"No organization selected.\",\n `Pass ${chalk.bold(\"--org <id>\")} or run ${chalk.bold(\"rebase cloud use\")}.`,\n \"no_org\"\n );\n }\n\n // Prompt only for the essentials, and only when attached to a terminal —\n // a headless `projects create --name X --subdomain Y` must never block.\n // repo/branch/provider are optional and default sensibly.\n const prompts: Array<{ type: \"input\"; name: string; message: string }> = [];\n if (!args[\"--name\"]) prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Project name:\" });\n if (!args[\"--subdomain\"]) prompts.push({ type: \"input\",\nname: \"subdomain\",\nmessage: \"Subdomain:\" });\n const answers = prompts.length && process.stdin.isTTY\n ? await inquirer.prompt(prompts)\n : {};\n const a = answers as Record<string, string>;\n\n const name = (args[\"--name\"] || a.name || \"\").trim();\n const subdomain = (args[\"--subdomain\"] || a.subdomain || \"\").trim().toLowerCase();\n const gitRepoUrl = (args[\"--repo\"] || a.repo || \"\").trim();\n const gitBranch = (args[\"--branch\"] || a.branch || \"main\").trim();\n const target = await resolveRequestedTarget(\n client,\n url,\n (args[\"--provider\"] || a.provider)?.trim() || undefined\n );\n const provider = target.provider;\n // region is required by the control plane; default sensibly per provider so\n // a headless `projects create` needs only name + subdomain. The target's own\n // region wins where it has one: a per-provider guess is how a GKE project\n // ended up recorded in `nbg1`.\n const defaults = providerDefaults(provider);\n const region = (args[\"--region\"] || target.region || defaults.region).trim();\n\n // Compute, if the caller named any. The same flags `compute set` takes,\n // parsed by the same function — a second parser here would be the place the\n // two spellings of a dial drift apart. Nothing is required: a project that\n // names no dial takes the platform default and can change it afterwards.\n const dials = buildDialPatch(rawArgs, { requireOne: false });\n if (dials.error) fail(dials.error, undefined, \"bad_request\");\n\n // Validated before the project row is written, not after: a typo'd `--db`\n // discovered afterwards leaves a project that exists and cannot deploy —\n // exactly the state this flag is here to remove.\n const dbChoice = (args[\"--db\"] ?? \"managed\").trim().toLowerCase();\n if (![\"managed\", \"byodb\", \"none\"].includes(dbChoice)) {\n fail(`--db must be managed, byodb or none (got \"${args[\"--db\"]}\").`, undefined, \"bad_request\");\n }\n if (dbChoice === \"byodb\" && !args[\"--connection-string\"]) {\n fail(\n \"--db byodb needs the database to point at.\",\n `Pass ${chalk.bold(\"--connection-string <url>\")}.`,\n \"input_required\"\n );\n }\n\n if (!name || !subdomain) {\n fail(\n \"Name and subdomain are required.\",\n `Pass ${chalk.bold(\"--name <name>\")} and ${chalk.bold(\"--subdomain <slug>\")}.`,\n \"input_required\"\n );\n }\n\n // Validate subdomain availability up front for a clean error.\n try {\n const check = await client.functions.invoke<{ available: boolean; reason?: string }>(\n \"check-subdomain\",\n { subdomain }\n );\n if (!check.available) {\n fail(\n `Subdomain \"${subdomain}\" is not available${check.reason ? ` (${check.reason})` : \"\"}.`,\n undefined,\n \"subdomain_unavailable\"\n );\n }\n } catch {\n // If the control plane has no such function, skip the pre-check —\n // the collection hook still enforces uniqueness on create.\n }\n\n try {\n const user = await client.auth.getUser();\n if (!user) {\n fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\", \"session_invalid\");\n }\n const created = requireCloudRow<ProjectRow>(await client.data.collection(\"projects\").create({\n name,\n subdomain,\n gitRepoUrl,\n gitBranch,\n provider,\n region,\n ...dials.patch,\n organization: org,\n createdById: user.uid,\n status: \"provisioning\"\n }), \"project\");\n\n const host = projectHost(created, await fetchTenantBaseDomain(client, url));\n const linked = Boolean(args[\"--link\"]);\n if (linked) {\n writeLink({ url,\nprojectId: String(created.id),\nslug: created.subdomain,\nprojectName: name,\norgId: String(org) });\n }\n\n // Attached in its own try, and reported separately, because the two\n // halves fail independently. A project that exists with no database is\n // the state worth naming loudly — reporting the whole command as failed\n // would hide a project that was in fact created, and reporting it as\n // succeeded would hide that the project cannot deploy.\n const database = await attachRequestedDatabase(client, {\n projectId: String(created.id),\n choice: dbChoice,\n connectionString: args[\"--connection-string\"],\n projectRef: created.subdomain ?? String(created.id)\n });\n\n if (database.warning) warn(database.warning[0], database.warning[1]);\n\n success(`Created project ${chalk.bold(name)}`);\n emit(\n () => {\n keyValues([\n [\"Slug\", String(created.subdomain ?? \"\")],\n [\"URL\", host],\n [\"Provider\", provider],\n [\"Branch\", gitBranch],\n [\"Database\", database.line]\n ]);\n if (linked) note(chalk.gray(\"Linked this directory to the new project.\"));\n noteBlank();\n for (const line of database.notes) note(chalk.gray(line));\n note(chalk.gray(`Deploy it with: ${chalk.bold(`rebase cloud deploy --project ${created.subdomain ?? created.id}`)}`));\n noteBlank();\n },\n {\n success: true,\n id: String(created.id),\n name,\n slug: created.subdomain ?? null,\n host: host ?? null,\n provider,\n region,\n dials: dials.patch,\n branch: gitBranch,\n org: String(org),\n linked,\n database: database.payload\n }\n );\n } catch (e) {\n reportError(e, \"Failed to create project\");\n }\n}\n\n/**\n * Attach the database `--db` asked for, and describe what happened.\n *\n * Never throws. The project already exists by the time this runs, so a failure\n * here is a *partial* success and has to be reported as one — with the exact\n * command that finishes the job. Turning it into an exception would report the\n * whole `projects create` as failed and leave a real project behind, which is\n * the worst of both readings.\n */\nasync function attachRequestedDatabase(\n client: CloudClient,\n input: { projectId: string; choice: string; connectionString?: string; projectRef: string }\n): Promise<{\n line: string;\n notes: string[];\n /** `[message, hint]` — raised through `warn`, so it survives JSON mode. */\n warning?: [string, string];\n payload: Record<string, unknown>;\n}> {\n if (input.choice === \"none\") {\n return {\n line: chalk.yellow(\"none\"),\n // A note, not a warning: the caller asked for this, and the only\n // thing owed is the command that undoes it.\n notes: [\n \"No database attached (--db none). This project cannot deploy until one is:\",\n \" rebase cloud db create --type managed\"\n ],\n payload: { attached: false,\ntype: null,\nreason: \"requested_none\" }\n };\n }\n\n try {\n const row = await attachDatabaseRow(client, {\n projectId: input.projectId,\n type: input.choice,\n connectionString: input.connectionString\n });\n return {\n line: input.choice === \"managed\"\n ? `managed ${chalk.gray(\"· created at the first deploy\")}`\n : `byodb ${chalk.gray(\"· not tested (`rebase cloud db test`)\")}`,\n notes: [],\n payload: { attached: true,\nid: String(row.id),\ntype: input.choice,\nmaterializedAt: input.choice === \"managed\" ? \"first_deploy\" : \"now\" }\n };\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return {\n line: chalk.red(\"not attached\"),\n notes: [],\n // A warning, because the caller did NOT ask for this: they now hold\n // a project that exists and cannot deploy. `warn` writes to stderr\n // in every output mode, so a piped run still sees it beside the\n // `database.attached: false` in the payload.\n warning: [\n `The project was created, but attaching its ${input.choice} database failed: ${message}`,\n `Finish it with: rebase cloud db create --type ${input.choice} --project ${input.projectRef}`\n ],\n payload: { attached: false,\ntype: input.choice,\nreason: \"attach_failed\",\nerror: message }\n };\n }\n}\n\n/* ─── info ─────────────────────────────────────────────────────── */\n\n/**\n * Which project `projects info` / `projects delete` acts on.\n *\n * The id is optional — omitted, it falls back to `--project` or the link file —\n * and the dispatcher used to read it off `positionals()`, which skips only\n * LEADING `-` tokens and declares only the global cloud flags. So an undeclared\n * flag written after the action became the id: `rebase cloud projects delete\n * --force` looked up a project named \"--force\" and reported it missing, rather\n * than saying there is no such flag. Benign next to the deletes and writes the\n * rest of this family aimed at the wrong resource, but the same mistake, and\n * `positionals()` has no spec with which to do better — the handler's own\n * module does.\n *\n * Exported so its tests drive the real parser rather than a copy of it.\n */\nexport function resolveProjectArg(rawArgs: string[], action: \"info\" | \"delete\"): string {\n const { positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud projects <action>\n command: `cloud projects ${action}`,\n maxPositionals: 1\n });\n return positionals[0] || requireProjectRef(rawArgs);\n}\n\n/** What `capacity` reports for a project's database, when it reports anything. */\ninterface DatabaseCapacity {\n usedMb: number;\n limitMb: number;\n usedFraction: number | null;\n locked: boolean;\n state: \"locked\" | \"warning\" | \"ok\";\n detail: string;\n}\n\n/**\n * A project's database capacity, or null.\n *\n * Swallows every failure on purpose. This decorates `status`; a control plane\n * that predates the `capacity` function 404s here, and an older CLI talking to a\n * newer one must still print the project. Losing the capacity line is a missing\n * nicety — failing the whole command over it would be the bug.\n */\nasync function fetchCapacity(client: CloudClient, projectId: string): Promise<DatabaseCapacity | null> {\n try {\n const res = await client.functions.invoke<{ database?: DatabaseCapacity | null }>(\n \"capacity\",\n undefined,\n { method: \"GET\", path: projectId }\n );\n return res?.database ?? null;\n } catch {\n return null;\n }\n}\n\nexport async function projectInfo(rawArgs: string[], projectRef: string): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const projectId = await resolveProjectRef(projectRef, client);\n const p = (await client.data.collection(\"projects\").findById(projectId)) as ProjectRow | undefined;\n if (!p) fail(`Project ${projectRef} not found.`, undefined, \"project_not_found\");\n\n const [db, lastDeploy, baseDomain, capacity] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url),\n fetchCapacity(client, projectId)\n ]);\n\n emit(\n () => {\n console.log(\"\");\n console.log(` ${chalk.bold(p.name ?? \"(unnamed)\")} ${chalk.gray(`[${p.subdomain ?? p.id}]`)} ${colorStatus(p.status)}`);\n console.log(\"\");\n keyValues([\n [\"Subdomain\", projectHost(p, baseDomain)],\n [\"Custom domain\", p.customDomain],\n [\"Repository\", p.gitRepoUrl],\n [\"Branch\", p.gitBranch],\n [\"Provider\", p.provider],\n [\"Region\", p.region],\n [\"Organization\", p.organization !== undefined ? String(p.organization) : undefined],\n [\"Database\", db ? `${db.type} (${colorStatus(db.connectionStatus as string)})` : \"none\"],\n // Only when there is a ceiling to report against. A project\n // on a dedicated database has none, and printing \"0 MB / 0 MB\"\n // for it would read as full.\n [\"Storage\", capacity && capacity.limitMb > 0\n ? `${capacity.usedMb} MB / ${capacity.limitMb} MB${\n capacity.usedFraction !== null ? ` (${(capacity.usedFraction * 100).toFixed(0)}%)` : \"\"\n }`\n : undefined],\n [\"Last deploy\", lastDeploy ? `${colorStatus(lastDeploy.status)} · ${fmtDate(lastDeploy.createdAt)}` : \"never\"]\n ]);\n // The whole point of the feature: a tenant hitting the ceiling\n // used to find out because their app stopped answering. Say it\n // here, where they already look, and say what happens next.\n if (capacity && capacity.state !== \"ok\") {\n console.log(\"\");\n console.log(\n capacity.state === \"locked\"\n ? ` ${chalk.red.bold(\"✗ Database locked — over its storage limit\")}`\n : ` ${chalk.yellow.bold(\"⚠ Database approaching its storage limit\")}`\n );\n console.log(` ${chalk.gray(capacity.detail)}`);\n }\n console.log(\"\");\n },\n {\n id: String(p.id),\n name: p.name ?? null,\n slug: p.subdomain ?? null,\n host: projectHost(p, baseDomain) ?? null,\n customDomain: p.customDomain ?? null,\n repository: p.gitRepoUrl ?? null,\n branch: p.gitBranch ?? null,\n provider: p.provider ?? null,\n region: p.region ?? null,\n status: p.status ?? null,\n org: p.organization !== undefined ? String(p.organization) : null,\n database: db ? { type: db.type ?? null,\nconnectionStatus: db.connectionStatus ?? null,\ncapacity: capacity ?? null } : null,\n lastDeploy: lastDeploy\n ? { id: String(lastDeploy.id),\nstatus: lastDeploy.status ?? null,\ncreatedAt: lastDeploy.createdAt ?? null }\n : null\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load project\");\n }\n}\n\n/* ─── delete ───────────────────────────────────────────────────── */\n\nexport async function deleteProject(rawArgs: string[], projectRef: string): Promise<void> {\n const { flags: args } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud projects delete\n command: \"cloud projects delete\",\n maxPositionals: 1 // [id]\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n const p = (await client.data.collection(\"projects\").findById(projectId).catch(() => undefined)) as\n | ProjectRow\n | undefined;\n if (!p) fail(`Project ${projectRef} not found.`, undefined, \"project_not_found\");\n\n // Through the shared guard, not a bare `inquirer.prompt`. This was the one\n // destructive command in the family that rolled its own confirm, and it was\n // the only one that could HANG: piped or agent-run, the other nine refuse\n // with `confirmation_required` while this one sat on a prompt reading a\n // stdin that would never answer — on the single command whose whole job is\n // to tear a project down.\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Permanently delete project \"${p.name ?? projectRef}\" (${p.subdomain ?? projectRef})? This tears down its deployment.`\n });\n\n try {\n await client.data.collection(\"projects\").delete(projectId);\n success(`Deleted project ${chalk.bold(p.name ?? projectId)}`);\n emit(() => {}, {\n success: true,\n id: projectId,\n name: p.name ?? null,\n slug: p.subdomain ?? null\n });\n } catch (e) {\n reportError(e, \"Failed to delete project\");\n }\n}\n\n/* ─── shared helpers (used by other subcommands too) ───────────── */\n\nexport async function firstRow(\n client: CloudClient,\n collection: string,\n projectId: string\n): Promise<Record<string, unknown> | undefined> {\n const res = await client.data.collection(collection).find({\n where: { project: [\"==\", projectId] },\n limit: 1\n });\n return res.data[0];\n}\n\nexport async function latestDeployment(\n client: CloudClient,\n projectId: string\n): Promise<{ id: string | number; status?: string; createdAt?: string; logs?: string } | undefined> {\n const res = await client.data.collection(\"deployments\").find({\n where: { project: [\"==\", projectId] },\n orderBy: [\"createdAt\", \"desc\"],\n limit: 1\n });\n return res.data[0] as { id: string | number; status?: string; createdAt?: string; logs?: string } | undefined;\n}\n\nexport function fmtDate(value: string | undefined): string {\n if (!value) return \"—\";\n const d = new Date(value);\n return isNaN(d.getTime()) ? value : d.toLocaleString();\n}\n","/**\n * `rebase cloud debug <subcommand>` — one entry point for \"why is my deployed\n * app not behaving\".\n *\n * ## Why this exists\n *\n * The useful signals for a deployed project live in four different places — the\n * control plane, the workload's pods, the tenant database, and the public URL —\n * and each is normally reached with a different tool and a different set of\n * flags. Getting to a log should not be a research task. This started life as a\n * hand-rolled `prod-debug.sh` for a single project, with the namespace and the\n * URL hardcoded at the top; it earned its place twice in one week, so it is\n * generalised here to any project the CLI can already resolve.\n *\n * ## Read-only by default\n *\n * Every subcommand here only reads. The two things the original script could do\n * that mutate are deliberately NOT reproduced as-is:\n *\n * - restarting the workload lives at `rebase cloud restart`, which already\n * gates downtime behind `--yes`; duplicating it here would give the same\n * destructive act a second, ungated spelling.\n * - `debug db` prints the port-forward recipe and the connection's *shape*.\n * It opens no session and prints no password — `rebase cloud db info\n * --reveal` is the explicit, auditable way to get one.\n *\n * ## The probes are the point\n *\n * `debug health` is the highest-value piece and the reason the script existed.\n * A bare status code is not a diagnosis: a 404 from a functions route means\n * something completely different from a 404 at the root, and a 200 on an\n * unauthenticated read is a finding rather than a success. So every probe ships\n * with the interpretation of what it got, not just the number — see\n * {@link PROBES}.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { unknownCommandMessage } from \"../../utils/unknown-command\";\nimport {\n requireClient,\n requireProject,\n parseCloudArgs,\n displayProjectRef,\n fetchTenantBaseDomain,\n projectHost,\n colorStatus,\n keyValues,\n emit,\n printGroupHelp,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\n/* ═══════════════════════════════════════════════════════════════\n Health probes\n ═══════════════════════════════════════════════════════════════ */\n\n/** How a probe's outcome should be read. */\nexport type Verdict =\n /** Behaving as a healthy deployment should. */\n | \"ok\"\n /** Reachable and legal, but worth a human look (e.g. a public read). */\n | \"warn\"\n /** Broken, or wired up wrong. */\n | \"fail\"\n /** We could not classify the response. */\n | \"unknown\";\n\nexport interface ProbeReading {\n verdict: Verdict;\n /** What this status code *means for this endpoint*, in one sentence. */\n meaning: string;\n}\n\nexport interface ProbeSpec {\n id: string;\n /** Column label in human output. */\n label: string;\n method: \"GET\" | \"POST\";\n /** Path relative to the project origin. */\n path: (opts: ProbeTargets) => string;\n body?: unknown;\n /** One-line statement of what a healthy deployment answers here. */\n healthy: string;\n interpret: (status: number | null) => ProbeReading;\n /**\n * Read the response body as well. Set only where the body carries a fact the\n * status code cannot — today, the function listing.\n */\n needsBody?: boolean;\n /**\n * Sharpen the status-code reading using the parsed body. Returning null\n * keeps {@link interpret}'s verdict.\n */\n refine?: (body: unknown, targets: ProbeTargets) => ProbeReading | null;\n}\n\nexport interface ProbeTargets {\n /** Collection used for the unauthenticated-read probe. */\n collection: string;\n /** Function to confirm exists, if the caller named one. */\n fn?: string;\n}\n\n/** A response never arrived: DNS, TLS, ingress, or the pod. */\nconst NO_RESPONSE: ProbeReading = {\n verdict: \"fail\",\n meaning:\n \"nothing answered — the hostname does not resolve, the ingress has no route, or no pod is running\"\n};\n\nfunction serverError(what: string): ProbeReading {\n return { verdict: \"fail\",\nmeaning: `the server is running but ${what}` };\n}\n\n/**\n * The probe set, in the order a failure cascades: if `health` is down, nothing\n * below it is meaningful, so it is checked first and reported first.\n */\nexport const PROBES: ProbeSpec[] = [\n {\n id: \"health\",\n label: \"health\",\n method: \"GET\",\n path: () => \"/health\",\n healthy: \"200 — the backend is up\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the backend is up and serving\" };\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"something answered but it is not a Rebase backend — the ingress is routing this host elsewhere\"\n };\n }\n if (status >= 500) return serverError(\"its health endpoint is failing\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a health endpoint\" };\n }\n },\n {\n id: \"spa\",\n label: \"spa\",\n method: \"GET\",\n path: () => \"/\",\n healthy: \"200 — the frontend is being served\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the frontend bundle is being served\" };\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning:\n \"no frontend at the root — expected for a backend-only project, otherwise the SPA assets were not bundled into the image\"\n };\n }\n if (status >= 500) return serverError(\"the root route throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected at the site root\" };\n }\n },\n {\n id: \"auth\",\n label: \"auth\",\n method: \"POST\",\n path: () => \"/api/auth/login\",\n body: {},\n healthy: \"400 — auth is mounted and rejects an empty body\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n // The probe deliberately posts an empty body: a healthy auth route\n // must reject it. Reachability is what is being tested, not a login.\n if (status === 400 || status === 422) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and rejected the empty body, as it should\" };\n }\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and refused the credentials\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning: \"the auth routes are NOT mounted — this project cannot sign anyone in\"\n };\n }\n if (status === 200) {\n return {\n verdict: \"fail\",\n meaning: \"an EMPTY login body was accepted — a login with no credentials must never succeed\"\n };\n }\n if (status >= 500) return serverError(\"the login route throws — often a missing or unmigrated auth table\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a login route\" };\n }\n },\n {\n id: \"unauthRead\",\n label: \"unauth read\",\n method: \"GET\",\n path: (t) => `/api/data/${encodeURIComponent(t.collection)}`,\n healthy: \"401 — reads require authentication\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"unauthenticated reads are refused — row-level security is enforced\" };\n }\n if (status === 200) {\n // Legal, and sometimes intended. Never silently called healthy.\n return {\n verdict: \"warn\",\n meaning:\n \"this collection is readable with NO authentication — correct only if it is deliberately public\"\n };\n }\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning: \"no such collection on this deployment — check the name, or pass --collection\"\n };\n }\n if (status >= 500) {\n return serverError(\n \"the read reached the database and failed — most often an RLS policy naming a column or table that is not there\"\n );\n }\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a data read\" };\n }\n },\n {\n id: \"functions\",\n label: \"functions\",\n method: \"GET\",\n /**\n * The router's own listing endpoint, NOT a function's path.\n *\n * This matters, and it is the one place the original script got a wrong\n * answer. A function is a Hono sub-app mounted at `/<name>`, and it\n * usually defines only sub-routes (`/get`, `/list`) — so\n * `/api/functions/<name>` 404s **even when everything is mounted and\n * healthy**. Probing there cannot separate \"the router is missing\" from\n * \"that function defines no root route\", and reporting the first is how\n * you send someone to debug a deployment that was fine.\n *\n * `GET /api/functions` is unambiguous: the router registers a listing\n * route at its own root (see `createFunctionRoutes`), so a 200 proves\n * the mount *and* names every function that loaded.\n */\n path: () => \"/api/functions\",\n healthy: \"200 — the functions router is mounted and lists its functions\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the functions router is mounted\" };\n if (status === 401 || status === 403) {\n // The listing is behind auth on this deployment. That still\n // proves the router is there, which is what is being tested.\n return { verdict: \"ok\",\nmeaning: \"the functions router is mounted (its listing requires auth)\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"the functions router did not mount — no functions directory was found at build time, or it held no functions, so every function on this project is unreachable\"\n };\n }\n if (status >= 500) return serverError(\"the functions router throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for the functions listing\" };\n },\n needsBody: true,\n refine: (body, t) => {\n const names = functionNames(body);\n if (!names) return null;\n if (t.fn && !names.includes(t.fn)) {\n // Definitive, because the listing is authoritative — no guessing\n // from a 404 that could equally mean the router is absent.\n return {\n verdict: \"fail\",\n meaning:\n `the router is mounted but no function is named \"${t.fn}\" — it loaded ${names.length}: ` +\n `${names.join(\", \")}`\n };\n }\n const found = t.fn ? `, including ${t.fn}` : \"\";\n return {\n verdict: \"ok\",\n meaning: `the functions router is mounted and loaded ${names.length} function${names.length === 1 ? \"\" : \"s\"}${found}`\n };\n }\n }\n];\n\n/** The function names out of a listing body, or null when it is not one. */\nexport function functionNames(body: unknown): string[] | null {\n const list = (body as { functions?: unknown } | null | undefined)?.functions;\n if (!Array.isArray(list)) return null;\n const names = list\n .map((f) => (f as { name?: unknown })?.name)\n .filter((n): n is string => typeof n === \"string\");\n return names.length === list.length ? names : null;\n}\n\nexport interface ProbeResult {\n id: string;\n label: string;\n method: string;\n url: string;\n status: number | null;\n ms: number;\n verdict: Verdict;\n meaning: string;\n healthy: string;\n /**\n * Whether the STATUS CODE alone looked healthy. False means the code itself\n * was wrong; true with a failing `verdict` means the code was fine and the\n * body carried the bad news (a named function that did not load). The\n * summary uses this so it never tells you to expect a 200 you already got.\n */\n statusOk: boolean;\n}\n\n/** Milliseconds before a probe is treated as unanswered. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on a probe body we will parse. The only body read is the function\n * listing; anything larger is a page we have no use for, and a debug command\n * must not be the thing that runs a machine out of memory.\n */\nconst MAX_PROBE_BODY_BYTES = 256 * 1024;\n\n/**\n * Run one probe. A transport failure is a `null` status, never a thrown error:\n * \"nothing answered\" is a diagnosis in its own right and the other probes still\n * need to run.\n */\nexport async function runProbe(origin: string, spec: ProbeSpec, targets: ProbeTargets): Promise<ProbeResult> {\n const url = `${origin}${spec.path(targets)}`;\n const started = Date.now();\n let status: number | null = null;\n let body: unknown;\n try {\n const res = await fetch(url, {\n method: spec.method,\n headers: spec.body ? { \"Content-Type\": \"application/json\" } : undefined,\n body: spec.body ? JSON.stringify(spec.body) : undefined,\n redirect: \"manual\",\n signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)\n });\n status = res.status;\n if (spec.needsBody && res.ok) {\n const text = await res.text();\n if (text.length <= MAX_PROBE_BODY_BYTES) {\n try {\n body = JSON.parse(text);\n } catch {\n // Not JSON — `refine` returns null and the status reading stands.\n }\n }\n }\n } catch {\n status = null;\n }\n const statusReading = spec.interpret(status);\n // The body can only sharpen a reading, never invent one where the request\n // failed outright.\n const reading = (status !== null && spec.refine?.(body, targets)) || statusReading;\n return {\n statusOk: statusReading.verdict === \"ok\",\n id: spec.id,\n label: spec.label,\n method: spec.method,\n url,\n status,\n ms: Date.now() - started,\n verdict: reading.verdict,\n meaning: reading.meaning,\n healthy: spec.healthy\n };\n}\n\n/** The worst verdict across probes — what the command's exit code keys off. */\nexport function overallVerdict(results: ProbeResult[]): Verdict {\n if (results.some((r) => r.verdict === \"fail\")) return \"fail\";\n if (results.some((r) => r.verdict === \"unknown\")) return \"unknown\";\n if (results.some((r) => r.verdict === \"warn\")) return \"warn\";\n return \"ok\";\n}\n\nfunction verdictMark(v: Verdict): string {\n switch (v) {\n case \"ok\":\n return chalk.green(\"✓\");\n case \"warn\":\n return chalk.yellow(\"!\");\n case \"fail\":\n return chalk.red(\"✗\");\n default:\n return chalk.gray(\"?\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Log parsing\n ═══════════════════════════════════════════════════════════════\n\n `runtime-logs` renders each line as `<rfc3339> [<pod>] <text>`, where <text>\n is normally the application's structured JSON. These helpers unwrap that so\n the derived views (errors / requests / boot) work on the payload rather than\n on the transport's formatting.\n*/\n\nexport interface ParsedLogLine {\n ts: string | null;\n pod: string | null;\n text: string;\n}\n\nconst LOG_PREFIX_RE = /^(?:(\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z?)\\s+)?(?:\\[([^\\]]+)\\]\\s+)?([\\s\\S]*)$/;\n\nexport function parseLogLine(line: string): ParsedLogLine {\n const m = LOG_PREFIX_RE.exec(line);\n if (!m) return { ts: null,\npod: null,\ntext: line };\n return { ts: m[1] ?? null,\npod: m[2] ?? null,\ntext: m[3] ?? \"\" };\n}\n\n/**\n * Lines an operator scanning for a fault wants to see.\n *\n * Matches the structured `severity` field first, then the shapes that show up\n * in unstructured output. `refus`/`denied` are in the list because a permission\n * failure often logs at info level and is exactly what one is hunting for.\n */\nexport function isErrorLine(text: string): boolean {\n return /\"(?:severity|level)\":\\s*\"(?:ERROR|WARN(?:ING)?|error|warn)\"|\\bError:|\\bERR!|refus|denied|EACCES|ECONNREFUSED/i.test(\n text\n );\n}\n\nexport interface RequestLogEntry {\n status: number | null;\n method: string;\n path: string;\n latencyMs: number | null;\n}\n\n/**\n * Pull an HTTP request record out of a log line, or null when it is not one.\n *\n * Only structured request lines are recognised. Guessing at prose would produce\n * a table with invented columns, which is worse than a short one.\n */\nexport function parseRequestLine(text: string): RequestLogEntry | null {\n const start = text.indexOf(\"{\");\n if (start === -1) return null;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text.slice(start)) as Record<string, unknown>;\n } catch {\n return null;\n }\n if (parsed.message !== \"request\" && parsed.msg !== \"request\") return null;\n\n const num = (v: unknown): number | null => {\n const n = typeof v === \"string\" ? Number(v) : typeof v === \"number\" ? v : NaN;\n return Number.isFinite(n) ? n : null;\n };\n return {\n status: num(parsed.status),\n method: typeof parsed.method === \"string\" ? parsed.method : \"\",\n path: typeof parsed.path === \"string\" ? parsed.path : \"\",\n latencyMs: num(parsed.latencyMs ?? parsed.durationMs)\n };\n}\n\n/**\n * Startup lines: what the server *decided* it was going to do. Which storage\n * backend it bound, which functions it loaded, whether auth tables were found.\n * This is the fastest way to tell a misconfiguration from a runtime fault.\n */\nexport function isBootLine(text: string): boolean {\n // \"Loaded custom functions\" and \"Loaded cron job…\" are 0.25's words for what\n // earlier runtimes logged as \"Mounted …\"; both are what a deployment runs.\n return /storage|Loaded (?:custom )?function|Loaded cron|Cron jobs scheduled|Cron scheduler|Mounted|Auth tables|Server running|listening|Refusing|migrat/i.test(text);\n}\n\n/** Render a number of seconds back as the compact duration a user would type. */\nexport function formatDuration(seconds: number): string {\n if (seconds % 86400 === 0 && seconds >= 86400) return `${seconds / 86400}d`;\n if (seconds % 3600 === 0 && seconds >= 3600) return `${seconds / 3600}h`;\n if (seconds % 60 === 0 && seconds >= 60) return `${seconds / 60}m`;\n return `${seconds}s`;\n}\n\n/**\n * Parse a duration like `15m`, `2h`, `90s`, `1d` (or a bare number of seconds)\n * into seconds. Returns null when it is not a duration.\n */\nexport function parseSince(input: string | undefined): number | null {\n if (!input) return null;\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([smhd])?$/i.exec(input.trim());\n if (!m) return null;\n const value = parseFloat(m[1]);\n const unit = (m[2] || \"s\").toLowerCase();\n const mult = unit === \"s\" ? 1 : unit === \"m\" ? 60 : unit === \"h\" ? 3600 : 86400;\n return Math.round(value * mult);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Shared fetches\n ═══════════════════════════════════════════════════════════════ */\n\n/** One pod's entry in a `runtime-logs` answer. */\nexport interface RuntimeLogsPod {\n pod: string;\n state: string;\n /** Lines this pod returned. */\n lines: number;\n message: string | null;\n hint: string | null;\n /** The server's per-pod BYTE budget cut this pod's output. Says nothing about the line limit. */\n truncated?: boolean;\n}\n\nexport interface RuntimeLogsResponse {\n logs?: string;\n pods?: RuntimeLogsPod[];\n ordering?: string;\n /** A byte budget or the pod-count ceiling cut the result. Says nothing about the line limit. */\n truncated?: boolean;\n state?: string;\n message?: string | null;\n}\n\n/**\n * The most lines `runtime-logs` returns per pod.\n *\n * The control plane enforces this (`MAX_TAIL_LINES` in\n * `saas/backend/functions/runtime-logs.ts`) by clamping a larger `tailLines`\n * without saying so: its answer names neither the limit nor the value it used.\n * `--tail 200000` therefore came back as 2000 lines reported as untruncated.\n * The CLI clamps first, with the same number, so the lowering is something it\n * can print rather than something that happened out of sight.\n */\nexport const SERVER_MAX_TAIL_LINES = 2000;\n\n/** How many lines per pod a read asks for, and why that may be less than requested. */\nexport interface TailLimit {\n /** What `--tail` asked for, or the view's default. */\n requested: number;\n /** What is sent: `requested`, lowered to {@link SERVER_MAX_TAIL_LINES}. */\n applied: number;\n /** Whether `--tail` was given, so a message can name the flag or the default. */\n explicit: boolean;\n /** Set when `applied < requested`: the sentence that says so. */\n note: string | null;\n}\n\nexport function resolveTail(requested: number, explicit: boolean): TailLimit {\n const applied = Math.min(requested, SERVER_MAX_TAIL_LINES);\n return {\n requested,\n applied,\n explicit,\n note:\n applied < requested\n ? `--tail ${requested} was lowered to ${applied}: the control plane returns at most ` +\n `${SERVER_MAX_TAIL_LINES} lines per pod.`\n : null\n };\n}\n\n/** Read `--tail`, refusing anything that is not a positive whole number. */\nfunction tailFromFlag(value: number | undefined, fallback: number): TailLimit {\n if (value === undefined) return resolveTail(fallback, false);\n if (!Number.isInteger(value) || value <= 0) {\n fail(`--tail must be a positive whole number of lines; received \"${value}\".`, undefined, \"usage\");\n }\n return resolveTail(value, true);\n}\n\n/** What one pod's lines actually cover. */\nexport interface PodCoverage extends RuntimeLogsPod {\n /** Earliest and latest timestamps among the lines this pod returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n /** A limit cut what this pod would otherwise have returned for the window. */\n truncated: boolean;\n /** Which limit: the per-pod line limit, or the server's byte budget. */\n truncatedBy: \"tail\" | \"bytes\" | null;\n /** The plain explanation, when truncated. */\n truncatedReason: string | null;\n /**\n * Every line this pod holds in the window came back. With no window (read\n * from the start), its first line is the start of its log.\n */\n complete: boolean;\n}\n\n/** The window asked for against the window delivered. */\nexport interface LogCoverage {\n /** Start of the window asked for, ISO. Null when reading each pod from its start. */\n requestedFrom: string | null;\n /** Earliest and latest timestamps across every line returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n pods: PodCoverage[];\n truncated: boolean;\n truncatedReasons: string[];\n}\n\n/** A span of milliseconds as `29d 23h`, `2h 5m`, `35m`, `40s`. */\nexport function formatSpan(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n const d = Math.floor(s / 86400);\n const h = Math.floor((s % 86400) / 3600);\n const m = Math.floor((s % 3600) / 60);\n if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`;\n if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;\n if (m > 0) return `${m}m`;\n return `${s}s`;\n}\n\nfunction timestampRange(lines: ParsedLogLine[]): { first: string | null; last: string | null } {\n let first: { text: string; ms: number } | null = null;\n let last: { text: string; ms: number } | null = null;\n for (const l of lines) {\n if (!l.ts) continue;\n const ms = Date.parse(l.ts);\n if (Number.isNaN(ms)) continue;\n if (!first || ms < first.ms) first = { text: l.ts,\nms };\n if (!last || ms > last.ms) last = { text: l.ts,\nms };\n }\n return { first: first?.text ?? null,\nlast: last?.text ?? null };\n}\n\n/**\n * Compare what a read covered with what it asked for.\n *\n * The server's `truncated` describes only its byte budgets and pod ceiling, so\n * a pod that filled the line limit came back marked complete however much of\n * the window it left unread. The line limit is the cut that matters most, and\n * it is detected here: a pod that returned as many lines as the limit, whose\n * earliest line is later than the start of the window, was cut by it.\n *\n * Filling the limit is the half that separates a cut from a young pod. A pod\n * that started an hour ago also has no line older than an hour; it returned\n * fewer lines than the limit, so what came back is its whole log, and nothing\n * was cut.\n */\nexport function assessCoverage(opts: {\n res: RuntimeLogsResponse;\n lines: ParsedLogLine[];\n /** The window asked for. Null reads each pod from its start. */\n sinceSeconds: number | null;\n tail: TailLimit;\n now: number;\n}): LogCoverage {\n const { res, lines, sinceSeconds, tail, now } = opts;\n const windowStartMs = sinceSeconds === null ? null : now - sinceSeconds * 1000;\n const requestedFrom = windowStartMs === null ? null : new Date(windowStartMs).toISOString();\n const limitName = tail.note\n ? `the control plane's ceiling of ${tail.applied} lines per pod`\n : tail.explicit\n ? `the --tail ${tail.applied} limit`\n : `the default of ${tail.applied} lines per pod`;\n // Only worth saying when raising it would read further back.\n const raise = tail.applied < SERVER_MAX_TAIL_LINES\n ? ` Raise --tail (at most ${SERVER_MAX_TAIL_LINES}) to read further back.`\n : ` The control plane returns only each pod's newest ${SERVER_MAX_TAIL_LINES}, so older lines cannot be read from here.`;\n\n const pods: PodCoverage[] = (res.pods ?? []).map((p) => {\n const range = timestampRange(lines.filter((l) => l.pod === p.pod));\n const base = { ...p,\nfirstTimestamp: range.first,\nlastTimestamp: range.last };\n if (p.state !== \"ok\") {\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: false };\n }\n if (p.truncated) {\n return {\n ...base,\n truncated: true,\n truncatedBy: \"bytes\" as const,\n truncatedReason:\n `${p.pod}: the control plane's per-pod byte budget cut this pod's output short` +\n (range.first ? ` — what fit runs ${range.first} to ${range.last}.` : \".\"),\n complete: false\n };\n }\n const firstMs = range.first ? Date.parse(range.first) : null;\n const startsLate = windowStartMs === null || firstMs === null || firstMs > windowStartMs;\n if (p.lines >= tail.applied && startsLate) {\n let reason: string;\n if (firstMs === null) {\n reason = `${p.pod}: returned ${p.lines} lines, ${limitName}; they carry no timestamps, so how far back they reach is unknown.`;\n } else if (sinceSeconds !== null && windowStartMs !== null) {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, and the earliest is ${range.first} — ` +\n `${formatSpan(firstMs - windowStartMs)} after the ${formatDuration(sinceSeconds)} ` +\n `window begins (${requestedFrom}). Lines in between were not read.${raise}`;\n } else {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, so its log before ${range.first} ` +\n `was not read.${raise}`;\n }\n return { ...base,\ntruncated: true,\ntruncatedBy: \"tail\" as const,\ntruncatedReason: reason,\ncomplete: false };\n }\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: true };\n });\n\n const truncatedReasons = pods.flatMap((p) => (p.truncatedReason ? [p.truncatedReason] : []));\n // The server's flag also covers cuts no single pod owns: its total byte\n // budget across pods, and the cap on how many pods it reads.\n if (res.truncated && !pods.some((p) => p.truncatedBy === \"bytes\")) {\n truncatedReasons.push(\n \"The control plane trimmed the combined result (its total byte budget, or the most pods it reads at once); the oldest lines were dropped.\"\n );\n }\n const overall = timestampRange(lines);\n return {\n requestedFrom,\n firstTimestamp: overall.first,\n lastTimestamp: overall.last,\n pods,\n truncated: Boolean(res.truncated) || pods.some((p) => p.truncated),\n truncatedReasons\n };\n}\n\nasync function fetchRuntimeLogs(\n client: CloudClient,\n projectId: string,\n opts: { sinceSeconds?: number; tailLines?: number; previous?: boolean }\n): Promise<RuntimeLogsResponse> {\n const params = new URLSearchParams();\n if (opts.sinceSeconds !== undefined) params.set(\"sinceSeconds\", String(opts.sinceSeconds));\n if (opts.tailLines !== undefined) params.set(\"tailLines\", String(opts.tailLines));\n if (opts.previous) params.set(\"previous\", \"true\");\n params.set(\"timestamps\", \"true\");\n const qs = params.toString();\n return client.functions.invoke<RuntimeLogsResponse>(\"runtime-logs\", undefined, {\n method: \"GET\",\n path: `${projectId}${qs ? `?${qs}` : \"\"}`\n });\n}\n\n/** Print the per-pod states runtime-logs reports, including its hints. */\nfunction printPodStates(res: RuntimeLogsResponse): void {\n if (res.state === \"no_pods\") {\n console.log(chalk.yellow(` ${res.message ?? \"No pods are running for this project.\"}`));\n console.log(\"\");\n return;\n }\n for (const p of res.pods ?? []) {\n if (p.state === \"ok\") continue;\n console.log(` ${chalk.yellow(p.pod)} ${chalk.gray(`(${p.state})`)}`);\n if (p.message) console.log(chalk.gray(` ${p.message}`));\n // The hint is the actionable half — a crash-looping container's reason\n // is in its PREVIOUS instance, and that is only discoverable if we say so.\n if (p.hint) console.log(chalk.cyan(` → ${p.hint}`));\n }\n}\n\n/**\n * The window asked for, the window delivered, and every cut between them.\n * Printed after the lines, where a reader's eye is when the output ends.\n */\nfunction printCoverage(coverage: LogCoverage, tail: TailLimit): void {\n const asked = coverage.requestedFrom ? `from ${coverage.requestedFrom}` : \"from each pod's start\";\n const got = coverage.firstTimestamp && coverage.lastTimestamp\n ? `${coverage.firstTimestamp} → ${coverage.lastTimestamp} ` +\n `(${formatSpan(Date.parse(coverage.lastTimestamp) - Date.parse(coverage.firstTimestamp))})`\n : \"no timestamped lines\";\n console.log(chalk.gray(` Asked for: ${asked}`));\n console.log(chalk.gray(` Returned: ${got}`));\n if (tail.note) console.log(chalk.yellow(` ! ${tail.note}`));\n if (coverage.truncated) {\n console.log(chalk.yellow(\" ! Truncated — the lines above do not cover the window asked for:\"));\n for (const reason of coverage.truncatedReasons) console.log(chalk.yellow(` ${reason}`));\n }\n console.log(\"\");\n}\n\n/**\n * Resolve the public origin a project is served at — or `--host`, when given.\n *\n * Shared with `rebase cloud cron`, which reads the runtime at the same address\n * `debug health` probes.\n */\nexport async function resolveOrigin(\n rawArgs: string[],\n client: CloudClient,\n url: string,\n projectId: string\n): Promise<string> {\n const parsed = arg({ \"--host\": String }, { argv: rawArgs.slice(3),\npermissive: true });\n if (parsed[\"--host\"]) {\n const h = parsed[\"--host\"].trim().replace(/\\/+$/, \"\");\n return /^https?:\\/\\//.test(h) ? h : `https://${h}`;\n }\n\n const [project, baseDomain] = await Promise.all([\n client.data.collection(\"projects\").findById(projectId) as Promise<\n { subdomain?: string; host?: string; customDomain?: string } | undefined\n >,\n fetchTenantBaseDomain(client, url)\n ]);\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`);\n\n const host = projectHost(project, baseDomain);\n if (!host) {\n fail(\n \"Could not determine the public URL for this project.\",\n \"It may never have been deployed. Pass --host <hostname> to probe an address directly.\"\n );\n }\n return `https://${host}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: health\n ═══════════════════════════════════════════════════════════════ */\n\nasync function healthCommand(rawArgs: string[]): Promise<void> {\n // Strict: `--collecton users` used to be dropped and the probe then ran\n // against the default collection while reporting on the one asked for.\n const { flags: parsed } = parseCloudArgs({\n spec: HEALTH_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug health\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const targets: ProbeTargets = {\n collection: parsed[\"--collection\"] || \"users\",\n // Optional: the listing endpoint proves the mount on its own. A name\n // here additionally asserts that this particular function loaded.\n fn: parsed[\"--function\"]\n };\n\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const origin = await resolveOrigin(rawArgs, client, url, projectId);\n\n // Sequential, not Promise.all: five simultaneous requests to a struggling\n // pod is a small load test, and the latency column would then measure our\n // own contention rather than the endpoint's.\n const results: ProbeResult[] = [];\n for (const spec of PROBES) results.push(await runProbe(origin, spec, targets));\n\n const overall = overallVerdict(results);\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🩺 Health — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${origin}`));\n console.log(\"\");\n const width = Math.max(...results.map((r) => r.label.length));\n for (const r of results) {\n const code = r.status === null ? chalk.red(\"---\") : String(r.status);\n console.log(\n ` ${verdictMark(r.verdict)} ${chalk.bold(r.label.padEnd(width))} ${code.padStart(3)} ${chalk.gray(`${r.ms}ms`)}`\n );\n console.log(` ${chalk.gray(r.meaning)}`);\n }\n console.log(\"\");\n if (overall === \"ok\") {\n console.log(chalk.green(\" Everything reachable and wired as expected.\"));\n } else {\n const bad = results.filter((r) => r.verdict === \"fail\" || r.verdict === \"warn\");\n console.log(chalk.gray(` ${bad.length} of ${results.length} check${bad.length === 1 ? \"\" : \"s\"} need attention.`));\n // Only where the status code itself was wrong — restating\n // \"expected 200\" under a probe that returned 200 reads as a bug.\n const wrongStatus = bad.filter((r) => !r.statusOk);\n if (wrongStatus.length > 0) {\n console.log(chalk.gray(\" A healthy deployment answers:\"));\n for (const r of wrongStatus) {\n console.log(chalk.gray(` ${r.label.padEnd(width)} ${r.healthy}`));\n }\n }\n }\n console.log(\"\");\n },\n { origin,\noverall,\nprobes: results }\n );\n\n // A failing probe is a failing command — this is meant to be usable in a\n // deploy script's `if`, not only read by a human.\n if (overall === \"fail\") process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: logs / errors / requests / boot\n ═══════════════════════════════════════════════════════════════ */\n\n/** What `debug logs`, `errors` and `boot` parse. Their help pairs against this. */\nexport const LOG_VIEW_FLAGS = {\n \"--since\": String,\n \"--tail\": Number,\n \"--previous\": Boolean\n} as const;\n\n/** What `debug requests` parses. */\nexport const REQUESTS_FLAGS = {\n \"--since\": String,\n \"--tail\": Number\n} as const;\n\n/** What `debug health` parses. */\nexport const HEALTH_FLAGS = {\n \"--collection\": String,\n \"--function\": String,\n // `--host` is read again inside `resolveOrigin`, which needs it before\n // the client exists; declared here because THIS is the parse that\n // decides whether the line is accepted at all.\n \"--host\": String\n} as const;\n\ninterface LogViewOptions {\n /** Keep only lines matching this. Omit to keep everything. */\n filter?: (text: string) => boolean;\n /** Default lookback when --since is not given. Null reads each pod from its start. */\n defaultSinceSeconds: number | null;\n /** Lines read per pod when --tail is not given. */\n defaultTail: number;\n /** Max lines rendered. */\n limit: number;\n title: string;\n /**\n * The lines wanted are the first a pod wrote, so a read that did not reach\n * a pod's start has not looked where they are — see {@link bootReach}.\n */\n needsStart?: boolean;\n}\n\nconst LOG_VIEWS = {\n logs: { defaultSinceSeconds: 900,\ndefaultTail: 500,\nlimit: 200,\ntitle: \"📄 Logs\" },\n errors: { filter: isErrorLine,\ndefaultSinceSeconds: 3600,\ndefaultTail: 500,\nlimit: 40,\ntitle: \"🔥 Errors\" },\n boot: {\n filter: isBootLine,\n // No window, and the most lines the control plane returns. Startup\n // happened when the pod started, which may have been days ago: a\n // 7-day window and the newest 500 lines missed it on any pod that had\n // served traffic since.\n defaultSinceSeconds: null,\n defaultTail: SERVER_MAX_TAIL_LINES,\n limit: 25,\n title: \"🚀 Boot\",\n needsStart: true\n }\n} satisfies Record<string, LogViewOptions>;\n\nconst REQUESTS_DEFAULTS = { sinceSeconds: 900,\ntail: 1000 };\n\n/** Read `--since`, refusing anything that is not a duration. Undefined when it was not given. */\nfunction sinceFromFlag(sinceArg: string | undefined): number | undefined {\n if (sinceArg === undefined) return undefined;\n const seconds = parseSince(sinceArg);\n if (seconds === null) fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n return seconds;\n}\n\nfunction windowLabel(sinceSeconds: number | null): string {\n return sinceSeconds === null ? \"since each pod started\" : `last ${formatDuration(sinceSeconds)}`;\n}\n\n/**\n * Whether a boot read reached each pod's start, which is where its startup\n * lines are. A pod whose read was cut has not been looked at there, so finding\n * no startup lines in it means nothing — and a line from later in its life\n * that happens to mention `storage` is not its startup.\n *\n * Under `--since` a pod is never counted as reached: a complete read of the\n * window starts at the pod's first line only if the pod started inside it, and\n * nothing in the answer says whether it did.\n */\nexport function bootReach(pods: PodCoverage[], sinceSeconds: number | null): {\n reachedStart: boolean;\n unreached: string[];\n} {\n const unreached = pods\n .filter((p) => p.state === \"ok\" && (!p.complete || sinceSeconds !== null))\n .map((p) => p.pod);\n return { reachedStart: unreached.length === 0,\nunreached };\n}\n\nasync function logView(rawArgs: string[], view: LogViewOptions): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: LOG_VIEW_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug logs|errors|boot\n command: \"cloud debug\",\n maxPositionals: 0\n });\n\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? view.defaultSinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], view.defaultTail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, {\n sinceSeconds: sinceSeconds ?? undefined,\n tailLines: tail.applied,\n previous: Boolean(parsed[\"--previous\"])\n });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const all = (res.logs ?? \"\").split(\"\\n\").filter((l) => l !== \"\");\n const parsedLines = all.map(parseLogLine);\n const kept = view.filter ? parsedLines.filter((l) => view.filter!(l.text)) : parsedLines;\n const shown = kept.slice(-view.limit);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n const reach = view.needsStart ? bootReach(coverage.pods, sinceSeconds) : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` ${view.title} — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" (nothing matched in what was read)\"));\n console.log(\"\");\n } else {\n for (const l of shown) console.log(` ${l.pod ? chalk.gray(`[${l.pod}] `) : \"\"}${l.text}`);\n console.log(\"\");\n if (kept.length > shown.length) {\n console.log(chalk.gray(` (showing the last ${shown.length} of ${kept.length} matching lines)`));\n console.log(\"\");\n }\n }\n printCoverage(coverage, tail);\n if (reach && !reach.reachedStart) {\n const which = reach.unreached.join(\", \");\n console.log(\n chalk.yellow(\n sinceSeconds === null\n ? ` ! The start of ${which} was not read, so its startup lines are not among the lines above.`\n : ` ! The start of ${which} may not have been read: --since limits the read to a recent window. ` +\n \"Drop it to read each pod from its start.\"\n )\n );\n console.log(\"\");\n }\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n state: res.state ?? null,\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n ...(reach ? { reachedStart: reach.reachedStart,\nunreachedPods: reach.unreached } : {}),\n matched: kept.length,\n lines: shown\n }\n );\n}\n\nasync function requestsCommand(rawArgs: string[]): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: REQUESTS_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug requests\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? REQUESTS_DEFAULTS.sinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], REQUESTS_DEFAULTS.tail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, { sinceSeconds,\ntailLines: tail.applied });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const parsedLines = (res.logs ?? \"\")\n .split(\"\\n\")\n .filter((l) => l !== \"\")\n .map(parseLogLine);\n const entries = parsedLines\n .map((l) => parseRequestLine(l.text))\n .filter((e): e is RequestLogEntry => e !== null);\n const shown = entries.slice(-40);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 🌐 Requests — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" No structured request lines in what was read.\"));\n console.log(chalk.gray(\" (this view needs the server's request logging; try `debug logs`)\"));\n console.log(\"\");\n printCoverage(coverage, tail);\n return;\n }\n for (const e of shown) {\n const status = e.status ?? 0;\n const color = status >= 500 ? chalk.red : status >= 400 ? chalk.yellow : chalk.green;\n console.log(\n ` ${color(String(e.status ?? \"---\").padStart(3))} ${e.method.padEnd(6)} ${e.path.slice(0, 70).padEnd(70)} ${chalk.gray(\n e.latencyMs === null ? \"\" : `${e.latencyMs}ms`\n )}`\n );\n }\n console.log(\"\");\n printCoverage(coverage, tail);\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n requests: shown\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: pod\n ═══════════════════════════════════════════════════════════════ */\n\nasync function podCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface MetricsResponse {\n status?: string;\n cpu?: string | null;\n memory?: string | null;\n placement?: {\n cluster?: string | null;\n provider?: string | null;\n region?: string | null;\n namespace?: string | null;\n host?: string | null;\n image?: string | null;\n replicas?: { available?: number; desired?: number };\n };\n }\n\n let m: MetricsResponse;\n try {\n m = await client.functions.invoke<MetricsResponse>(\"metrics\", undefined, {\n method: \"GET\",\n path: projectId\n });\n } catch (e) {\n reportError(e, \"Failed to read workload placement\");\n }\n\n const p = m.placement ?? {};\n const replicas = p.replicas ?? {};\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ☸ Workload — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n keyValues([\n [\"Status\", m.status ? colorStatus(m.status === \"running\" ? \"active\" : m.status) : undefined],\n [\n \"Replicas\",\n replicas.desired === undefined\n ? undefined\n : `${replicas.available ?? 0} / ${replicas.desired} available`\n ],\n [\"Namespace\", p.namespace],\n [\"Cluster\", p.cluster],\n [\"Region\", [p.provider, p.region].filter(Boolean).join(\" · \") || undefined],\n [\"Host\", p.host],\n [\"Image\", p.image],\n // Reported as-is: the metrics function returns null for \"not\n // measurable\", which must not render as a number.\n [\"CPU\", m.cpu ?? undefined],\n [\"Memory\", m.memory ?? undefined]\n ]);\n console.log(\"\");\n if ((replicas.available ?? 0) === 0 && (replicas.desired ?? 0) > 0) {\n console.log(chalk.yellow(\" No replica is available — the pod is not passing its readiness check.\"));\n console.log(chalk.gray(\" See why with: \") + chalk.bold(\"rebase cloud debug logs --previous\"));\n console.log(\"\");\n }\n },\n { status: m.status ?? null,\nplacement: p }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: db\n ═══════════════════════════════════════════════════════════════ */\n\nasync function dbDebugCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface DbInfo {\n type?: string;\n host?: string | null;\n port?: string | null;\n database?: string | null;\n username?: string | null;\n passwordAvailable?: boolean;\n unavailableReason?: string | null;\n directAccess?: {\n via: \"tunnel\";\n kubectl?: { namespace: string; service: string; localPort: number; remotePort: number };\n } | null;\n }\n\n let info: DbInfo;\n try {\n info = await client.functions.invoke<DbInfo>(\"db-info\", undefined, { method: \"GET\",\npath: projectId });\n } catch (e) {\n reportError(e, \"Failed to read database connection info\");\n }\n\n // The host above is a Service inside the platform's cluster, so `debug db`\n // has to say what to do about that. It used to print `kubectl port-forward\n // -n rebase-tenant-…`, which needs a kubeconfig for OUR cluster: a customer\n // has none, and nothing in the platform issues one. The tunnel is the\n // remedy a reader can actually run.\n const access = info.directAccess;\n const connectCmd = access ? \"rebase cloud db connect\" : null;\n const LOCAL_PORT = 5432;\n const psqlCmd =\n access && info.username && info.database\n ? `psql -h 127.0.0.1 -p ${LOCAL_PORT} -U ${info.username} -d ${info.database}`\n : null;\n // Only for a cluster the customer owns, where the credentials are theirs.\n const kubectlCmd = access?.kubectl\n ? `kubectl port-forward -n ${access.kubectl.namespace} svc/${access.kubectl.service} `\n + `${access.kubectl.localPort}:${access.kubectl.remotePort}`\n : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🐘 Database — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (info.unavailableReason) {\n console.log(chalk.yellow(` ${info.unavailableReason}`));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Type\", info.type],\n [\"Host\", info.host],\n [\"Port\", info.port],\n [\"Database\", info.database],\n [\"Username\", info.username],\n [\"Password\", info.passwordAvailable ? chalk.gray(\"stored — not shown here\") : chalk.yellow(\"none stored\")]\n ]);\n console.log(\"\");\n if (connectCmd) {\n // Printed rather than run. Opening a tunnel and a database shell\n // is not something a command called `debug` should do implicitly.\n console.log(chalk.gray(\" That host is inside the platform's cluster and does not resolve here.\"));\n console.log(chalk.gray(\" To reach the database from this machine:\"));\n console.log(\"\");\n console.log(` ${connectCmd}`);\n if (psqlCmd) console.log(` ${psqlCmd}`);\n console.log(\"\");\n if (kubectlCmd) {\n console.log(chalk.gray(\" Or, on your own cluster:\"));\n console.log(` ${kubectlCmd}`);\n console.log(\"\");\n }\n if (info.passwordAvailable) {\n console.log(\n chalk.gray(\" Get the password with: \") + chalk.bold(\"rebase cloud db info --reveal\")\n );\n console.log(\"\");\n }\n }\n },\n {\n type: info.type ?? null,\n host: info.host ?? null,\n port: info.port ?? null,\n database: info.database ?? null,\n username: info.username ?? null,\n passwordAvailable: Boolean(info.passwordAvailable),\n connectCommand: connectCmd,\n kubectlCommand: kubectlCmd,\n psqlCommand: psqlCmd\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Everything the switch below dispatches, for the did-you-mean. `workload` is\n * the older spelling of `pod` and stays out of it: suggesting the name we no\n * longer print in the help would teach the wrong one.\n */\nconst DEBUG_SUBCOMMANDS = [\"health\", \"logs\", \"errors\", \"boot\", \"requests\", \"pod\", \"db\"] as const;\n\nexport async function debugCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case undefined:\n case \"health\":\n // Bare `rebase cloud debug` runs the probes: it is the answer to\n // \"something is wrong\" more often than any other view here.\n await healthCommand(rawArgs);\n break;\n case \"logs\":\n case \"errors\":\n case \"boot\":\n await logView(rawArgs, LOG_VIEWS[action]);\n break;\n case \"requests\":\n await requestsCommand(rawArgs);\n break;\n case \"pod\":\n case \"workload\":\n await podCommand(rawArgs);\n break;\n case \"db\":\n await dbDebugCommand(rawArgs);\n break;\n case \"help\":\n case \"--help\":\n printDebugHelp();\n break;\n default:\n // One refusal path in both modes. The terminal branch used to print\n // the whole help page to STDOUT — the results stream — after a\n // command that produced no result, which is the same shape the\n // index dispatcher was fixed out of. `fail` writes the machine\n // envelope under `--json` and one red line to stderr otherwise, and\n // the words come from the shared builder so the human line and the\n // machine one cannot drift apart: it carries the near-miss when\n // there is one, and names the page for the rest.\n fail(unknownCommandMessage(action, DEBUG_SUBCOMMANDS, \"cloud debug\"), undefined, \"unknown_command\");\n }\n}\n\n/**\n * The log flags as one action's help lists them, with THAT action's defaults.\n * They were one group-wide list saying \"Default: 500\", which was true of two of\n * the four actions, and offered `--previous` to `requests`, which rejects it.\n */\nfunction logFlagHelp(defaults: { sinceSeconds: number | null; tail: number }, previous: boolean): Array<[string, string]> {\n const flags: Array<[string, string]> = [\n [\n \"--since <dur>\",\n defaults.sinceSeconds === null\n ? \"Only lines this recent: 90s, 15m, 2h, 1d. Default: from each pod's start\"\n : `Lookback window: 90s, 15m, 2h, 1d. Default: ${formatDuration(defaults.sinceSeconds)}`\n ],\n [\"--tail <n>\", `Newest lines to read per pod, at most ${SERVER_MAX_TAIL_LINES}. Default: ${defaults.tail}`]\n ];\n if (previous) flags.push([\"--previous\", \"Read the CRASHED container instance, where the reason lives\"]);\n return flags;\n}\n\nfunction logViewFlagHelp(view: LogViewOptions): Array<[string, string]> {\n return logFlagHelp({ sinceSeconds: view.defaultSinceSeconds,\ntail: view.defaultTail }, true);\n}\n\nexport function printDebugHelp(): void {\n printGroupHelp({\n command: \"cloud debug\",\n title: \"Find out why a deployed project is misbehaving\",\n actions: [\n {\n action: \"health\",\n section: \"End-to-end\",\n description: \"Probe the live URL and explain every status code (the default)\",\n flags: [\n [\"--host <hostname>\", \"Probe this address instead of the project's own\"],\n [\"--collection <name>\", \"Collection for the unauth-read probe. Default: users\"],\n [\"--function <name>\", \"Also assert this function loaded, against the listing\"]\n ]\n },\n { action: \"logs\",\nsection: \"Runtime\",\ndescription: \"Recent application logs\",\nflags: logViewFlagHelp(LOG_VIEWS.logs) },\n { action: \"errors\",\nsection: \"Runtime\",\ndescription: \"Error and warning lines only\",\nflags: logViewFlagHelp(LOG_VIEWS.errors) },\n { action: \"requests\",\nsection: \"Runtime\",\ndescription: \"HTTP requests the server logged: status, path, latency\",\nflags: logFlagHelp(REQUESTS_DEFAULTS, false) },\n { action: \"boot\",\nsection: \"Runtime\",\ndescription: \"What the server decided at startup: storage, functions, auth\",\nflags: logViewFlagHelp(LOG_VIEWS.boot) },\n { action: \"pod\",\nsection: \"Runtime\",\ndescription: \"Replicas, image, namespace, cluster placement\" },\n { action: \"db\",\nsection: \"Data\",\ndescription: \"Connection shape and the port-forward recipe. Never the password\" }\n ],\n notes: [\n \"Everything here is read-only. `health` exits non-zero when a check fails, so it works in a\",\n \"deploy script. To restart a workload, use `rebase cloud restart`.\",\n \"The log views end with the window asked for, the window returned, and anything that cut\",\n `between them. The control plane returns at most ${SERVER_MAX_TAIL_LINES} lines per pod.`\n ]\n });\n}\n","/**\n * `rebase cloud cron` — a deployed project's scheduled jobs and their run\n * history, read with the `rebase cloud` login.\n *\n * ## Why this is not just `curl /api/admin/cron`\n *\n * The run history lives in the app itself — `rebase.cron_logs`, served by the\n * runtime's `/api/admin/cron/:id/logs` — behind the app's admin gate. A project\n * owner is signed in to the *control plane*, which that gate has never heard\n * of, and holds none of what it accepts: often no admin account in the app yet,\n * no `rk_` key, and rightly not the service key, which is admin on the whole API.\n * Pod stdout (`rebase cloud debug logs`) covers the last half hour or so; the\n * history covers every run.\n *\n * ## How it reaches the runtime\n *\n * Two legs, each over a channel `rebase cloud debug` already uses:\n *\n * 1. The control plane, as the signed-in person (`debug logs`' channel):\n * `POST /api/functions/runtime-token/<project>` checks the caller may read\n * this project's logs and answers a token — `rpt_…`, ES256, bound to this\n * project, `cron:read` only, minutes long.\n * 2. The runtime at its public address (`debug health`'s channel), with that\n * token as the bearer. The runtime verifies it against the platform's\n * public key and grants `cron:read` and nothing else — it cannot trigger,\n * disable, or read anything but cron.\n *\n * A fresh token per command: nothing is cached, so nothing long-lived ends up\n * on this machine.\n */\nimport chalk from \"chalk\";\nimport type { CronJobLogEntry, CronJobStatus } from \"@rebasepro/types\";\nimport {\n requireClient,\n requireProject,\n parseCloudArgs,\n displayProjectRef,\n emit,\n fail,\n reportError,\n requireKnownAction,\n type CloudClient\n} from \"./context\";\nimport { resolveOrigin } from \"./debug\";\n\n/** The control-plane function that mints runtime tokens. */\nexport const RUNTIME_TOKEN_FUNCTION = \"runtime-token\";\n\n/** The one scope these commands ask the platform for. */\nexport const CRON_READ_SCOPE = \"cron:read\";\n\n/** Where the runtime serves its cron surface. */\nconst CRON_PATH = \"/api/admin/cron\";\n\nconst RUNTIME_TIMEOUT_MS = 15_000;\n\n/** What `runtime-token` answers. */\nexport interface RuntimeTokenResponse {\n /** `rpt_…` — the bearer the runtime accepts. */\n token: string;\n /** ISO timestamp; past it the runtime refuses the token. */\n expiresAt?: string;\n /** What the token was granted, which may be narrower than what was asked. */\n scopes?: string[];\n}\n\n/** What the runtime's `GET /api/admin/cron` answers. */\ninterface CronListResponse {\n jobs?: CronJobStatus[];\n skipped?: number;\n rejected?: Array<{ id: string; name: string; schedule: string; reason: string }>;\n note?: string;\n}\n\n/** The runtime's error envelope, as far as these commands read it. */\ninterface ErrorEnvelope {\n error?: { code?: string; message?: string };\n}\n\n/**\n * A 404 that is about the route, not the project: the JSON envelope a Rebase\n * backend answers for an unmatched path, or the bare one a router answers\n * before that handler exists.\n */\nexport function isMissingRoute(message: string | undefined): boolean {\n return /^No route for |^(404 )?Not Found$/i.test((message ?? \"\").trim());\n}\n\n/**\n * Ask the control plane for a token the project's runtime will accept.\n *\n * A missing route means this control plane has no `runtime-token` function\n * yet, which is a different fix from \"no such project\" and is said so.\n */\nexport async function mintRuntimeToken(\n client: CloudClient,\n projectId: string,\n scopes: string[]\n): Promise<RuntimeTokenResponse> {\n let res: RuntimeTokenResponse;\n try {\n res = await client.functions.invoke<RuntimeTokenResponse>(RUNTIME_TOKEN_FUNCTION, { scopes }, {\n method: \"POST\",\n path: projectId\n });\n } catch (e) {\n const err = e as { status?: number; message?: string };\n if (err.status === 404 && isMissingRoute(err.message)) {\n fail(\n \"This control plane does not issue runtime tokens yet, so the CLI cannot read the app's cron history.\",\n \"Until it does, `rebase cloud debug logs` shows what jobs printed in the last half hour.\",\n \"runtime_token_unavailable\"\n );\n }\n reportError(e, \"Failed to get a runtime token from the control plane\");\n }\n if (typeof res?.token !== \"string\" || res.token.length === 0) {\n fail(\"The control plane answered without a runtime token.\", undefined, \"runtime_token_unavailable\");\n }\n return res;\n}\n\n/**\n * GET a path on the runtime with a platform token, and refuse — with what it\n * means for this command — anything but a 2xx.\n *\n * `notFound` words the 404, which means different things per route: no cron\n * surface at all on the list, no such job on its logs.\n */\nexport async function runtimeGet<T>(\n origin: string,\n path: string,\n token: string,\n notFound: { message: string; hint?: string; code: string }\n): Promise<T> {\n let res: Response;\n try {\n res = await fetch(`${origin}${path}`, {\n headers: { Authorization: `Bearer ${token}`, Accept: \"application/json\" },\n redirect: \"manual\",\n signal: AbortSignal.timeout(RUNTIME_TIMEOUT_MS)\n });\n } catch (e) {\n fail(\n `Could not reach the app at ${origin}: ${e instanceof Error ? e.message : String(e)}`,\n \"`rebase cloud debug health` checks whether the deployment is answering at all.\",\n \"runtime_unreachable\"\n );\n }\n\n const text = await res.text();\n let body: unknown;\n try {\n body = text ? JSON.parse(text) : undefined;\n } catch {\n body = undefined;\n }\n if (res.ok) return body as T;\n\n const error = (body as ErrorEnvelope | undefined)?.error;\n const said = error?.message ? ` (${error.message})` : \"\";\n\n if (res.status === 401) {\n if (error?.code === \"PLATFORM_TOKENS_OFF\" || error?.code === \"INVALID_PLATFORM_TOKEN\") {\n fail(\n `The app refused the platform's token${said}.`,\n \"The platform sets the key it verifies with when it deploys; redeploying the project picks it up.\",\n \"runtime_token_refused\"\n );\n }\n // A runtime that predates platform tokens parses `rpt_…` as a user\n // session and answers the generic refusal.\n fail(\n `This deployment's runtime does not accept platform tokens${said}.`,\n \"Runtimes from before platform tokens accept only an admin of the app, an `rk_` key or the service key. \" +\n \"Redeploy to move to a runtime that accepts them.\",\n \"runtime_token_refused\"\n );\n }\n if (res.status === 404) fail(notFound.message, notFound.hint, notFound.code);\n if (res.status === 501 && error?.code === \"ADMIN_SURFACE_UNAVAILABLE\") {\n fail(`The app has its admin surfaces switched off${said}.`, undefined, \"admin_surface_unavailable\");\n }\n fail(\n `The app answered ${res.status} for ${path}${said}.`,\n res.status >= 500 ? \"`rebase cloud debug errors` shows what the server logged.\" : undefined,\n res.status === 400 ? \"usage\" : \"runtime_error\"\n );\n}\n\n/** Everything both actions need before their one request. */\nasync function connect(rawArgs: string[]): Promise<{ origin: string; token: string }> {\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n // The origin first: a project with no address cannot be read, and that is\n // worth knowing before asking anyone to mint anything.\n const origin = await resolveOrigin(rawArgs, client, url, projectId);\n const { token } = await mintRuntimeToken(client, projectId, [CRON_READ_SCOPE]);\n return { origin, token };\n}\n\nconst NO_CRON_SURFACE = {\n message: \"This deployment serves no cron surface.\",\n hint: \"The app was built without a crons directory, or its runtime does not serve the cron admin routes.\",\n code: \"cron_not_served\"\n};\n\n/** `2026-10-05T10:31:00.000Z` → `2026-10-05 10:31:00Z`, or `—`. */\nexport function shortTime(iso: string | undefined): string {\n if (!iso) return \"—\";\n const date = new Date(iso);\n return Number.isNaN(date.getTime()) ? iso : `${date.toISOString().slice(0, 19).replace(\"T\", \" \")}Z`;\n}\n\n/** Milliseconds as `850ms`, `2.4s` or `3m 10s`. */\nexport function shortDuration(ms: number | undefined): string {\n if (ms === undefined || !Number.isFinite(ms)) return \"\";\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n}\n\nfunction stateColor(state: string): string {\n if (state === \"error\") return chalk.red(state);\n if (state === \"running\") return chalk.cyan(state);\n if (state === \"disabled\") return chalk.gray(state);\n if (state === \"success\") return chalk.green(state);\n return state;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cron list\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `cron list` parses — the help page lists exactly these. */\nexport const CRON_LIST_FLAGS = { \"--host\": String };\n\nasync function listCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({\n spec: CRON_LIST_FLAGS,\n rawArgs,\n commandWords: 3,\n command: \"cloud cron list\",\n maxPositionals: 0\n });\n const { origin, token } = await connect(rawArgs);\n const res = await runtimeGet<CronListResponse>(origin, CRON_PATH, token, NO_CRON_SURFACE);\n const jobs = res?.jobs ?? [];\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⏰ Cron — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${origin}`));\n console.log(\"\");\n if (jobs.length === 0) {\n console.log(chalk.gray(\" No cron jobs are scheduled on this deployment.\"));\n } else {\n // Padded on the plain text: a colour code has length and no width.\n const lastRun = (job: CronJobStatus): { at: string; took: string } => ({\n at: shortTime(job.lastRunAt),\n took: job.lastRunAt ? shortDuration(job.lastDurationMs) : \"\"\n });\n const lastText = (job: CronJobStatus): string => [lastRun(job).at, lastRun(job).took].filter(Boolean).join(\" \");\n const idWidth = Math.max(3, ...jobs.map(job => job.id.length));\n const scheduleWidth = Math.max(8, ...jobs.map(job => job.schedule.length));\n const stateWidth = Math.max(5, ...jobs.map(job => job.state.length));\n const lastWidth = Math.max(8, ...jobs.map(job => lastText(job).length));\n console.log(chalk.gray(\n ` ${\"JOB\".padEnd(idWidth)} ${\"SCHEDULE\".padEnd(scheduleWidth)} ${\"STATE\".padEnd(stateWidth)} ` +\n `${\"LAST RUN\".padEnd(lastWidth)} NEXT RUN`\n ));\n for (const job of jobs) {\n const { at, took } = lastRun(job);\n const pad = (text: string, width: number) => \" \".repeat(Math.max(0, width - text.length));\n console.log(\n ` ${chalk.bold(job.id)}${pad(job.id, idWidth)} ${job.schedule.padEnd(scheduleWidth)} ` +\n `${stateColor(job.state)}${pad(job.state, stateWidth)} ` +\n `${at}${took ? ` ${chalk.gray(took)}` : \"\"}${pad(lastText(job), lastWidth)} ${shortTime(job.nextRunAt)}`\n );\n if (job.state === \"error\" && job.lastError) {\n console.log(chalk.red(` ${\" \".repeat(idWidth)} ${job.lastError}`));\n }\n }\n }\n if (res?.note) {\n console.log(\"\");\n console.log(chalk.yellow(` ⚠ ${res.note}`));\n for (const rejected of res.rejected ?? []) {\n console.log(chalk.yellow(` ${rejected.id} (${rejected.schedule}): ${rejected.reason}`));\n }\n }\n console.log(\"\");\n if (jobs.length > 0) {\n console.log(chalk.gray(\" A job's run history: \") + chalk.bold(\"rebase cloud cron logs <job>\"));\n console.log(\"\");\n }\n },\n {\n origin,\n jobs,\n skipped: res?.skipped ?? 0,\n rejected: res?.rejected ?? [],\n note: res?.note ?? null\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cron logs <job>\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `cron logs` parses — the help page lists exactly these. */\nexport const CRON_LOGS_FLAGS = { \"--limit\": Number, \"--host\": String };\n\nasync function logsCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parseCloudArgs({\n spec: CRON_LOGS_FLAGS,\n rawArgs,\n commandWords: 3,\n command: \"cloud cron logs\",\n maxPositionals: 1\n });\n const jobId = positionals[0];\n if (!jobId) {\n fail(\"Name the job: `rebase cloud cron logs <job>`.\", \"`rebase cloud cron list` names them.\", \"usage\");\n }\n const limit = flags[\"--limit\"];\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {\n fail(`--limit must be a positive whole number; received ${String(limit)}.`, undefined, \"usage\");\n }\n\n const { origin, token } = await connect(rawArgs);\n const query = limit !== undefined ? `?limit=${limit}` : \"\";\n const res = await runtimeGet<{ logs?: CronJobLogEntry[] }>(\n origin,\n `${CRON_PATH}/${encodeURIComponent(jobId)}/logs${query}`,\n token,\n {\n message: `No cron job named \"${jobId}\" on this deployment (or no cron surface at all).`,\n hint: \"`rebase cloud cron list` names the jobs it runs.\",\n code: \"not_found\"\n }\n );\n const logs = res?.logs ?? [];\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 📜 Cron runs — ${jobId} on ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` newest first, ${logs.length} run${logs.length === 1 ? \"\" : \"s\"}`)\n );\n console.log(\"\");\n if (logs.length === 0) {\n console.log(chalk.gray(\" This job has no recorded runs.\"));\n console.log(\"\");\n return;\n }\n for (const run of logs) {\n const mark = run.success ? chalk.green(\"✓\") : chalk.red(\"✗\");\n const tags = [shortDuration(run.durationMs), run.manual ? \"manual\" : undefined].filter(Boolean).join(\" \");\n console.log(` ${mark} ${shortTime(run.startedAt)} ${chalk.gray(tags)}`);\n if (run.error) console.log(chalk.red(` ${run.error}`));\n for (const line of run.logs ?? []) console.log(` ${line}`);\n }\n console.log(\"\");\n },\n { origin, job: jobId, logs }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\nconst CRON_ACTIONS = [\"list\", \"logs\"] as const;\n\nexport async function cronCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n requireKnownAction(\"cron\", action, CRON_ACTIONS);\n if (action === \"logs\") {\n await logsCommand(rawArgs);\n return;\n }\n await listCommand(rawArgs);\n}\n","/**\n * `rebase cloud env` — a project's environment variables.\n *\n * env list Keys only — a value is NEVER printed here\n * env set KEY=VALUE Create/replace one variable (`--secret` ⇒ write-only)\n * env unset KEY Remove one variable\n * env reveal KEY Release one non-secret value (a secret var 403s)\n * env pull [--out .env] Write revealable values to a local dotenv file\n *\n * With `--preview`, `list`, `set` and `unset` act on what the project's\n * PREVIEWS run with instead (`rebase cloud deploy --preview`), and `reset KEY\n * --preview` hands a variable back to production's value. A backend preview\n * starts from a copy of production's environment, live third-party keys\n * included; this is how a preview gets a test key instead, or none. Production\n * is never changed by any of them.\n *\n * Values are the sharp edge here. The list endpoint returns keys and never\n * values by design (a page load is not consent to spray a customer's secrets\n * through caches and logs), and a `--secret` variable is write-only: it can be\n * replaced but never read back. This mirrors `env-vars` exactly and refuses to\n * offer reveal for a secret variable rather than letting the server 403.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { isMissingRoute } from \"./cron\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n parseCloudArgs,\n emit,\n printGroupHelp,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\n/**\n * Reserved names the control plane will release the value of.\n *\n * They carry no row, so the listing above cannot see them, and a CLI that\n * required a row refused them before the server got a say. Kept as a list here\n * only so the refusal is skipped — the server is what decides, and it holds the\n * same allowlist for the reasons set out there.\n */\nconst PLATFORM_REVEALABLE_KEYS = [\"REBASE_SERVICE_KEY\"];\n\ninterface EnvVarView {\n id: string;\n key: string;\n secret: boolean;\n valueSet: boolean;\n createdAt: string | null;\n updatedAt: string | null;\n}\n\ninterface EnvVarListResponse {\n vars: EnvVarView[];\n pendingRedeploy: boolean | null;\n pendingSince: string | null;\n limits: {\n maxVars: number;\n maxValueBytes: number;\n maxTotalBytes: number;\n keyPattern: string;\n reservedKeys: string[];\n };\n}\n\nasync function fetchEnvVars(client: CloudClient, projectId: string): Promise<EnvVarListResponse> {\n return client.functions.invoke<EnvVarListResponse>(\"env-vars\", undefined, {\n method: \"GET\",\n path: projectId\n });\n}\n\n/** `--preview`: act on what the project's previews run with, not production. */\nexport const ENV_PREVIEW_FLAGS = { \"--preview\": Boolean } as const;\n\n/** The control-plane function that holds preview overrides. */\nconst PREVIEWS_FUNCTION = \"previews\";\n\n/** What the control plane shows of one preview override. */\ninterface PreviewEnvVarView {\n key: string;\n /** Previews run without this variable. */\n unset: boolean;\n secret: boolean;\n value?: string;\n updatedAt: string | null;\n}\n\n/** A refusal for a control plane that has no previews, or null for any other error. */\nfunction previewsUnavailable(e: unknown): void {\n const err = e as { status?: number; message?: string; code?: string };\n if (err?.status === 404 && (err.code === \"FUNCTION_NOT_FOUND\" || isMissingRoute(err.message))) {\n fail(\n \"This control plane does not serve preview deployments yet, so previews have no variables of their own. Nothing was changed.\",\n \"Production's variables are managed without --preview.\",\n \"previews_unavailable\"\n );\n }\n}\n\nexport async function envCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listEnv(rawArgs);\n break;\n case \"set\":\n await setEnv(rawArgs);\n break;\n case \"unset\":\n case \"delete\":\n case \"rm\":\n await unsetEnv(rawArgs, action);\n break;\n case \"reveal\":\n await revealEnv(rawArgs);\n break;\n case \"reset\":\n await resetPreviewEnv(rawArgs);\n break;\n case \"pull\":\n await pullEnv(rawArgs);\n break;\n case \"--help\":\n printEnvHelp();\n break;\n default:\n fail(`Unknown env command: ${action}`, \"Run `rebase cloud env --help`.\", \"unknown_command\");\n }\n}\n\n/** A short human hint about redeploy state (the JSON carries `pendingRedeploy`). */\nfunction pendingHint(pending: boolean | null): string | undefined {\n if (pending === true) return chalk.yellow(\"A variable changed since the last deploy — run `rebase cloud deploy` to apply it.\");\n if (pending === null) return chalk.gray(\"Redeploy state is unknown (deployment history unavailable).\");\n return undefined;\n}\n\nasync function listEnv(rawArgs: string[]): Promise<void> {\n const { flags } = parseCloudArgs({ spec: ENV_PREVIEW_FLAGS,\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud env\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n if (flags[\"--preview\"]) {\n await listPreviewEnv(client, projectId, projectRef);\n return;\n }\n try {\n const res = await fetchEnvVars(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔑 Environment — project ${projectRef}`));\n console.log(\"\");\n if (!res.vars.length) {\n console.log(chalk.gray(\" No variables. Add one with `rebase cloud env set KEY=VALUE`.\"));\n console.log(\"\");\n return;\n }\n for (const v of res.vars) {\n const badges = [\n v.secret ? chalk.magenta(\"secret\") : undefined,\n v.valueSet ? undefined : chalk.gray(\"empty\")\n ]\n .filter(Boolean)\n .join(\" \");\n // Deliberately no value — reveal is the only way to read one.\n console.log(` ${chalk.bold(v.key)}${badges ? ` ${badges}` : \"\"}`);\n }\n const hint = pendingHint(res.pendingRedeploy);\n if (hint) {\n console.log(\"\");\n console.log(` ${hint}`);\n }\n console.log(\"\");\n },\n {\n projectId,\n pendingRedeploy: res.pendingRedeploy,\n pendingSince: res.pendingSince,\n // Never a value: keys + shape only.\n vars: res.vars.map((v) => ({\n key: v.key,\n secret: v.secret,\n valueSet: v.valueSet,\n createdAt: v.createdAt,\n updatedAt: v.updatedAt\n })),\n limits: res.limits\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list environment variables\");\n }\n}\n\n/** `env list --preview`: what previews run with instead of production's values. */\nasync function listPreviewEnv(client: CloudClient, projectId: string, projectRef: string): Promise<void> {\n let vars: PreviewEnvVarView[] = [];\n try {\n const res = await client.functions.invoke<{ vars: PreviewEnvVarView[] }>(PREVIEWS_FUNCTION, undefined, {\n method: \"GET\",\n path: `${projectId}/env`\n });\n vars = res.vars ?? [];\n } catch (e) {\n previewsUnavailable(e);\n reportError(e, \"Failed to list preview variables\");\n }\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔑 Preview environment — project ${projectRef}`));\n console.log(chalk.gray(\" Previews run with production's variables, except:\"));\n console.log(\"\");\n if (!vars.length) {\n console.log(chalk.gray(\" Nothing — previews get production's values, live keys included.\"));\n console.log(chalk.gray(\" Replace one with `rebase cloud env set KEY=VALUE --preview`.\"));\n console.log(\"\");\n return;\n }\n for (const v of vars) {\n const what = v.unset\n ? chalk.yellow(\"not set in previews\")\n : v.secret ? chalk.magenta(\"replaced (secret)\") : \"replaced\";\n console.log(` ${chalk.bold(v.key)} ${what}`);\n }\n console.log(\"\");\n },\n // Keys and shape only, as `env list` — a value is never listed.\n { projectId, preview: true, vars: vars.map(v => ({ key: v.key, unset: v.unset, secret: v.secret, updatedAt: v.updatedAt })) }\n );\n}\n\n/** Parse `KEY=VALUE` or `KEY VALUE` from the positional operands. */\nexport function parseEnvAssignment(operands: string[]): { key: string; value: string } | null {\n const first = operands[0];\n if (!first) return null;\n const eq = first.indexOf(\"=\");\n if (eq > 0) {\n return { key: first.slice(0, eq).trim(),\nvalue: first.slice(eq + 1) };\n }\n // `set KEY VALUE` form — VALUE is the next operand (may be absent ⇒ empty).\n return { key: first.trim(),\nvalue: operands[1] ?? \"\" };\n}\n\n/**\n * Prefixes whose variables are read by a BUNDLER at build time, not by the\n * process at run time.\n *\n * These are the ones this command cannot deliver. A project's environment is\n * applied at rollout — after Kaniko has already built the image — so a\n * `VITE_API_URL` set here is present in the running container and absent from\n * the JavaScript that was compiled minutes earlier. Nothing fails: the variable\n * exists, the deploy succeeds, and the bundle carries `undefined` where the\n * value should be. The bug then presents in the browser as missing\n * configuration, which is several steps away from the cause.\n *\n * `import.meta.env` inlining is Vite's; `NEXT_PUBLIC_`/`PUBLIC_`/`REACT_APP_`\n * are the same contract in Next, Astro/SvelteKit and CRA.\n */\nconst BUILD_TIME_ENV_PREFIXES = [\"VITE_\", \"NEXT_PUBLIC_\", \"PUBLIC_\", \"REACT_APP_\"];\n\n/** The prefix that makes `key` a build-time variable, or undefined. */\nexport function buildTimeEnvPrefix(key: string): string | undefined {\n return BUILD_TIME_ENV_PREFIXES.find((prefix) => key.toUpperCase().startsWith(prefix));\n}\n\n/** The flags `rebase cloud env set` takes, on top of the global cloud ones. */\nexport const ENV_SET_FLAGS = {\n \"--secret\": Boolean,\n \"--force\": Boolean,\n /* Read the value from standard input instead of the command line, where\n every process on the machine can read it (`ps`) and the shell keeps it\n in its history. The MCP server's `rebase_cloud_env_set` sets values this\n way. */\n \"--stdin\": Boolean,\n ...ENV_PREVIEW_FLAGS\n} as const;\n\n/**\n * The value `env set KEY --stdin` was piped: everything on standard input,\n * less the one line ending `echo` and a here-string add. Refuses a terminal\n * (it would wait for a value nobody knows to type) and a line that also gives\n * the value, which would leave two candidates.\n */\nexport function envValueFromStdin(\n operands: string[],\n read: () => string = () => fs.readFileSync(0, \"utf-8\"),\n isTTY: boolean = process.stdin.isTTY === true\n): { key: string; value: string } {\n const first = operands[0] ?? \"\";\n if (operands.length !== 1 || first.includes(\"=\")) {\n fail(\n \"With --stdin, name only the variable: `rebase cloud env set KEY --stdin`.\",\n \"The value is read from standard input, so it cannot also be on the command line.\",\n \"usage\"\n );\n }\n if (isTTY) {\n fail(\n \"--stdin reads the value from a pipe, and standard input is a terminal.\",\n \"Pipe it in: `printf %s \\\"$VALUE\\\" | rebase cloud env set KEY --stdin`.\",\n \"usage\"\n );\n }\n return { key: first.trim(), value: read().replace(/\\r?\\n$/, \"\") };\n}\n\n/**\n * What `env set` was asked to store.\n *\n * The sharp one in this family: the old operand filter left `--project`'s value\n * in the operand list, so `rebase cloud env set KEY -p acme` parsed as the\n * `KEY VALUE` form and stored the project slug as KEY's value — a write that\n * succeeds, reports success, and is wrong. Strict parsing consumes `-p` with\n * its value, leaving `[\"KEY\"]` and the documented empty value.\n *\n * A value beginning with `-` must use the `KEY=-v` form; the bare `KEY -v` form\n * is refused rather than guessed at, as everywhere else strict parsing is used.\n *\n * Exported so its tests drive the real parser rather than a copy of it.\n */\nexport function resolveEnvSetArgs(rawArgs: string[]) {\n const { flags, positionals } = parseCloudArgs({\n spec: ENV_SET_FLAGS,\n rawArgs,\n commandWords: 3, // cloud env set\n command: \"cloud env set\",\n maxPositionals: 2 // KEY=VALUE, or KEY VALUE\n });\n return { flags,\npositionals,\nassignment: parseEnvAssignment(positionals) };\n}\n\nasync function setEnv(rawArgs: string[]): Promise<void> {\n const resolved = resolveEnvSetArgs(rawArgs);\n const args = resolved.flags;\n // Read before any request, so a refusal costs nothing.\n const parsed = args[\"--stdin\"] ? envValueFromStdin(resolved.positionals) : resolved.assignment;\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n if (!parsed || !parsed.key) {\n fail(\"Usage: rebase cloud env set KEY=VALUE [--secret]\", undefined, \"usage\");\n }\n\n // Refused rather than warned. A warning is the wrong instrument here: this\n // command is most often run non-interactively, where a warning scrolls past\n // and the variable is stored anyway — leaving a project that looks\n // configured, deploys clean, and is broken in the browser. `--force` exists\n // because a custom build could legitimately read one of these at run time.\n const buildTimePrefix = buildTimeEnvPrefix(parsed!.key);\n if (buildTimePrefix && !args[\"--force\"]) {\n fail(\n `${parsed!.key} is read by your bundler at BUILD time, and project variables are applied at ` +\n \"rollout — after the image is built. Setting it here would not reach the bundle.\",\n // Per deploy path, because the two read it in different places. A\n // managed deploy builds the frontend on this machine; a `--source`\n // build runs on the platform from an upload that never carries an\n // `.env` file (see `neverUploaded`).\n // `VITE_API_URL` is the exception: the local build reads it from the\n // shell alone (`staticBuildEnv`), never from a file.\n \"A managed deploy builds the frontend on this machine: set it in your shell when you run \" +\n `\\`rebase cloud deploy\\`${parsed!.key === \"VITE_API_URL\" ? \"\" : \", or in the app's .env.production\"}. ` +\n \"A --source build runs on the platform and \" +\n \"never receives .env files: set it in the build itself — an ENV line in your Dockerfile, or \" +\n \"`define` in your bundler config. Pass --force if your build genuinely reads this at run time.\",\n \"build_time_variable\"\n );\n }\n\n const body: { key: string; value: string; secret?: boolean } = { key: parsed!.key,\nvalue: parsed!.value };\n if (args[\"--secret\"]) body.secret = true;\n\n if (args[\"--preview\"]) {\n let res: { var: PreviewEnvVarView } | undefined;\n try {\n res = await client.functions.invoke<{ success: boolean; var: PreviewEnvVarView; pendingRedeploy: true }>(\n PREVIEWS_FUNCTION,\n body,\n { method: \"POST\", path: `${projectId}/env` }\n );\n } catch (e) {\n previewsUnavailable(e);\n reportError(e, \"Failed to set the preview variable\");\n }\n emit(\n () => {\n success(`Previews of ${projectRef} now run with their own ${chalk.bold(res!.var.key)}${res!.var.secret ? chalk.magenta(\" (secret)\") : \"\"}. Production is unchanged.`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — each preview takes it at its next \\`rebase cloud deploy --preview\\`.`);\n console.log(\"\");\n },\n { success: true, preview: true, key: res!.var.key, secret: res!.var.secret, pendingRedeploy: true }\n );\n return;\n }\n\n try {\n const res = await client.functions.invoke<{ success: boolean; var: EnvVarView; pendingRedeploy: true }>(\n \"env-vars\",\n body,\n { path: projectId }\n );\n emit(\n () => {\n success(`Set ${chalk.bold(res.var.key)}${res.var.secret ? chalk.magenta(\" (secret)\") : \"\"}`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — run \\`rebase cloud deploy\\` to apply it.`);\n console.log(\"\");\n },\n {\n success: true,\n key: res.var.key,\n secret: res.var.secret,\n valueSet: res.var.valueSet,\n pendingRedeploy: res.pendingRedeploy\n }\n );\n } catch (e) {\n reportError(e, \"Failed to set environment variable\");\n }\n}\n\n/**\n * The variable `env unset` / `env reveal` names.\n *\n * `unset` is a delete, and the operand filter aimed it at the wrong variable:\n * `rebase cloud env unset -p acme` removed a variable called \"acme\" from the\n * linked project instead of reporting a missing KEY, and `env unset -p acme\n * KEY` removed \"acme\" instead of KEY. Both read `--project`'s value as the\n * operand — a plain word in the right position that no flag filter can catch.\n *\n * `action` is the word the caller used (`unset`, `rm`, `delete`, `reveal`); the\n * count of command words is the same for all of them.\n */\nexport function resolveEnvKeyArg(rawArgs: string[], action: string): string | undefined {\n return resolveEnvKeyArgs(rawArgs, action).key;\n}\n\n/** {@link resolveEnvKeyArg}, and whether `--preview` was given (`unset` and `reset` take it). */\nexport function resolveEnvKeyArgs(rawArgs: string[], action: string): { key: string | undefined; preview: boolean } {\n const { flags, positionals } = parseCloudArgs({\n spec: action === \"reveal\" ? {} : ENV_PREVIEW_FLAGS,\n rawArgs,\n commandWords: 3, // cloud env <action>\n command: `cloud env ${action}`,\n maxPositionals: 1\n });\n return { key: positionals[0], preview: (flags as { \"--preview\"?: boolean })[\"--preview\"] === true };\n}\n\nasync function unsetEnv(rawArgs: string[], action: string): Promise<void> {\n const { key, preview } = resolveEnvKeyArgs(rawArgs, action);\n // Refused before the login round-trip: an unusable line is unusable whether\n // or not there is a session behind it.\n if (!key) fail(\"Usage: rebase cloud env unset KEY [--preview]\", undefined, \"usage\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n if (preview) {\n // Previews run WITHOUT the variable — an override that removes it —\n // while production keeps it. `env reset KEY --preview` undoes this.\n try {\n await client.functions.invoke(PREVIEWS_FUNCTION, { key, unset: true }, { method: \"POST\", path: `${projectId}/env` });\n } catch (e) {\n previewsUnavailable(e);\n reportError(e, \"Failed to remove the variable from previews\");\n }\n emit(\n () => {\n success(`Previews now run without ${chalk.bold(key!)}. Production is unchanged.`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — each preview takes it at its next \\`rebase cloud deploy --preview\\`.`);\n console.log(\"\");\n },\n { success: true, preview: true, key, unset: true, pendingRedeploy: true }\n );\n return;\n }\n\n try {\n const res = await client.functions.invoke<{ success: boolean; pendingRedeploy: true }>(\"env-vars\", undefined, {\n method: \"DELETE\",\n path: `${projectId}/${encodeURIComponent(key!)}`\n });\n emit(\n () => {\n success(`Removed ${chalk.bold(key!)}`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — run \\`rebase cloud deploy\\` to apply it.`);\n console.log(\"\");\n },\n { success: true,\nkey,\npendingRedeploy: res.pendingRedeploy }\n );\n } catch (e) {\n reportError(e, \"Failed to remove environment variable\");\n }\n}\n\n/** `env reset KEY --preview`: previews take production's value of KEY again. */\nasync function resetPreviewEnv(rawArgs: string[]): Promise<void> {\n const { key, preview } = resolveEnvKeyArgs(rawArgs, \"reset\");\n if (!key || !preview) {\n fail(\n \"Usage: rebase cloud env reset KEY --preview\",\n \"`reset` hands a variable in previews back to production's value; production itself has nothing to reset to.\",\n \"usage\"\n );\n }\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n await client.functions.invoke(PREVIEWS_FUNCTION, undefined, {\n method: \"DELETE\",\n path: `${projectId}/env/${encodeURIComponent(key!)}`\n });\n } catch (e) {\n previewsUnavailable(e);\n if ((e as { status?: number })?.status === 404) {\n fail(`Previews have no value of their own for ${key}.`, \"`rebase cloud env list --preview` lists them.\", \"not_found\");\n }\n reportError(e, \"Failed to reset the preview variable\");\n }\n emit(\n () => {\n success(`Previews take production's ${chalk.bold(key!)} again.`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — each preview takes it at its next \\`rebase cloud deploy --preview\\`.`);\n console.log(\"\");\n },\n { success: true, preview: true, key, reset: true, pendingRedeploy: true }\n );\n}\n\nasync function revealEnv(rawArgs: string[]): Promise<void> {\n const key = resolveEnvKeyArg(rawArgs, \"reveal\");\n if (!key) fail(\"Usage: rebase cloud env reveal KEY\", undefined, \"usage\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // Pre-check: a secret variable is write-only. Don't even ask the server — it\n // would 403 — say so plainly and never offer reveal for it. Done OUTSIDE the\n // reveal try so a deliberate refusal is not re-wrapped as a server error.\n let list: EnvVarListResponse;\n try {\n list = await fetchEnvVars(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n const found = list!.vars.find((v) => v.key === key);\n // A platform-managed name has no row in the listing, because the platform\n // computes it and injects it at deploy time rather than storing it. Refusing\n // here on the strength of an absent row is how `env reveal\n // REBASE_SERVICE_KEY` came to answer \"No variable named REBASE_SERVICE_KEY\"\n // for a value that very much exists — and that the tenant API recommends by\n // name as the way out of \"API keys cannot manage API keys\". The server\n // decides which of these it will release; this only stops pre-empting it.\n if (!found && !PLATFORM_REVEALABLE_KEYS.includes(key!)) {\n fail(`No variable named ${key} in project ${projectRef}.`, undefined, \"not_found\");\n }\n if (found?.secret) {\n fail(\n `${key} is a secret (write-only) variable; its value cannot be revealed.`,\n \"Replace it with `rebase cloud env set KEY=VALUE` if you need to change it.\",\n \"secret_write_only\"\n );\n }\n\n try {\n const res = await client.functions.invoke<{ key: string; value: string }>(\n \"env-vars\",\n { projectId,\nkey },\n { path: \"reveal\" }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(` ${chalk.bold(res.key)}=${res.value}`);\n console.log(\"\");\n },\n { key: res.key,\nvalue: res.value }\n );\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n}\n\n/**\n * One `KEY=value` line that dotenv reads back as exactly `value`, or null when\n * no quoting can carry it.\n *\n * dotenv's quoting is not JSON's, and `JSON.stringify` was what this used: a\n * double-quoted value has only `\\n` and `\\r` unescaped, so every other\n * backslash stayed and `{\"a\":1}` came back as `{\\\"a\\\":1}`. Single quotes and\n * backticks are literal — nothing inside is unescaped, and either may span\n * lines — so they carry any value without their own quote character. Double\n * quotes come last: they cannot hold a `\"` or a literal backslash-n, and they\n * are the only way to carry a carriage return, which dotenv folds into a\n * newline everywhere else.\n */\nexport function dotenvLine(key: string, value: string): string | null {\n // Unquoted, a value is cut at `#`, trimmed, and read as quoted when it\n // starts with a quote character.\n if (!/[\\s#'\"`\\\\]/.test(value)) return `${key}=${value}`;\n if (!value.includes(\"\\r\")) {\n if (!value.includes(\"'\")) return `${key}='${value}'`;\n if (!value.includes(\"`\")) return `${key}=\\`${value}\\``;\n }\n if (!value.includes(\"\\\"\") && !/\\\\[nr]/.test(value)) {\n return `${key}=\"${value.replace(/\\r/g, \"\\\\r\").replace(/\\n/g, \"\\\\n\")}\"`;\n }\n return null;\n}\n\nasync function pullEnv(rawArgs: string[]): Promise<void> {\n // Strict: this writes a file, and the permissive parse accepted\n // `env pull --ouput creds.env` by ignoring the typo and overwriting `.env`.\n const { flags: args } = parseCloudArgs({\n spec: { \"--output\": String,\n\"--out\": \"--output\" },\n rawArgs,\n commandWords: 3, // cloud env pull\n command: \"cloud env pull\",\n maxPositionals: 0\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const outPath = path.resolve(args[\"--output\"] || \".env\");\n\n try {\n const list = await fetchEnvVars(client, projectId);\n\n if (fs.existsSync(outPath)) {\n await confirmDestructive({ yes: Boolean(args[\"--yes\"]),\nprompt: `Overwrite ${outPath}?` });\n }\n\n // Only non-secret, value-set variables can be written — a secret var is\n // write-only and reveal 403s, so it is honestly skipped, not faked.\n const written: string[] = [];\n const skipped: Array<{ key: string; reason: string }> = [];\n const lines: string[] = [];\n for (const v of list.vars) {\n if (v.secret) {\n skipped.push({ key: v.key,\nreason: \"secret (write-only)\" });\n continue;\n }\n if (!v.valueSet) {\n lines.push(`${v.key}=`);\n written.push(v.key);\n continue;\n }\n const revealed = await client.functions.invoke<{ key: string; value: string }>(\n \"env-vars\",\n { projectId,\nkey: v.key },\n { path: \"reveal\" }\n );\n const line = dotenvLine(v.key, revealed.value);\n if (line === null) {\n skipped.push({ key: v.key,\nreason: \"no .env quoting carries this value unchanged\" });\n continue;\n }\n lines.push(line);\n written.push(v.key);\n }\n\n fs.writeFileSync(outPath, lines.length ? lines.join(\"\\n\") + \"\\n\" : \"\", { mode: 0o600 });\n\n emit(\n () => {\n success(`Wrote ${written.length} variable${written.length === 1 ? \"\" : \"s\"} to ${outPath}`);\n if (skipped.length) {\n for (const s of skipped) console.log(chalk.gray(` Skipped ${s.key}: ${s.reason}`));\n console.log(\"\");\n }\n },\n { success: true,\npath: outPath,\nwritten,\nskipped }\n );\n } catch (e) {\n reportError(e, \"Failed to pull environment variables\");\n }\n}\n\nexport function printEnvHelp(): void {\n printGroupHelp({\n command: \"cloud env\",\n title: \"Environment variables\",\n actions: [\n { action: \"list\",\ndescription: \"List keys — values are never printed\",\nflags: [[\"--preview\", \"What previews run with instead of production's values\"]] },\n {\n action: \"set\",\n args: \"KEY=VALUE\",\n description: \"Create or replace a variable\",\n flags: [\n [\"--secret\", \"Mark it write-only: it can be set and used, never read back\"],\n [\"--force\", \"Set a build-time key anyway\"],\n [\"--stdin\", \"Read the value from standard input (give only KEY), so it is not on the command line\"],\n [\"--preview\", \"Only for previews: production keeps its value\"]\n ]\n },\n { action: \"unset\",\nargs: \"KEY\",\ndescription: \"Remove a variable\",\nflags: [[\"--preview\", \"Only from previews: production keeps it\"]] },\n { action: \"reset\",\nargs: \"KEY --preview\",\ndescription: \"Give previews production's value of KEY again\",\nflags: [[\"--preview\", \"Required: only previews have values to reset\"]] },\n { action: \"reveal\",\nargs: \"KEY\",\ndescription: \"Print one non-secret value\" },\n {\n action: \"pull\",\n description: \"Write revealable values to a dotenv file\",\n flags: [[\"--output, --out <file>\", \"Where to write it. Default: .env\"]]\n }\n ],\n notes: [\n \"Values are encrypted at rest (AES-256-GCM) and only decrypted at deploy time.\",\n \"VITE_* / NEXT_PUBLIC_* / PUBLIC_* / REACT_APP_* are read by your bundler at BUILD time;\",\n \"these are applied at rollout, after the image is built, so they never reach the bundle.\",\n \"A backend preview starts from production's variables, live keys included; --preview changes what previews get.\"\n ]\n });\n}\n","/**\n * `rebase cloud init --claim` — a live backend for this project, with no\n * account, and a link that hands it to a person.\n *\n * The command an agent runs when it has built an app and needs somewhere to\n * put it. The control plane provisions an ordinary project on Rebase Cloud in\n * an organization nobody owns yet, this command pushes the local collections to\n * it with a normal managed deploy, and what comes back is the live URL and a\n * claim link. The person the agent works for opens the link, signs in, and the\n * project is theirs; nobody claims it within 72 hours and it is deleted.\n *\n * What it writes:\n *\n * - `.env`: `REBASE_BASE_URL`, the project's live address — where the app, the\n * SDK and the MCP server should reach the backend now — and, once the deploy\n * has built the app, `REBASE_API_TOKEN`: a key the APP accepts, minted on it\n * by the control plane (`POST /api/functions/ephemeral/app-key`). It reads and\n * writes data through the app's row-level security, holds nothing of the\n * admin plane, and expires with the claim window unless the project is\n * claimed: a claim hands it over and it stops expiring; see {@link requestAppKey}.\n * With `--no-deploy`, or a deploy that failed, the next `rebase cloud deploy`\n * that succeeds asks for it instead; see {@link mintMissingAppKey}.\n * - `.rebase/cloud.json`: the link, so every `rebase cloud` command in this\n * directory acts on the project.\n * - `~/.rebase/credentials.json`: the project's token and claim link. Not the\n * repository: see `EphemeralGrant` in `context.ts` for why neither may go in\n * `.env` or the link file. `rebase cloud` commands in a directory linked to\n * the project pick the token up from there by themselves.\n *\n * @module\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { spawn } from \"child_process\";\nimport chalk from \"chalk\";\nimport {\n appKeyExpiryNote,\n dotenvSets,\n emit,\n ephemeralGrantFor,\n fail,\n grantForLink,\n isJsonMode,\n keyValues,\n note,\n noteBlank,\n parseCloudArgs,\n readLink,\n resolveCloudUrl,\n saveEphemeralGrant,\n success,\n TOKEN_ENV,\n warn,\n writeLink\n} from \"./context\";\nimport { dotenvLine } from \"./env\";\nimport { findProjectRoot } from \"../../utils/project\";\nimport { cmsMountOf, loadManifest } from \"../../manifest\";\nimport { cliUserAgent } from \"../../utils/version\";\n\n/** What `rebase cloud init` parses, beside the global flags. Exported so its help page cannot drift. */\nexport const INIT_FLAGS = {\n \"--claim\": Boolean,\n \"--name\": String,\n \"-n\": \"--name\",\n \"--no-deploy\": Boolean\n} as const;\n\n/** The variable the app, the SDK and the MCP server read the backend's address from. */\nexport const BASE_URL_ENV = \"REBASE_BASE_URL\";\n\n/** The variable the MCP server and the SDK read the app's key from. */\nexport const API_TOKEN_ENV = \"REBASE_API_TOKEN\";\n\n/** What `POST /api/functions/ephemeral/provision` answers. */\nexport interface ProvisionedProject {\n projectId: string;\n slug: string;\n name: string;\n projectUrl: string;\n apiKey: string;\n claimUrl: string;\n expiresAt: string;\n}\n\nfunction isProvisionedProject(value: unknown): value is ProvisionedProject {\n return typeof value === \"object\" && value !== null\n && \"projectId\" in value && typeof value.projectId === \"string\"\n && \"slug\" in value && typeof value.slug === \"string\"\n && \"name\" in value && typeof value.name === \"string\"\n && \"projectUrl\" in value && typeof value.projectUrl === \"string\"\n && \"apiKey\" in value && typeof value.apiKey === \"string\"\n && \"claimUrl\" in value && typeof value.claimUrl === \"string\"\n && \"expiresAt\" in value && typeof value.expiresAt === \"string\";\n}\n\n/** The control plane's refusal envelope, `{ error: { code, message } }`, when that is what arrived. */\nfunction refusalOf(value: unknown): { code: string; message: string } | undefined {\n if (typeof value !== \"object\" || value === null || !(\"error\" in value)) return undefined;\n const error = value.error;\n if (typeof error !== \"object\" || error === null) return undefined;\n const message = \"message\" in error && typeof error.message === \"string\" ? error.message : undefined;\n const code = \"code\" in error && typeof error.code === \"string\" ? error.code : \"error\";\n return message ? { code, message } : undefined;\n}\n\n/**\n * Ask the control plane for a project. No credential: this is the one call in\n * the family that is made by nobody.\n */\nexport async function requestEphemeralProject(url: string, name: string | undefined): Promise<ProvisionedProject> {\n let res: Response;\n try {\n res = await fetch(`${url}/api/functions/ephemeral/provision`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"User-Agent\": cliUserAgent() },\n body: JSON.stringify(name ? { name } : {})\n });\n } catch (err) {\n fail(\n `Could not reach ${url}: ${err instanceof Error ? err.message : String(err)}`,\n \"Check your connection, or pass --url for another control plane.\",\n \"unreachable\"\n );\n }\n const body: unknown = await res.json().catch(() => undefined);\n if (!res.ok) {\n const refusal = refusalOf(body);\n if (res.status === 429) {\n fail(\n refusal?.message ?? \"Too many projects were provisioned from this address recently.\",\n \"Claim one of them, wait, or create a project with an account: `rebase cloud login`, then `rebase cloud projects create --link`.\",\n \"rate_limited\"\n );\n }\n if (res.status === 404) {\n fail(\n `${url} does not provision projects without an account.`,\n \"Sign in with `rebase cloud login` and run `rebase cloud projects create --link`.\",\n \"not_supported\"\n );\n }\n fail(\n refusal?.message ?? `The control plane refused the provision (${res.status}).`,\n \"Sign in with `rebase cloud login` and run `rebase cloud projects create --link` instead.\",\n refusal?.code ?? \"provision_refused\"\n );\n }\n if (!isProvisionedProject(body)) {\n fail(\"The control plane's answer did not describe a project.\", undefined, \"bad_response\");\n }\n return body;\n}\n\n/** What `POST /api/functions/ephemeral/app-key` answers: a key minted on the app itself. */\nexport interface AppKey {\n apiKey: string;\n keyId: string;\n scopes: string[];\n expiresAt: string;\n}\n\nfunction isAppKey(value: unknown): value is AppKey {\n return typeof value === \"object\" && value !== null\n && \"apiKey\" in value && typeof value.apiKey === \"string\" && value.apiKey.startsWith(\"rk_\")\n && \"keyId\" in value && typeof value.keyId === \"string\"\n && \"scopes\" in value && Array.isArray(value.scopes) && value.scopes.every((s: unknown) => typeof s === \"string\")\n && \"expiresAt\" in value && typeof value.expiresAt === \"string\";\n}\n\nexport type AppKeyOutcome = { ok: true; key: AppKey } | { ok: false; code: string; message: string };\n\nexport interface AppKeyRetry {\n /** How many times to ask while the app is still coming up. */\n attempts: number;\n sleep: (ms: number) => Promise<void>;\n}\n\nconst APP_KEY_RETRY: AppKeyRetry = {\n attempts: 4,\n sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n};\n\n/** Between asks while the app is not answering yet. */\nconst APP_KEY_RETRY_DELAY_MS = 5_000;\n\n/**\n * Ask the control plane for a key the deployed app accepts, with the project's\n * own token.\n *\n * The control plane mints it on the app through the app's admin key route: a\n * service key holding `data:read` and `data:write` and nothing else, running\n * through the app's row-level security as a caller who is neither a person nor\n * an admin, expiring with the claim window. Never fatal: the project and its\n * claim link stand without it, so a refusal comes back as an outcome to report.\n *\n * Asks again only while the app is not answering yet, the state a rollout\n * that has just finished can still be in: a 503 from the control plane (the\n * app did not answer), or a 502/504 (the app's gateway answered for it — the\n * control plane passes any non-2xx from the app on as 502).\n */\nexport async function requestAppKey(\n url: string,\n token: string,\n projectId: string,\n retry: AppKeyRetry = APP_KEY_RETRY\n): Promise<AppKeyOutcome> {\n let last: AppKeyOutcome = { ok: false, code: \"unreachable\", message: \"The control plane was not asked.\" };\n for (let attempt = 1; attempt <= Math.max(1, retry.attempts); attempt++) {\n if (attempt > 1) await retry.sleep(APP_KEY_RETRY_DELAY_MS);\n let res: Response;\n try {\n res = await fetch(`${url}/api/functions/ephemeral/app-key`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Authorization\": `Bearer ${token}`,\n \"User-Agent\": cliUserAgent()\n },\n body: JSON.stringify({ projectId })\n });\n } catch (err) {\n return { ok: false, code: \"unreachable\", message: `Could not reach ${url}: ${err instanceof Error ? err.message : String(err)}` };\n }\n const body: unknown = await res.json().catch(() => undefined);\n if (res.ok) {\n return isAppKey(body)\n ? { ok: true, key: body }\n : { ok: false, code: \"bad_response\", message: \"The control plane's answer did not carry a key.\" };\n }\n const refusal = refusalOf(body);\n last = {\n ok: false,\n code: refusal?.code ?? \"app_key_refused\",\n message: refusal?.message ?? `The control plane did not mint a key for the app (${res.status}).`\n };\n if (res.status === 404 && !refusal) {\n return { ok: false, code: \"not_supported\", message: `${url} does not mint keys for an unclaimed project's app.` };\n }\n if (res.status !== 502 && res.status !== 503 && res.status !== 504) return last;\n }\n return last;\n}\n\n/**\n * Set one variable in a `.env`, keeping every other line as it was: replaced\n * where it is already set, appended where it is not.\n */\nexport function upsertDotenv(file: string, key: string, value: string): void {\n const line = dotenvLine(key, value);\n if (!line) throw new Error(`${key} cannot be written to a .env file as it is.`);\n const existing = fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : \"\";\n const lines = existing.length > 0 ? existing.replace(/\\n$/, \"\").split(\"\\n\") : [];\n const at = lines.findIndex((l) => new RegExp(`^\\\\s*(export\\\\s+)?${key}\\\\s*=`).test(l));\n if (at >= 0) lines[at] = line;\n else lines.push(line);\n // A `.env` this writes holds keys: created private, as `env pull` creates\n // one. An existing file keeps the mode its owner gave it.\n fs.writeFileSync(file, `${lines.join(\"\\n\")}\\n`, { mode: 0o600 });\n}\n\nexport { dotenvSets };\n\n/**\n * Set on the deploy `init` runs as a child. `init` asks for the app's key\n * itself once that deploy is done, and reports it in its own result, so the\n * child leaves it alone: asked twice, the second key revokes the first.\n */\nexport const INIT_CHILD_DEPLOY_ENV = \"REBASE_CLOUD_INIT_DEPLOY\";\n\n/** The key's outcome as a result reports it. Never the key: this output reaches an agent's transcript. */\nexport function appKeyPayload(outcome: AppKeyOutcome): Record<string, unknown> {\n return outcome.ok\n ? {\n ok: true,\n env: API_TOKEN_ENV,\n scopes: outcome.key.scopes,\n expiresAt: outcome.key.expiresAt,\n // When it expires, and that a claim hands it over: said where an agent reads it.\n note: appKeyExpiryNote(outcome.key.expiresAt)\n }\n : { ok: false, error: { code: outcome.code, message: outcome.message } };\n}\n\n/**\n * After `rebase cloud deploy` succeeded: the app's key, when this directory is\n * linked to an unclaimed project and its `.env` has none yet.\n *\n * `init` asks for the key right after its own deploy, so a project provisioned\n * with `--no-deploy`, or whose first deploy failed, had no way to get one, and\n * `init` does not run again in a linked directory. The next deploy that builds\n * the app is that way.\n *\n * Asks nothing when the project is claimed or its grant has expired (there is\n * no grant then), when the deploy was for a project other than the linked one,\n * or when `.env` already sets `REBASE_API_TOKEN`: that may be a key someone\n * made by hand, and a new one revokes the last one minted. Never throws, since\n * the deploy succeeded either way, and answers `undefined` when it asked nothing.\n */\nexport async function mintMissingAppKey(opts: {\n url: string;\n projectId: string;\n /** The directory holding the link and `.env`: the project root, or the working directory. */\n root?: string;\n appKey?: InitDeps[\"appKey\"];\n}): Promise<AppKeyOutcome | undefined> {\n try {\n if (process.env[INIT_CHILD_DEPLOY_ENV]) return undefined;\n const root = opts.root ?? findProjectRoot() ?? process.cwd();\n if (readLink(root)?.projectId !== opts.projectId) return undefined;\n const grant = ephemeralGrantFor(opts.url, opts.projectId);\n if (!grant) return undefined;\n const dotenv = path.join(root, \".env\");\n if (dotenvSets(dotenv, API_TOKEN_ENV)) return undefined;\n\n const outcome = await (opts.appKey ?? DEFAULT_DEPS.appKey)(opts.url, grant.token, opts.projectId);\n if (outcome.ok) upsertDotenv(dotenv, API_TOKEN_ENV, outcome.key.apiKey);\n return outcome;\n } catch (err) {\n return { ok: false, code: \"app_key_failed\", message: err instanceof Error ? err.message : String(err) };\n }\n}\n\n/**\n * Say how {@link mintMissingAppKey} went, under a deploy's verdict and before\n * its result. A refusal is a warning, in every output mode: the deploy\n * succeeded regardless. JSON carries the same through {@link appKeyPayload}.\n */\nexport function reportMintedAppKey(outcome: AppKeyOutcome | undefined): void {\n if (!outcome) return;\n if (!outcome.ok) {\n warn(\n `${API_TOKEN_ENV} was not written: ${outcome.message}`,\n \"The deploy succeeded without it. The next `rebase cloud deploy` asks again, until the project is claimed.\"\n );\n return;\n }\n if (isJsonMode()) return;\n console.log(chalk.gray(` ${API_TOKEN_ENV} set in .env (${outcome.key.scopes.join(\", \")}): the app's own key, for this unclaimed project.`));\n console.log(chalk.gray(\" It reads and writes data as the app's rules allow.\"));\n console.log(chalk.gray(` ${appKeyExpiryNote(outcome.key.expiresAt)}`));\n console.log(\"\");\n}\n\n/**\n * Where the project's CMS is served once deployed: the mount `rebase.json`\n * declares, on the project's own host unless that app names its own.\n */\nexport function adminPanelUrl(projectRoot: string | null, projectUrl: string): string | undefined {\n if (!projectRoot) return undefined;\n try {\n const mount = cmsMountOf(loadManifest(projectRoot).manifest);\n if (!mount) return undefined;\n const origin = mount.host ? `https://${mount.host}` : projectUrl.replace(/\\/+$/, \"\");\n return `${origin}${mount.path === \"/\" ? \"/\" : mount.path}`;\n } catch {\n return undefined;\n }\n}\n\n/** How a deploy went, as `rebase cloud deploy --json` reported it. */\nexport interface DeployOutcome {\n ok: boolean;\n /** The deploy's own JSON result or error, when it printed one. */\n result?: unknown;\n}\n\n/**\n * The environment of {@link runBundleDeploy}'s child: this one, marked as\n * init's own deploy, and without `REBASE_TOKEN`.\n *\n * `REBASE_TOKEN` outranks the stored grant (see `requireClient`), and a shell\n * or an MCP server that has one holds it for the person's other projects — it\n * has no scope on the project just provisioned, so the deploy was refused and\n * the project never got its collections. The project is deployed with its own\n * token.\n */\nexport function bundleDeployEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const child: NodeJS.ProcessEnv = { ...env, [INIT_CHILD_DEPLOY_ENV]: \"1\" };\n delete child[TOKEN_ENV];\n return child;\n}\n\n/**\n * Push the local collections: `rebase cloud deploy --bundle`, as a child.\n *\n * A child rather than a call, so this command still prints exactly one\n * result — a JSON caller gets the deploy's outcome folded into it — and still\n * prints the claim link when the deploy fails. The child finds the project\n * through the link just written, and its token through the credentials file.\n * It asks for no app key: this command does, after it (see {@link INIT_CHILD_DEPLOY_ENV}).\n */\nexport function runBundleDeploy(cwd: string, json: boolean): Promise<DeployOutcome> {\n const bin = process.argv[1];\n const args = [bin, \"cloud\", \"deploy\", \"--bundle\", ...(json ? [\"--json\"] : [])];\n return new Promise((resolve) => {\n const child = spawn(process.execPath, args, {\n cwd,\n stdio: json ? [\"ignore\", \"pipe\", \"inherit\"] : \"inherit\",\n env: bundleDeployEnv(process.env)\n });\n let stdout = \"\";\n child.stdout?.on(\"data\", (chunk: Buffer) => { stdout += chunk.toString(\"utf-8\"); });\n child.on(\"error\", () => resolve({ ok: false }));\n child.on(\"close\", (code) => {\n let result: unknown;\n try {\n result = stdout.trim() ? JSON.parse(stdout) : undefined;\n } catch {\n result = stdout.trim() || undefined;\n }\n resolve({ ok: code === 0, result });\n });\n });\n}\n\nexport interface InitDeps {\n provision: typeof requestEphemeralProject;\n deploy: typeof runBundleDeploy;\n appKey: (url: string, token: string, projectId: string) => Promise<AppKeyOutcome>;\n}\n\nconst DEFAULT_DEPS: InitDeps = {\n provision: requestEphemeralProject,\n deploy: runBundleDeploy,\n appKey: (url, token, projectId) => requestAppKey(url, token, projectId)\n};\n\nexport async function cloudInitCommand(rawArgs: string[], deps: InitDeps = DEFAULT_DEPS): Promise<void> {\n const { flags } = parseCloudArgs({\n spec: INIT_FLAGS,\n rawArgs,\n commandWords: 2, // cloud init\n command: \"cloud init\",\n maxPositionals: 0\n });\n\n if (!flags[\"--claim\"]) {\n fail(\n \"`rebase cloud init` provisions a project with no account, and needs --claim to say so.\",\n \"`rebase cloud init --claim` gives this directory a live backend and a link to claim it within 72 hours. \"\n + \"With an account: `rebase cloud login`, then `rebase cloud projects create --link`.\",\n \"usage\"\n );\n }\n\n const existing = readLink();\n if (existing?.projectId) {\n // An unclaimed project here is the one to hand over, not to replace:\n // unlinking it leaves it running, and orphaned, until it expires.\n const grant = grantForLink(existing);\n fail(\n `This directory is already linked to project ${existing.slug ?? existing.projectId}.`,\n grant\n ? `It is unclaimed: open ${grant.claimUrl} and sign in to keep it (it is deleted ${new Date(grant.expiresAt).toLocaleString()} otherwise). `\n + \"Deploy to it with `rebase cloud deploy`.\"\n : \"Run `rebase cloud unlink` first to provision a new one here.\",\n \"already_linked\"\n );\n }\n\n const url = resolveCloudUrl(rawArgs);\n const projectRoot = findProjectRoot();\n const root = projectRoot ?? process.cwd();\n\n note(`Provisioning a project on ${chalk.cyan(url)}…`);\n const project = await deps.provision(url, flags[\"--name\"]?.trim() || undefined);\n\n // The token and the claim link first, before anything that can fail: they\n // are the only copy, and the link is how a person ever gets the project.\n saveEphemeralGrant(url, project.projectId, {\n token: project.apiKey,\n claimUrl: project.claimUrl,\n expiresAt: project.expiresAt\n });\n writeLink({ url, projectId: project.projectId, slug: project.slug, projectName: project.name, apiUrl: project.projectUrl }, root);\n upsertDotenv(path.join(root, \".env\"), BASE_URL_ENV, project.projectUrl);\n\n let deployed: DeployOutcome | undefined;\n if (!flags[\"--no-deploy\"]) {\n if (!projectRoot) {\n warn(\"No rebase.json here, so there is nothing to deploy yet.\", \"Run `rebase cloud deploy` from the project once it has one.\");\n } else {\n note(\"Pushing the local collections (rebase cloud deploy --bundle)…\");\n noteBlank();\n deployed = await deps.deploy(root, isJsonMode());\n if (!deployed.ok) {\n warn(\n \"The deploy did not finish. The project and its claim link are kept.\",\n \"Fix what the deploy reported and run `rebase cloud deploy` again.\"\n );\n }\n }\n }\n\n // Only once the deploy has built the app: before that there is nothing to\n // mint the key on. A missing key is reported, never fatal.\n let appKey: AppKeyOutcome | undefined;\n if (deployed?.ok && dotenvSets(path.join(root, \".env\"), API_TOKEN_ENV)) {\n // The rule `mintMissingAppKey` follows: a key already in `.env` may be\n // one someone made by hand, and is not replaced. Not asked for either,\n // since a key minted and never written is a key nobody can use.\n appKey = {\n ok: false,\n code: \"env_has_key\",\n message: `.env already sets ${API_TOKEN_ENV}, which may be a key someone made by hand, so it was kept. `\n + \"Remove it and run `rebase cloud deploy` to get the project's app key.\"\n };\n warn(`${API_TOKEN_ENV} was not written: ${appKey.message}`);\n } else if (deployed?.ok) {\n appKey = await deps.appKey(url, project.apiKey, project.projectId);\n if (appKey.ok) {\n upsertDotenv(path.join(root, \".env\"), API_TOKEN_ENV, appKey.key.apiKey);\n } else {\n warn(\n `${API_TOKEN_ENV} was not written: ${appKey.message}`,\n \"The project is live without it. The next `rebase cloud deploy` here asks again, until the project is claimed.\"\n );\n }\n }\n\n const adminUrl = deployed?.ok ? adminPanelUrl(projectRoot, project.projectUrl) : undefined;\n const expires = new Date(project.expiresAt);\n\n success(`Provisioned ${chalk.bold(project.name)}${deployed?.ok ? \" and deployed it\" : \"\"}`);\n emit(\n () => {\n keyValues([\n [\"Project\", project.slug],\n [\"Live URL\", project.projectUrl],\n [\"Admin panel\", adminUrl],\n [\"App key\", appKey?.ok ? `${API_TOKEN_ENV} in .env (${appKey.key.scopes.join(\", \")})` : undefined],\n [\"Claim URL\", chalk.bold(project.claimUrl)],\n [\"Expires\", `${expires.toLocaleString()} (72 hours) unless claimed`]\n ]);\n console.log(\"\");\n const written = appKey?.ok ? `${BASE_URL_ENV} and ${API_TOKEN_ENV} are` : `${BASE_URL_ENV} is`;\n console.log(chalk.gray(` ${written} set in .env. Open the claim URL, sign in, and the project is yours;`));\n console.log(chalk.gray(\" until then `rebase cloud` commands here use the project's own token.\"));\n console.log(chalk.gray(` Local commands that read ${BASE_URL_ENV} (\\`rebase api-keys\\`, \\`rebase storage\\`, \\`rebase auth reset-password\\`)`));\n console.log(chalk.gray(\" now go to this project too, and say so; set it in the shell to reach a local backend instead.\"));\n if (appKey?.ok) {\n console.log(chalk.gray(` ${API_TOKEN_ENV} reads and writes data as the app's rules allow.`));\n console.log(chalk.gray(` ${appKeyExpiryNote(appKey.key.expiresAt)}`));\n }\n console.log(\"\");\n },\n {\n projectId: project.projectId,\n slug: project.slug,\n name: project.name,\n projectUrl: project.projectUrl,\n adminUrl: adminUrl ?? null,\n claimUrl: project.claimUrl,\n expiresAt: project.expiresAt,\n env: { [BASE_URL_ENV]: project.projectUrl },\n // The key itself stays in .env: this output reaches an agent's transcript.\n appKey: appKey ? appKeyPayload(appKey) : null,\n deploy: deployed ? { ok: deployed.ok, result: deployed.result ?? null } : null\n }\n );\n if (deployed && !deployed.ok) process.exitCode = 1;\n}\n","/**\n * `rebase cloud claim` — the claim link of the project `rebase cloud init\n * --claim` provisioned in this directory, and how long is left to use it.\n *\n * The link is a bearer secret the control plane keeps only a hash of, so the\n * one copy that can be shown again is the one `init` kept in the private\n * credentials file. `status` and `whoami` print it too; this is the command\n * named after the thing a person is looking for, and the one that can open it.\n *\n * It asks the control plane one question before answering: whether the\n * project's own token is still accepted. A claim revokes that token, so a\n * refusal means somebody already claimed it — and printing a link that leads\n * to \"already claimed\" would send the reader somewhere useless.\n */\nimport chalk from \"chalk\";\nimport {\n readLink,\n storedGrantForLink,\n forgetEphemeralGrant,\n probeToken,\n projectDotenvSetsAppKey,\n appKeyExpiryNote,\n parseCloudArgs,\n openUrl,\n emit,\n keyValues,\n fail\n} from \"./context\";\n\n/** What `rebase cloud claim` parses, beside the global flags. Its page pairs against this. */\nexport const CLAIM_FLAGS = { \"--open\": Boolean } as const;\n\n/** \"41h\", \"25m\", \"under a minute\": how long is left, for a person. */\nexport function timeLeft(expiresAt: string, now: number = Date.now()): string {\n const ms = Date.parse(expiresAt) - now;\n if (!(ms > 0)) return \"no time\";\n const minutes = Math.floor(ms / 60_000);\n if (minutes < 1) return \"under a minute\";\n if (minutes < 120) return `${minutes}m`;\n return `${Math.floor(minutes / 60)}h`;\n}\n\nexport async function claimCommand(rawArgs: string[], now: () => number = Date.now): Promise<void> {\n const { flags } = parseCloudArgs({\n spec: CLAIM_FLAGS,\n rawArgs,\n commandWords: 2, // cloud claim\n command: \"cloud claim\",\n maxPositionals: 0\n });\n\n const link = readLink();\n if (!link?.projectId || link.mode === \"direct\") {\n fail(\n \"This directory is not linked to a Rebase Cloud project, so there is nothing to claim here.\",\n `${chalk.bold(\"rebase cloud init --claim\")} provisions a project without an account and prints its claim link.`,\n \"no_project\"\n );\n }\n const project = link.slug ?? link.projectId;\n\n const stored = storedGrantForLink(link);\n if (!stored) {\n fail(\n `Project ${project} has no claim link on this machine.`,\n \"It was claimed already, it was created by a signed-in account, or `rebase cloud init --claim` ran on another machine \"\n + `(the link is kept only where it was printed). ${chalk.bold(\"rebase cloud status\")} shows the project.`,\n \"no_claim_link\"\n );\n }\n const { url, grant } = stored;\n\n if (!(Date.parse(grant.expiresAt) > now())) {\n fail(\n `Project ${project}'s claim window ended at ${new Date(grant.expiresAt).toLocaleString()}.`,\n \"An unclaimed project is deleted when its window ends. Run `rebase cloud unlink`, then \"\n + \"`rebase cloud init --claim` for a new one.\",\n \"claim_expired\"\n );\n }\n\n // A claim revokes the project's token, so the token's standing is the\n // claim's: one request, to the route every token may read.\n const verdict = await probeToken(url, grant.token);\n if (verdict === \"refused\") {\n forgetEphemeralGrant(url, link.projectId);\n fail(\n `Project ${project} has already been claimed: the control plane no longer accepts the token \\`rebase cloud init --claim\\` stored for it.`,\n `Sign in as the account that claimed it with ${chalk.bold(\"rebase cloud login\")}; the project is in that account's organization.`,\n \"already_claimed\"\n );\n }\n\n const verified = verdict === \"accepted\";\n const appKeyNote = projectDotenvSetsAppKey() ? appKeyExpiryNote(grant.expiresAt) : undefined;\n const left = timeLeft(grant.expiresAt, now());\n\n emit(\n () => {\n console.log(\"\");\n console.log(` ${chalk.bold(`Unclaimed: deleted in ${left}`)} ${chalk.gray(`[${project}]`)}`);\n console.log(\"\");\n keyValues([\n [\"Claim URL\", chalk.bold(grant.claimUrl)],\n [\"Expires\", new Date(grant.expiresAt).toLocaleString()]\n ]);\n console.log(\"\");\n console.log(chalk.gray(\" Open the link and sign in: the project moves into your organization, and nothing is redeployed.\"));\n if (!verified) {\n console.log(chalk.yellow(` ${url} could not be asked whether it is still unclaimed; if the link says so, it was claimed already.`));\n }\n if (appKeyNote) console.log(chalk.gray(` ${appKeyNote}`));\n console.log(\"\");\n },\n {\n projectId: link.projectId,\n slug: link.slug ?? null,\n claimUrl: grant.claimUrl,\n expiresAt: grant.expiresAt,\n // False when the control plane could not be asked: the link is the\n // stored one, and the project may have been claimed meanwhile.\n verified,\n opened: flags[\"--open\"] === true,\n appKeyNote: appKeyNote ?? null\n }\n );\n\n if (flags[\"--open\"]) openUrl(grant.claimUrl, \"Opening the claim link\");\n}\n","/**\n * Deploying a project as a managed **bundle** rather than a source build.\n *\n * `rebase cloud deploy --bundle` builds the bundle, tars it, uploads it to the\n * control plane's bundle endpoint, and triggers a deploy carrying the bundle id\n * and its generated manifest. The control plane resolves a runtime from the\n * manifest's range and runs the platform image with this bundle — the managed\n * path. A project not in managed mode, or one whose bundle fails intake, is told\n * so by the control plane; this side just packages and hands it over.\n *\n * The pieces here are separated from the network calls so they can be tested: the\n * manifest read, the tar packaging, and the request body assembly are pure enough\n * to check without a control plane.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { spawn, execFileSync } from \"child_process\";\nimport type { RebaseBundleManifest } from \"@rebasepro/types\";\nimport type { RebuildSource } from \"./rebuild-source\";\nimport { toolStdio } from \"../../utils/tool-stdio\";\n\n/** Read and shallow-validate a built bundle's manifest. */\nexport function readBundleManifest(bundleDir: string): RebaseBundleManifest {\n const manifestPath = path.join(bundleDir, \"manifest.json\");\n if (!fs.existsSync(manifestPath)) {\n throw new Error(\n `No manifest.json in ${bundleDir}. Run \\`rebase build\\` first.`\n );\n }\n let manifest: RebaseBundleManifest;\n try {\n manifest = JSON.parse(fs.readFileSync(manifestPath, \"utf8\")) as RebaseBundleManifest;\n } catch (err) {\n throw new Error(`${manifestPath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (typeof manifest.bundleFormat !== \"number\" || !manifest.runtime?.range) {\n throw new Error(`${manifestPath} is not a valid bundle manifest.`);\n }\n return manifest;\n}\n\n/**\n * The control plane's cap on an uploaded bundle: its `MAX_BUNDLE_BYTES`, which\n * it checks before reading the body.\n */\nexport const MAX_BUNDLE_UPLOAD_BYTES = 100 * 1024 * 1024;\n\n/**\n * Tar a built bundle into a gzipped archive.\n *\n * `node_modules` goes in only with `withModules`: a tree the build vendored for\n * the runtime's platform is the point of vendoring, while one installed into a\n * prebuilt bundle by hand was installed for whatever machine ran it.\n */\nexport function packBundle(bundleDir: string, outPath: string, options: { withModules?: boolean } = {}): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(\n \"tar\",\n // `--no-xattrs` (plus COPYFILE_DISABLE) keeps macOS from writing\n // `LIBARCHIVE.xattr.com.apple.provenance` headers into the archive,\n // which GNU tar on the runtime image then warns about once per file.\n // Harmless, but it buries real extraction errors in noise.\n [\"-czf\", outPath, \"--no-xattrs\", ...(options.withModules ? [] : [\"--exclude\", \"node_modules\"]), \"-C\", bundleDir, \".\"],\n // Only a deploy packs a bundle, and a deploy's stdout may be its JSON result.\n { stdio: toolStdio(true),\nenv: { ...process.env,\nCOPYFILE_DISABLE: \"1\" } }\n );\n child.on(\"error\", reject);\n child.on(\"close\", (code) => (code === 0 ? resolve() : reject(new Error(`tar exited ${code}`))));\n });\n}\n\n/**\n * Pack a bundle for upload — without `node_modules`, even a vendored tree.\n *\n * Vendoring exists so a pod untars and boots rather than spending 35-55s of\n * every start in `npm install`, and a deploy did carry the tree for one night\n * (c36ea4637). It is left out again because of what the control plane does\n * with the archive: `GET /bundle/:projectId/:bundleId` reads the whole object\n * into memory on every pod start, and a runtime rollout restarts every tenant's\n * pods at once. Bundles it was sized against are a few hundred kB; a vendored\n * one is tens of MB, up to the 100 MB cap — N pods starting together would hold\n * N of them. A slower cold start per pod is the status quo every deploy has\n * shipped with; a control plane out of memory is every tenant's outage. The\n * platform's own rebuilds build with `--no-vendor` for the same shape of\n * reason. When the control plane streams bundles, this is the one switch to\n * flip, and `rebase cloud deploy` builds with `vendor: false` until then.\n *\n * `modulesLeftOut` says a tree the build DID vendor was not uploaded — a\n * prebuilt `--bundle-dir` from a plain `rebase build`, which vendors by default.\n */\nexport async function packBundleForUpload(\n bundleDir: string,\n outPath: string,\n manifest: RebaseBundleManifest,\n maxBytes: number = MAX_BUNDLE_UPLOAD_BYTES\n): Promise<{ bytes: number; modulesLeftOut: boolean }> {\n const vendored = manifest.deps?.vendored === true;\n await packBundle(bundleDir, outPath, { withModules: false });\n const bytes = fs.statSync(outPath).size;\n if (bytes > maxBytes) {\n throw new Error(\n `The bundle is ${(bytes / 1024 / 1024).toFixed(1)} MB without its dependencies, over the ` +\n `${Math.round(maxBytes / 1024 / 1024)} MB upload limit.`\n );\n }\n return { bytes, modulesLeftOut: vendored };\n}\n\n/**\n * Assemble the deploy-trigger body for a bundle deploy.\n *\n * The manifest travels with the trigger so the control plane can validate intake\n * without unpacking the uploaded archive first — a rejection (native deps, no\n * matching runtime) is then a fast, cheap answer.\n */\n/** The commit a bundle was built from, as far as the working directory knows. */\nexport interface BundleCommit {\n hash: string;\n message: string;\n}\n\n/**\n * The commit HEAD is on, read here because here is the only place it exists.\n *\n * A bundle deploy has no repository anywhere near the control plane: the CLI\n * builds a tarball and uploads it, so the three paths `deploy.ts` documents for\n * learning a commit — clone, `ls-remote`, or \"there is no repo at all\" — all\n * resolve to the third. Every bundle deployment therefore recorded an empty\n * hash, which is 291 of the 305 rows in production: a Deployments list where\n * almost nothing says what it shipped.\n *\n * But the CLI is standing IN the repository. `git -C <dir> log -1` answers\n * exactly, message included — the one thing even the git-build path cannot get\n * from `ls-remote`.\n *\n * Returns null rather than guessing, for every reason it can fail: no git, not a\n * repository, no commits yet. The server records what it is given and nothing\n * more, so null here stays `UNKNOWN_COMMIT_HASH` there.\n *\n * A dirty tree is NOT reported as a different commit. The bundle may contain\n * uncommitted work, and the honest statement about that is \"built from a tree at\n * <hash>\", not a fabricated identifier — the same rule the rest of this file\n * follows about inventing values.\n */\nexport function bundleCommit(cwd: string, run: (args: string[]) => string = gitIn(cwd)): BundleCommit | null {\n try {\n const hash = run([\"rev-parse\", \"--short=7\", \"HEAD\"]).trim();\n if (!/^[0-9a-f]{7,40}$/.test(hash)) return null;\n // `%s` is the subject alone. A full body would put newlines into a\n // single-line column that the console renders in a table row.\n const message = run([\"log\", \"-1\", \"--pretty=%s\"]).trim();\n return { hash, message };\n } catch {\n return null;\n }\n}\n\n/** `git -C <cwd> …`, as a function, so `bundleCommit` is testable without a repo. */\nfunction gitIn(cwd: string): (args: string[]) => string {\n return (args) => execFileSync(\"git\", [\"-C\", cwd, ...args], { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n}\n\nexport function bundleDeployBody(input: {\n projectId: string;\n bundleId: string;\n manifest: RebaseBundleManifest;\n app?: string;\n message?: string;\n /**\n * Every app this repository declares in `rebase.json`, so the platform can\n * register the whole set rather than only the one being deployed.\n */\n declaredApps?: DeclaredApp[];\n /**\n * What HEAD said when this bundle was built, or null outside a repository.\n *\n * Omitted from the body entirely when null — an absent field and an empty\n * one are the same to the server, and sending `\"\"` would make \"we did not\n * look\" indistinguishable from \"we looked and there was nothing\".\n */\n commit?: BundleCommit | null;\n /**\n * The source this bundle was built from, uploaded so a platform upgrade can\n * rebuild it on a newer release. Omitted when none was uploaded — `--no-source`,\n * a static app, or an upload that failed — never sent empty.\n */\n rebuildSource?: RebuildSource | null;\n /** `--allow-downgrade`: deploy a bundle built on an older release than the project runs. */\n allowFrameworkDowngrade?: boolean;\n}): Record<string, unknown> {\n return {\n projectId: input.projectId,\n bundleId: input.bundleId,\n bundleManifest: input.manifest,\n app: input.app ?? input.manifest.app ?? \"backend\",\n client: \"cli\",\n frameworkVersion: input.manifest.runtime?.builtAgainst,\n ...(input.declaredApps?.length ? { declaredApps: input.declaredApps } : {}),\n ...(input.message ? { message: input.message } : {}),\n ...(input.commit\n ? { gitCommitHash: input.commit.hash, gitCommitMessage: input.commit.message }\n : {}),\n ...(input.rebuildSource\n ? {\n rebuildSource: {\n sourceId: input.rebuildSource.sourceId,\n projectPath: input.rebuildSource.projectPath,\n buildEnv: input.rebuildSource.buildEnv\n }\n }\n : {}),\n ...(input.allowFrameworkDowngrade ? { allowFrameworkDowngrade: true } : {})\n };\n}\n\n/** An app as `rebase.json` declares it, reduced to what the registry stores. */\nexport interface DeclaredApp {\n name: string;\n type: string;\n}\n\n/**\n * The apps a project manifest declares.\n *\n * A deploy only ever ships ONE app's bundle, so the trigger alone could never\n * tell the platform that the repository also contains a web frontend and an\n * admin panel — and the Apps page, whose whole job is to show the set, listed a\n * single entry called \"backend\". Sending the declared set fixes that without\n * pretending the others are deployed: the platform registers them, and their\n * status says what is actually true.\n */\nexport function declaredAppsFrom(manifest: { apps?: Record<string, { type?: string }> } | null | undefined): DeclaredApp[] {\n const apps = manifest?.apps;\n if (!apps || typeof apps !== \"object\") return [];\n return Object.entries(apps)\n .filter(([name]) => name.trim().length > 0)\n // Two types, and the control plane accepts exactly those — anything else\n // is a registration it would reject, which shows up as deploy noise\n // rather than as the manifest error it actually is. `backend` is the\n // narrow case; everything a repository declares that is not the backend\n // is served as files.\n .map(([name, value]) => ({ name,\ntype: value?.type === \"backend\" ? \"backend\" : \"static\" }));\n}\n\n/** Upload a bundle archive; returns the control-plane bundle id. */\nexport async function uploadBundle(\n url: string,\n token: string,\n projectId: string,\n tarPath: string\n): Promise<string> {\n const bytes = fs.readFileSync(tarPath);\n const res = await fetch(\n `${url}/api/functions/deploy/bundle/upload?projectId=${encodeURIComponent(projectId)}`,\n {\n method: \"POST\",\n headers: { Authorization: `Bearer ${token}`,\n\"Content-Type\": \"application/gzip\" },\n body: bytes\n }\n );\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Bundle upload failed (${res.status}): ${body || res.statusText}`);\n }\n const data = (await res.json()) as { bundleId?: string };\n if (!data.bundleId) throw new Error(\"Bundle upload endpoint did not return a bundle id.\");\n return data.bundleId;\n}\n\n/** One DNS record a hostname needs, as the control plane lists it. */\nexport interface DeployHostRecord {\n type: string;\n name: string;\n values: string[];\n}\n\n/**\n * A hostname an app in this deploy is declared on, as the deploy found it.\n *\n * The control plane registers each one on the project as it deploys — an app\n * whose `path` is `https://admin.example.com` needs that host on the project\n * before anything can route it — and a new one starts `pending`, because it is\n * served only once its DNS is published and verified. `records` is what to\n * publish, present for a pending host.\n */\nexport interface DeployHost {\n host: string;\n status: \"verified\" | \"pending\";\n records?: DeployHostRecord[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction recordFrom(value: unknown): DeployHostRecord | null {\n if (!isRecord(value) || typeof value.type !== \"string\" || typeof value.name !== \"string\") return null;\n const values = Array.isArray(value.values) ? value.values.filter((v): v is string => typeof v === \"string\") : [];\n return values.length > 0 ? { type: value.type, name: value.name, values } : null;\n}\n\n/**\n * The `hosts` a deploy response carries, read defensively.\n *\n * `undefined` when there is no such field, which is what a control plane that\n * predates host-routed apps answers: the caller then leaves `hosts` out of its\n * own output rather than reporting an empty set nobody looked for. An entry\n * with no hostname is dropped, and any status but `verified` is pending — the\n * same rule `cloud domains` reads rows by, because an unreadable status must\n * not print as live.\n */\nexport function deployHostsFrom(response: unknown): DeployHost[] | undefined {\n if (!isRecord(response) || !Array.isArray(response.hosts)) return undefined;\n const hosts: DeployHost[] = [];\n for (const entry of response.hosts) {\n if (!isRecord(entry) || typeof entry.host !== \"string\" || entry.host === \"\") continue;\n const records = Array.isArray(entry.records)\n ? entry.records.map(recordFrom).filter((r): r is DeployHostRecord => r !== null)\n : [];\n hosts.push({\n host: entry.host,\n status: entry.status === \"verified\" ? \"verified\" : \"pending\",\n ...(records.length > 0 ? { records } : {})\n });\n }\n return hosts;\n}\n\n/**\n * What to tell somebody whose deploy declared a hostname that is not live yet.\n *\n * A deploy that succeeds with an app on a hostname nobody can reach reads as a\n * broken deploy, so each pending host gets its own block: that it is registered\n * but waiting, the records to create, and the command that finishes the job.\n * The records come from the control plane, never composed here — A or CNAME\n * depends on apex-vs-subdomain and on the ingress behind the project, which\n * the CLI cannot know. Plain text: the caller colours it.\n */\nexport function pendingHostNotices(hosts: DeployHost[]): Array<{ headline: string; details: string[] }> {\n return hosts\n .filter(host => host.status !== \"verified\")\n .map(({ host, records }) => ({\n headline: `${host} is registered on this project, but not served until its DNS is verified.`,\n details: [\n ...(records?.length\n ? [\n \"Create these records with your DNS provider:\",\n ...records.map(record => ` ${record.type} ${record.name} → ${record.values.join(\", \")}`)\n ]\n : [\"See the records it needs with `rebase cloud domains list`.\"]),\n `Then run \\`rebase cloud domains verify ${host}\\`.`\n ]\n }));\n}\n","/**\n * What `rebase cloud deploy` says when it is done: which apps it shipped, where\n * each one answers, whether the new version is actually being served, and — when\n * it failed — which app and why, in one line.\n *\n * A deploy used to end on `{\"success\":true,…,\"hosts\":[]}`: no URL, a `hosts`\n * list that was empty for a project with a live host, and nothing that said the\n * new version was being served. Whoever ran it then checked with `curl`, after\n * every deploy. Everything here exists so they do not have to.\n *\n * Pure apart from {@link checkLive}, whose `fetch` and clock are injectable, so\n * all of it is testable without a control plane.\n */\nimport chalk from \"chalk\";\nimport type { RebaseBundleManifest } from \"@rebasepro/types\";\nimport type { DeployHost } from \"./bundle-deploy\";\n\n/**\n * Where a backend's API is mounted on its host. The runtime's default\n * `REBASE_BASE_PATH`, which the platform does not let a project change.\n */\nexport const BACKEND_API_PATH = \"/api\";\n\n/** How long the live check waits by default before saying it could not confirm. */\nexport const DEFAULT_LIVE_TIMEOUT_MS = 60_000;\n\n/** One app a deploy shipped, and the address it now answers on. */\nexport interface DeployedApp {\n name: string;\n type: \"backend\" | \"static\";\n /**\n * The address a person would open — the site for a static app, the API\n * root for a backend. Absent when the host it is served on is unknown:\n * a guessed URL is worse than none.\n */\n url?: string;\n /** The hostname `url` is on. */\n host?: string;\n}\n\n/**\n * The apps a bundle ships, read off the bundle's own manifest.\n *\n * The manifest rather than `rebase.json`, because it is what was uploaded: it\n * covers `--bundle-dir` and a static app deployed alone exactly as it covers a\n * backend with its frontends folded in. A static app with a hostname of its own\n * answers there; every other app answers on the project's host.\n */\nexport function bundleApps(\n manifest: Pick<RebaseBundleManifest, \"app\" | \"kind\"> & { entry?: { static?: RebaseBundleManifest[\"entry\"][\"static\"] } },\n projectHost: string | undefined\n): DeployedApp[] {\n const apps: DeployedApp[] = [];\n if (manifest.kind === \"backend\") {\n apps.push(appAt(manifest.app, \"backend\", projectHost, BACKEND_API_PATH));\n }\n for (const entry of manifest.entry?.static ?? []) {\n const name = entry.name ?? (manifest.kind === \"static\" ? manifest.app : lastSegment(entry.dir));\n apps.push(appAt(name, \"static\", entry.host ?? projectHost, entry.path));\n }\n // A static bundle is its one app, whatever its entry says.\n if (manifest.kind === \"static\" && apps.length === 0) {\n apps.push(appAt(manifest.app, \"static\", projectHost, \"/\"));\n }\n // Root-mounted sites first: the address most people came for.\n return apps.sort((a, b) => order(a) - order(b));\n}\n\n/**\n * The one app a source build ships: whatever image the build produced, on the\n * project's host. The CLI did not build it, so it cannot say what is inside.\n */\nexport function sourceBuildApps(appName: string | undefined, projectHost: string | undefined): DeployedApp[] {\n return [appAt(appName ?? \"backend\", \"backend\", projectHost, \"/\")];\n}\n\nfunction appAt(name: string, type: DeployedApp[\"type\"], host: string | undefined, appPath: string): DeployedApp {\n if (!host) return { name,\ntype };\n const suffix = appPath === \"/\" || appPath === \"\" ? \"\" : appPath.replace(/\\/$/, \"\");\n return { name,\ntype,\nhost,\nurl: `https://${host}${suffix}` };\n}\n\nfunction lastSegment(dir: string): string {\n const parts = dir.split(\"/\").filter(Boolean);\n return parts[parts.length - 1] ?? dir;\n}\n\nfunction order(app: DeployedApp): number {\n if (app.type === \"static\" && app.url && !new URL(app.url).pathname.replace(/\\/$/, \"\")) return 0;\n return app.type === \"static\" ? 1 : 2;\n}\n\n/**\n * Every hostname this deploy is served on: the project's own host, then the\n * hostnames the control plane registered for apps that declare one.\n *\n * The control plane's `hosts` lists only the second kind — hostnames an app's\n * `path` names, which a deploy has to register — so for the ordinary project,\n * served on its own `<slug>.rebase.website`, it was always empty. That read as\n * \"this deploy is served nowhere\". The project's host is served by the platform\n * from the moment the project exists, so it goes first, as verified.\n */\nexport function deployHosts(registered: DeployHost[] | undefined, projectHost: string | undefined): DeployHost[] {\n const hosts: DeployHost[] = projectHost ? [{ host: projectHost,\nstatus: \"verified\" }] : [];\n for (const entry of registered ?? []) {\n if (!hosts.some(h => h.host === entry.host)) hosts.push(entry);\n }\n return hosts;\n}\n\n/* ─── is the new version live? ───────────────────────────────────────────── */\n\n/** What probing one app's address found. */\nexport interface LiveCheck {\n app: string;\n /** The address probed: the site itself, or a backend's `/health` (or `/api/health`). */\n url: string;\n live: boolean;\n /** The HTTP status of the last answer, when there was one. */\n httpStatus?: number;\n /**\n * The deployment the answer says it came from (`x-rebase-deployment`), when\n * it says. Only the platform's static hosting stamps it; a managed pod's\n * readiness is the control plane's to confirm, and it did before `success`.\n */\n servingDeployment?: string;\n /** Why it is not live, in a few words. */\n reason?: string;\n}\n\n/**\n * The URL that proves an app is up.\n *\n * For a backend, the bare `/health`: every rebase-server registers it, beside\n * `<REBASE_BASE_PATH>/health`, and the platform routes it to the backend ahead\n * of any static app. `/api/health` is only where it lives when the base path is\n * the default — a project with `REBASE_BASE_PATH=/v1` and a site at `/` answers\n * it with the site's index.html, and its deploy read as not live.\n */\nexport function probeUrl(app: DeployedApp): string | undefined {\n if (!app.url || !app.host) return undefined;\n return app.type === \"backend\" ? `https://${app.host}/health` : app.url;\n}\n\n/** Where a server that registers no bare `/health` — one of the developer's own — may still answer. */\nfunction fallbackHealthUrl(app: DeployedApp): string {\n return `https://${app.host}${BACKEND_API_PATH}/health`;\n}\n\ntype FetchLike = typeof fetch;\n\n/**\n * Probe one app once.\n *\n * A backend is live when its health route answers `200 {\"status\":\"ok\"}` — a\n * site at `/` with client-side routing answers 200 to *any* path, so a bare\n * status would let a folded SPA vouch for an API that is down. A static app is\n * live when its address answers below 400 and, if the answer names the\n * deployment it came from, that deployment is this one.\n */\nexport async function probeOnce(\n app: DeployedApp,\n deploymentId: string,\n fetchImpl: FetchLike\n): Promise<LiveCheck | undefined> {\n const url = probeUrl(app);\n if (!url) return undefined;\n const check = await probeAt(app, url, deploymentId, fetchImpl);\n // Asked again at `/api/health` only when the bare path is not a health\n // route at all — a 404, or a 200 that is not its JSON (a site's catch-all).\n // A backend that answered 503 \"degraded\" there has answered.\n const notAHealthRoute = (answer: LiveCheck) => !answer.live && (answer.httpStatus === 404 || answer.httpStatus === 200);\n if (app.type !== \"backend\" || !notAHealthRoute(check)) return check;\n const fallback = await probeAt(app, fallbackHealthUrl(app), deploymentId, fetchImpl);\n return fallback.httpStatus !== undefined && !notAHealthRoute(fallback) ? fallback : check;\n}\n\nasync function probeAt(\n app: DeployedApp,\n url: string,\n deploymentId: string,\n fetchImpl: FetchLike\n): Promise<LiveCheck> {\n try {\n const res = await fetchImpl(url, {\n redirect: \"follow\",\n signal: AbortSignal.timeout(10_000),\n headers: { \"cache-control\": \"no-cache\" }\n });\n if (app.type === \"backend\") {\n const body = res.status === 200 ? await res.json().catch(() => undefined) : undefined;\n const ok = typeof body === \"object\" && body !== null && \"status\" in body && body.status === \"ok\";\n return ok\n ? { app: app.name,\nurl,\nlive: true,\nhttpStatus: res.status }\n : { app: app.name,\nurl,\nlive: false,\nhttpStatus: res.status,\n reason: res.status === 200 ? \"health check did not answer ok\" : `health check answered ${res.status}` };\n }\n const serving = res.headers.get(\"x-rebase-deployment\") ?? undefined;\n if (res.status >= 400) {\n return { app: app.name,\nurl,\nlive: false,\nhttpStatus: res.status,\nreason: `answered ${res.status}` };\n }\n if (serving && serving !== deploymentId) {\n return { app: app.name,\nurl,\nlive: false,\nhttpStatus: res.status,\nservingDeployment: serving,\n reason: `still serving deployment ${serving}` };\n }\n return { app: app.name,\nurl,\nlive: true,\nhttpStatus: res.status,\n...(serving ? { servingDeployment: serving } : {}) };\n } catch (e) {\n return { app: app.name,\nurl,\nlive: false,\nreason: networkReason(e) };\n }\n}\n\n/** `fetch failed` says nothing; its cause usually says which half failed. */\nfunction networkReason(e: unknown): string {\n if (e instanceof Error) {\n if (e.name === \"TimeoutError\" || e.name === \"AbortError\") return \"no answer within 10s\";\n const cause = \"cause\" in e ? e.cause : undefined;\n if (cause instanceof Error && \"code\" in cause && typeof cause.code === \"string\") {\n return cause.code === \"ENOTFOUND\" ? \"hostname does not resolve yet\" : `unreachable (${cause.code})`;\n }\n return e.message;\n }\n return String(e);\n}\n\n/**\n * Probe every app on a verified host until each is live or `timeoutMs` passes.\n *\n * An app on a hostname whose DNS is not verified is reported, not probed: the\n * platform does not route it, and waiting on it would only spend the timeout.\n * Returns one entry per app that has a URL.\n */\nexport async function checkLive(\n apps: DeployedApp[],\n opts: {\n deploymentId: string;\n hosts: DeployHost[];\n timeoutMs: number;\n intervalMs?: number;\n fetchImpl?: FetchLike;\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n }\n): Promise<LiveCheck[]> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const sleep = opts.sleep ?? ((ms: number) => new Promise<void>(r => setTimeout(r, ms)));\n const now = opts.now ?? Date.now;\n const deadline = now() + opts.timeoutMs;\n\n const results = new Map<string, LiveCheck>();\n const pending: DeployedApp[] = [];\n for (const app of apps) {\n const url = probeUrl(app);\n if (!url) continue;\n const host = opts.hosts.find(h => h.host === app.host);\n if (host && host.status !== \"verified\") {\n results.set(app.name, { app: app.name,\nurl,\nlive: false,\nreason: `DNS for ${app.host} is not verified yet` });\n } else {\n pending.push(app);\n }\n }\n\n for (;;) {\n const round = await Promise.all(pending.map(app => probeOnce(app, opts.deploymentId, fetchImpl)));\n for (const check of round) if (check) results.set(check.app, check);\n const stillDown = pending.filter(app => results.get(app.name)?.live !== true);\n if (stillDown.length === 0 || now() >= deadline) break;\n pending.splice(0, pending.length, ...stillDown);\n await sleep(Math.min(opts.intervalMs ?? 2_000, Math.max(0, deadline - now())));\n }\n\n // In the order the apps were listed, not the order they came up in.\n return apps.flatMap(app => results.get(app.name) ?? []);\n}\n\n/* ─── what gets printed ──────────────────────────────────────────────────── */\n\n/** `42s`, `1m 12s`, `12m`. */\nexport function formatDuration(ms: number): string {\n const seconds = Math.max(0, Math.round(ms / 1000));\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.floor(seconds / 60);\n const rest = seconds % 60;\n return rest === 0 ? `${minutes}m` : `${minutes}m ${rest}s`;\n}\n\nexport interface DeploySummaryInput {\n projectRef: string;\n deploymentId: string;\n elapsedMs: number;\n apps: DeployedApp[];\n /**\n * The live check's results; `undefined` when it was not run\n * (`--live-timeout 0`), which is said rather than passed over.\n */\n live: LiveCheck[] | undefined;\n liveTimeoutMs: number;\n}\n\n/**\n * The human summary a successful deploy ends on: the project, each app with its\n * address and whether it answers, the deployment id and how long it took, and\n * one line that says whether the new version is live.\n */\nexport function deploySummaryLines(input: DeploySummaryInput): string[] {\n const lines: string[] = [\n \"\",\n chalk.bold.green(` ✓ Deployed ${input.projectRef} in ${formatDuration(input.elapsedMs)}`)\n + chalk.gray(` (deployment ${input.deploymentId})`),\n \"\"\n ];\n\n const nameWidth = Math.max(...input.apps.map(a => a.name.length), 0);\n const urlWidth = Math.max(...input.apps.map(a => (a.url ?? \"\").length), 0);\n for (const app of input.apps) {\n const check = input.live?.find(c => c.app === app.name);\n const state = !check\n ? \"\"\n : check.live\n ? chalk.green(check.servingDeployment ? \"live, serving this deployment\" : \"live\")\n : chalk.yellow(`not live: ${check.reason ?? \"no answer\"}`);\n const url = app.url ? chalk.cyan(app.url.padEnd(urlWidth)) : chalk.gray(\"(address unknown — see `rebase cloud status`)\");\n lines.push(` ${app.name.padEnd(nameWidth)} ${chalk.gray(app.type.padEnd(7))} ${url} ${state}`.trimEnd());\n }\n lines.push(\"\");\n\n const verdict = liveVerdict(input.live, input.liveTimeoutMs);\n lines.push(verdict.live === true\n ? chalk.green(` ✓ ${verdict.message}`)\n : verdict.live === false ? chalk.yellow(` ⚠ ${verdict.message}`) : chalk.gray(` ${verdict.message}`));\n lines.push(\"\");\n return lines;\n}\n\n/**\n * Whether the new version is live, as one sentence and one boolean.\n *\n * `live: null` when nothing was checked — the check was skipped, or no app had\n * an address to check — which is not the same answer as \"no\".\n */\nexport function liveVerdict(live: LiveCheck[] | undefined, timeoutMs: number): { live: boolean | null; message: string } {\n if (live === undefined) {\n return { live: null,\nmessage: \"Live check skipped (--live-timeout 0).\" };\n }\n if (live.length === 0) {\n return { live: null,\nmessage: \"No address to check: run `rebase cloud status` to see where the project answers.\" };\n }\n const down = live.filter(c => !c.live);\n if (down.length === 0) {\n return { live: true,\nmessage: \"Live: the new version answers on every address above.\" };\n }\n const which = down.map(c => `${c.app} (${c.reason ?? \"no answer\"})`).join(\", \");\n return {\n live: false,\n message: `Not confirmed live after ${formatDuration(timeoutMs)}: ${which}. `\n + \"The deployment itself succeeded — check again with `rebase cloud status`.\"\n };\n}\n\n/**\n * Why a deployment failed, in one line, from its build log.\n *\n * The control plane ends a failed job's log on a `❌ <heading>: <why>` line (a\n * cancelled one on `🛑`), so that line is the reason. A log without one — an\n * older control plane, a job that died mid-write — gives its last line instead,\n * which is still closer to the truth than \"failed\".\n */\nexport function failureReason(logs: string): string | undefined {\n const lines = logs.split(\"\\n\").map(l => l.trim()).filter(Boolean);\n const marked = [...lines].reverse().find(l => /(^|\\]\\s*)(❌|🛑)/.test(l));\n const line = marked ?? lines[lines.length - 1];\n if (!line) return undefined;\n return line\n .replace(/^\\[[^\\]]*\\]\\s*/, \"\")\n .replace(/^(❌|🛑)\\s*/, \"\")\n .slice(0, 300);\n}\n\n/**\n * The one line a failed deploy ends on: which app, why, and where the rest is.\n */\nexport function failureLine(opts: { apps: string[]; status: string; deploymentId: string; logs: string }): string {\n const subject = opts.apps.length > 0 ? opts.apps.join(\" + \") : \"Deployment\";\n const why = failureReason(opts.logs) ?? `deployment ${opts.status}`;\n return `${subject} ${opts.status === \"cancelled\" ? \"was cancelled\" : \"failed to deploy\"}: ${why}`;\n}\n\n/**\n * Where to read the rest of a failed deploy's story.\n *\n * A preview's build log is not production's: bare `rebase cloud logs` reads\n * the newest PRODUCTION deployment, so pointing a failed preview at it showed\n * the last good production build under the preview's deployment id.\n */\nexport function failureHint(deploymentId: string, preview?: string): string {\n return preview !== undefined\n ? `Full build log: \\`rebase cloud logs --preview ${preview}\\` (deployment ${deploymentId}).`\n : `Full build log: \\`rebase cloud logs\\` (deployment ${deploymentId}).`;\n}\n","/**\n * Temporary archives, each in a directory no other run shares.\n *\n * A name built from `Date.now()` is shared by every run started in the same\n * millisecond — two deploys in parallel CI jobs, two vitest workers — and the\n * first run to finish removed the archive the other was still packing or\n * uploading. `mkdtemp` creates the directory atomically under a random suffix,\n * so a path inside it belongs to this run alone.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\n/**\n * Run `work` with a path for `<prefix>.tar.gz` inside a fresh temporary\n * directory, and remove that directory however the run ends.\n *\n * \"However\" includes `process.exit`: a `fail()` inside `work` ends the process\n * on the spot, and no `finally` runs after that, so the directory is removed on\n * the process's `exit` event as well.\n */\nexport async function withTempArchive<T>(prefix: string, work: (archivePath: string) => Promise<T>): Promise<T> {\n const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), `${prefix}-`));\n const remove = (): void => fs.rmSync(dir, { recursive: true, force: true });\n process.on(\"exit\", remove);\n try {\n return await work(path.join(dir, `${prefix}.tar.gz`));\n } finally {\n process.off(\"exit\", remove);\n remove();\n }\n}\n","/**\n * The project's source, uploaded beside its bundle so the platform can rebuild it.\n *\n * A managed deploy ships a built bundle, and a bundle is fixed to the framework\n * release it was built on. When the platform rolls a newer release across the\n * fleet it has to rebuild each project from source — and the bundle path never\n * uploaded any: the control plane held a tarball of compiled output and\n * nothing it could compile again. So every bundle deploy now also packs the\n * source the bundle was built from, uploads it, and names it in the trigger.\n *\n * Three rules shape what goes in:\n *\n * - **Git decides, when there is a repository.** `git ls-files --cached\n * --others --exclude-standard` at the repository's top level is exactly what\n * the developer considers source: `.gitignore` honoured the way git honours\n * it, and a sibling package the project links (`link:../../packages/editor`)\n * included, because it is outside the project directory but inside the\n * repository. Outside a repository — or inside one that ignores the project —\n * the project is walked, and its `.gitignore` files still decide.\n * - **Secrets never leave the machine, whatever git says.** A committed `.env`\n * is still a `.env`. {@link neverUploaded} is applied after git, not instead\n * of it.\n * - **It never costs the deploy.** The bundle is what runs; the source only\n * lets a later platform upgrade rebuild it. Too large, unpackable, refused by\n * the control plane — each is a warning, and the deploy goes on without it.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { execFileSync, spawn } from \"child_process\";\nimport dotenv from \"dotenv\";\nimport type { RebaseProjectManifest } from \"@rebasepro/types\";\nimport { cliUserAgent } from \"../../utils/version\";\nimport { withTempArchive } from \"../../utils/temp-archive\";\n\n/**\n * The control plane's cap on an uploaded source archive.\n *\n * Keep in sync with its build-context cap (deploy/upload `MAX_BYTES` and the\n * backend's `maxBodySize`). Checked before uploading, so an oversized archive is\n * a message in milliseconds rather than a bare 413 after the upload.\n */\nexport const MAX_SOURCE_UPLOAD_BYTES = 100 * 1024 * 1024;\n\n/** Env files that are templates by convention, and safe to ship. */\nconst ENV_TEMPLATES = new Set([\".env.example\", \".env.sample\", \".env.template\"]);\n\n/**\n * Whether a file must never be uploaded, whatever the ignore rules said.\n *\n * `relativePath` is POSIX. Installed packages, git's own directory and built\n * bundles are never source. Every `.env` and `.env.*` is excluded except the\n * three template names, and so is direnv's `.envrc`, which is the same thing\n * under another name.\n *\n * So is what the CLI keeps on this machine: `.rebase/`, which holds the\n * development database, and the `.rebase-dev-*` files beside it, one of which\n * is the development signing secrets. And so is a `*.dump`, which is what\n * `rebase db backup` writes: every row of the database, `rebase.users`\n * password hashes included.\n */\nexport function neverUploaded(relativePath: string): boolean {\n const segments = relativePath.split(\"/\");\n if (segments.some(segment =>\n segment === \"node_modules\" || segment === \".git\" || segment === \".rebase\" || segment.startsWith(\"dist-bundle\"))) {\n return true;\n }\n const base = segments[segments.length - 1];\n if (base === \".envrc\" || base.startsWith(\".rebase-dev-\") || base.endsWith(\".dump\")) return true;\n if ((base === \".env\" || base.startsWith(\".env.\")) && !ENV_TEMPLATES.has(base)) return true;\n return false;\n}\n\n/** Directories the walk outside a repository never enters. */\nconst WALK_SKIP = new Set([\"node_modules\", \".git\", \".rebase\", \".turbo\", \".next\", \"coverage\"]);\n\n/** The same directories as `ls-files` excludes, plus every `dist*` build directory. */\nconst WALK_EXCLUDES = [...[...WALK_SKIP].map(name => `--exclude=${name}/`), \"--exclude=dist*/\"];\n\n/** The file that says what a directory's source is not, which a walk has to honour. */\nconst IGNORE_FILE = \".gitignore\";\n\nexport interface SourceListing {\n /** The directory the archive is rooted at: the repository's top level, or the project root. */\n root: string;\n /** Regular files to pack, relative to `root`, POSIX, sorted. */\n files: string[];\n /** The project root relative to `root`, POSIX; `\"\"` when they are the same directory. */\n projectPath: string;\n /** Whether git chose the files. */\n fromGit: boolean;\n}\n\n/** `git -C <cwd> …`, returning stdout. Throws when git is missing or refuses. */\nexport type GitRunner = (cwd: string, args: string[]) => string;\n\nconst runGit: GitRunner = (cwd, args) => execFileSync(\"git\", [\"-C\", cwd, ...args], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n // `ls-files` on a large monorepo is megabytes; the default 1 MiB buffer\n // would kill it and silently fall back to the walk.\n maxBuffer: 256 * 1024 * 1024\n});\n\nfunction toPosix(relative: string): string {\n return relative.split(path.sep).join(\"/\");\n}\n\n/** A regular file on disk: not missing, not a directory or submodule, not a symlink. */\nfunction isRegularFile(absolute: string): boolean {\n try {\n return fs.lstatSync(absolute).isFile();\n } catch {\n return false;\n }\n}\n\n/** One tree the archive carries: a repository's files, or a walked directory's. */\ninterface SourceUnit {\n root: string;\n /** Relative to `root`, POSIX. */\n files: string[];\n fromGit: boolean;\n}\n\n/** Split `-z` output into its entries. */\nfunction nulSeparated(output: string): string[] {\n return [...new Set(output.split(\"\\0\").filter(Boolean))];\n}\n\n/**\n * Run `fn` with the git directory of a throwaway, empty repository.\n *\n * `git ls-files` reads `.gitignore` files only inside a repository. Pointed at\n * an empty one with `--git-dir`, and at a directory with `--work-tree`, it lists\n * that directory's files the way git would — nested ignore files, negations and\n * the user's global excludes included — without the directory being a\n * repository, or `git init` touching it.\n */\nfunction withScratchRepository<T>(git: GitRunner, fn: (gitDir: string) => T): T {\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"rebase-ignore-\"));\n try {\n git(scratch, [\"init\", \"-q\"]);\n return fn(path.join(scratch, \".git\"));\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * The files of the repository `dir` belongs to — tracked and unignored, the way\n * git sees them — or, when no repository holds it, `dir` walked.\n *\n * A repository that lists nothing under `dir` does not hold it: a project in a\n * directory the surrounding repository ignores (`tmp/my-app` under a repository\n * ignoring `tmp/`) has no repository of its own. Uploading that repository sent\n * everything except the project, so the project is walked instead.\n */\nfunction listUnit(dir: string, git: GitRunner): SourceUnit {\n try {\n const toplevel = git(dir, [\"rev-parse\", \"--show-toplevel\"]).trim();\n if (toplevel) {\n const root = fs.realpathSync(toplevel);\n const listed = git(root, [\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"]);\n // `--cached` lists a file once per merge stage during a conflict,\n // and a file deleted from the working tree but still in the index;\n // the set and the disk check take care of both. Submodules and\n // symlinks are listed too, and are not regular files.\n const files = nulSeparated(listed)\n .filter(relative => !neverUploaded(relative) && isRegularFile(path.join(root, relative)));\n const inside = toPosix(path.relative(root, dir));\n if (inside === \"\" || files.some(file => file.startsWith(`${inside}/`))) {\n return { root, files, fromGit: true };\n }\n }\n } catch {\n // Not a repository, no git, or git refusing the directory: the walk.\n }\n return { root: dir, files: walkFiles(dir, git), fromGit: false };\n}\n\n/**\n * `dir`'s files, walked, with its `.gitignore` files honoured.\n *\n * A scaffold made without `git init` still carries the stock `.gitignore`, and\n * it is the only statement of what in the directory is not source: `backups/`\n * with its database dumps, `uploads/` with the users' files. Git reads it,\n * through a throwaway repository (see {@link withScratchRepository}); a\n * repository nested in `dir` lists as one directory entry, and is listed as the\n * repository it is.\n *\n * Without git the walk has fixed excludes alone, and those cannot read an\n * ignore file. So a directory holding one is refused rather than walked past\n * it — the developer wrote down what must stay on this machine.\n */\nfunction walkFiles(dir: string, git: GitRunner): string[] {\n let listed: string[];\n try {\n listed = withScratchRepository(git, gitDir => nulSeparated(git(dir, [\n `--git-dir=${gitDir}`,\n `--work-tree=${dir}`,\n \"ls-files\", \"-z\", \"--others\", \"--exclude-standard\", ...WALK_EXCLUDES\n ])));\n } catch {\n return walkWithoutGit(dir);\n }\n\n const files: string[] = [];\n for (const relative of listed) {\n if (relative.endsWith(\"/\")) {\n // A repository of its own inside the walked directory.\n const nested = listUnit(path.join(dir, relative), git);\n const prefix = toPosix(path.relative(dir, nested.root));\n if (prefix.startsWith(\"..\") || path.isAbsolute(prefix)) continue;\n for (const file of nested.files) files.push(prefix ? `${prefix}/${file}` : file);\n } else if (!neverUploaded(relative) && isRegularFile(path.join(dir, relative))) {\n files.push(relative);\n }\n }\n return files;\n}\n\n/** The walk with fixed excludes, for a machine with no git. Refuses a tree with an ignore file in it. */\nfunction walkWithoutGit(dir: string): string[] {\n const files: string[] = [];\n const walk = (current: string, prefix: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(current, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const relative = prefix ? `${prefix}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (WALK_SKIP.has(entry.name) || entry.name.startsWith(\"dist\")) continue;\n walk(path.join(current, entry.name), relative);\n } else if (entry.isFile() && entry.name === IGNORE_FILE) {\n throw new Error(\n `${relative} says what is not source, and reading it takes git, which is not available here`\n );\n } else if (entry.isFile() && !neverUploaded(relative)) {\n files.push(relative);\n }\n }\n };\n walk(dir, \"\");\n return files;\n}\n\n/** Whether `candidate` is `dir` or inside it. */\nfunction isWithin(dir: string, candidate: string): boolean {\n const relative = path.relative(dir, candidate);\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\n/** The deepest directory containing every path given. */\nfunction commonAncestor(paths: string[]): string {\n let ancestor = paths[0];\n for (const p of paths.slice(1)) {\n while (!isWithin(ancestor, p)) ancestor = path.dirname(ancestor);\n }\n return ancestor;\n}\n\nconst DEPENDENCY_FIELDS = [\"dependencies\", \"devDependencies\", \"optionalDependencies\"] as const;\n\n/**\n * Directories outside every unit that a unit's `package.json` files link to\n * with `link:` or `file:`.\n *\n * `@rebasepro/*` links are not followed. They point at a local framework\n * checkout, which is not the project's source and would drag a whole monorepo\n * into the archive; a rebuild moves those packages to a published release\n * anyway.\n */\nfunction externalLinkTargets(units: SourceUnit[]): string[] {\n const targets = new Set<string>();\n for (const unit of units) {\n for (const relative of unit.files) {\n if (path.posix.basename(relative) !== \"package.json\") continue;\n let manifest: unknown;\n try {\n manifest = JSON.parse(fs.readFileSync(path.join(unit.root, relative), \"utf8\"));\n } catch {\n continue;\n }\n if (typeof manifest !== \"object\" || manifest === null) continue;\n for (const field of DEPENDENCY_FIELDS) {\n const deps = (manifest as Record<string, unknown>)[field];\n if (typeof deps !== \"object\" || deps === null) continue;\n for (const [name, spec] of Object.entries(deps)) {\n if (name.startsWith(\"@rebasepro/\") || typeof spec !== \"string\") continue;\n const match = /^(?:link|file):(.+)$/.exec(spec);\n if (!match) continue;\n const target = path.resolve(unit.root, path.posix.dirname(relative), match[1]);\n let real: string;\n try {\n real = fs.realpathSync(target);\n if (!fs.statSync(real).isDirectory()) continue;\n } catch {\n continue;\n }\n if (!units.some(u => isWithin(u.root, real))) targets.add(real);\n }\n }\n }\n }\n return [...targets];\n}\n\n/**\n * The files a source upload carries, and where they are rooted.\n *\n * The project's repository first — or the project walked, outside git. Then\n * every repository a local `link:`/`file:` dependency reaches outside it, until\n * nothing new is reached, rooted together at their deepest common directory.\n * That is dadaki's shape: its Rebase project is a repository of its own, nested\n * inside the editor's repository (which ignores it), and its frontend links\n * `../../packages/editor` from there. A listing of the project's repository\n * alone rebuilt into \"Rollup failed to resolve import @dadaki/editor\".\n *\n * Paths are resolved through `realpath` first: git reports its top level with\n * symlinks resolved (`/private/var/…` for a macOS temp directory), and a\n * project path computed against the unresolved one would climb out of the\n * archive with `../`.\n */\nexport function listSourceFiles(projectRoot: string, git: GitRunner = runGit): SourceListing {\n const realRoot = fs.realpathSync(projectRoot);\n const units: SourceUnit[] = [listUnit(realRoot, git)];\n for (let reached = externalLinkTargets(units); reached.length > 0; reached = externalLinkTargets(units)) {\n for (const target of reached) {\n if (units.some(u => isWithin(u.root, target))) continue;\n units.push(listUnit(target, git));\n }\n }\n\n const root = commonAncestor(units.map(u => u.root));\n const files = new Set<string>();\n for (const unit of units) {\n const prefix = toPosix(path.relative(root, unit.root));\n for (const file of unit.files) files.add(prefix ? `${prefix}/${file}` : file);\n }\n return {\n root,\n files: [...files].sort(),\n projectPath: toPosix(path.relative(root, realRoot)),\n fromGit: units.every(u => u.fromGit)\n };\n}\n\n/** The per-directory file of patterns a `--source` build context leaves out, beside `.gitignore`. */\nconst CONTEXT_IGNORE_FILE = \".rebaseignore\";\n\n/**\n * The files of a `--source` build context: `dir` and what is under it, relative\n * to it, POSIX, sorted.\n *\n * The same rules as the rebuild source — git decides, and {@link neverUploaded}\n * after it — restricted to `dir`, which is the context's root, so a Dockerfile\n * in it still reads its paths from there. A `dir` that is a subfolder of a\n * repository is held to that repository's `.gitignore`, which is where a\n * monorepo keeps it.\n *\n * `.rebaseignore` in `dir` leaves out more, read with `.gitignore` syntax and\n * anchored at `dir`. It needs git to be read, like `.gitignore` outside a\n * repository; without git, a context that has one is refused.\n */\nexport function listContextFiles(dir: string, git: GitRunner = runGit): string[] {\n const root = fs.realpathSync(dir);\n const unit = listUnit(root, git);\n const prefix = toPosix(path.relative(unit.root, root));\n let files = prefix === \"\"\n ? unit.files\n : unit.files.filter(file => file.startsWith(`${prefix}/`)).map(file => file.slice(prefix.length + 1));\n\n const contextIgnore = path.join(root, CONTEXT_IGNORE_FILE);\n if (fs.existsSync(contextIgnore)) {\n // Everything under `dir` the patterns match — the only patterns read,\n // since `--exclude-standard` is not passed — through a throwaway\n // repository, so they anchor at `dir` whatever repository holds it.\n const ignored = new Set(withScratchRepository(git, gitDir => nulSeparated(git(root, [\n `--git-dir=${gitDir}`,\n `--work-tree=${root}`,\n \"ls-files\", \"-z\", \"--others\", \"--ignored\", `--exclude-from=${contextIgnore}`\n ]))));\n files = files.filter(file => !ignored.has(file));\n }\n return [...files].sort();\n}\n\n/**\n * Pack a listing into a gzipped tarball at `outPath`.\n *\n * The list goes to tar as a NUL-separated file (`--null -T`), so a path with a\n * space or a newline in it is one path. `--no-xattrs` and `COPYFILE_DISABLE`\n * keep macOS's extended attributes and AppleDouble `._*` sidecars out of the\n * archive, as `packBundle` does; GNU tar accepts both. Every path handed to tar\n * is absolute, because GNU tar resolves a `-T` file after it has applied `-C`.\n */\nexport function packSource(listing: Pick<SourceListing, \"root\" | \"files\">, outPath: string): Promise<void> {\n const listPath = `${outPath}.files`;\n fs.writeFileSync(listPath, listing.files.map(file => `${file}\\0`).join(\"\"));\n return new Promise<void>((resolve, reject) => {\n const child = spawn(\n \"tar\",\n [\"-czf\", path.resolve(outPath), \"--no-xattrs\", \"--null\", \"-C\", listing.root, \"-T\", path.resolve(listPath)],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"], env: { ...process.env, COPYFILE_DISABLE: \"1\" } }\n );\n let stderr = \"\";\n child.stderr.on(\"data\", chunk => (stderr += String(chunk)));\n child.on(\"error\", reject);\n child.on(\"close\", code => (code === 0 ? resolve() : reject(new Error(stderr.trim() || `tar exited ${code}`))));\n }).finally(() => fs.rmSync(listPath, { force: true }));\n}\n\n/** Upload a source archive; returns the control plane's id for it. */\nexport async function uploadRebuildSource(url: string, token: string, projectId: string, tarPath: string): Promise<string> {\n const bytes = fs.readFileSync(tarPath);\n const res = await fetch(`${url}/api/functions/deploy/source/upload?projectId=${encodeURIComponent(projectId)}`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/gzip\",\n \"User-Agent\": cliUserAgent()\n },\n body: bytes\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`the upload was refused (${res.status}): ${body || res.statusText}`);\n }\n const data: unknown = await res.json();\n const sourceId = typeof data === \"object\" && data !== null && \"sourceId\" in data ? data.sourceId : undefined;\n if (typeof sourceId !== \"string\" || !/^[0-9a-f]{32}$/i.test(sourceId)) {\n throw new Error(\"the control plane did not return a source id\");\n }\n return sourceId;\n}\n\n/** The env files Vite reads for a production build, lowest precedence first. */\nconst PRODUCTION_ENV_FILES = [\".env\", \".env.local\", \".env.production\", \".env.production.local\"];\n\n/**\n * The `VITE_*` values a rebuild of this project's frontend needs.\n *\n * The `.env` files are never uploaded, so the values a static app is built with\n * have to travel separately — and only the `VITE_*` ones, which Vite inlines\n * into the client bundle and are public by construction. Nothing else is read.\n *\n * Read the way Vite reads them for `vite build`: `.env`, `.env.local`,\n * `.env.production`, `.env.production.local`, later winning — from the project\n * root, then from each static app's own `root`, which is where its Vite config\n * usually points. `process.env` wins over every file, as it does in Vite.\n *\n * `VITE_API_URL` is the one exception, taken from `process.env` only.\n * `staticBuildEnv` sets it to `process.env.VITE_API_URL ?? \"\"` for every\n * static build, so a value in a `.env` file never reaches a deployed bundle —\n * it is the `http://localhost:3001` of local development. Sending it would make\n * the rebuild bake in exactly the address the local build refuses to.\n */\nexport function collectBuildEnv(\n projectRoot: string,\n appRoots: string[],\n env: NodeJS.ProcessEnv = process.env\n): Record<string, string> {\n const collected: Record<string, string> = {};\n const seen = new Set<string>();\n for (const dir of [projectRoot, ...appRoots.map(root => path.resolve(projectRoot, root))]) {\n const resolved = path.resolve(dir);\n if (seen.has(resolved) || !fs.existsSync(resolved)) continue;\n seen.add(resolved);\n for (const name of PRODUCTION_ENV_FILES) {\n let parsed: Record<string, string>;\n try {\n parsed = dotenv.parse(fs.readFileSync(path.join(resolved, name), \"utf8\"));\n } catch {\n continue;\n }\n for (const [key, value] of Object.entries(parsed)) {\n if (key.startsWith(\"VITE_\")) collected[key] = value;\n }\n }\n }\n delete collected.VITE_API_URL;\n for (const [key, value] of Object.entries(env)) {\n if (key.startsWith(\"VITE_\") && value !== undefined) collected[key] = value;\n }\n return collected;\n}\n\n/** The `root` of every static app a manifest declares, in declaration order. */\nexport function staticAppRoots(manifest: RebaseProjectManifest | undefined): string[] {\n if (!manifest) return [];\n const roots: string[] = [];\n for (const app of Object.values(manifest.apps)) {\n if (app.type === \"static\" && typeof app.root === \"string\" && app.root !== \"\") roots.push(app.root);\n }\n return roots;\n}\n\n/** What the deploy trigger carries about an uploaded source. */\nexport interface RebuildSource {\n sourceId: string;\n projectPath: string;\n buildEnv: Record<string, string>;\n}\n\n/** The steps, injectable so a test can fail any one of them. */\nexport interface RebuildSourceSteps {\n list: (projectRoot: string) => SourceListing;\n pack: (listing: SourceListing, outPath: string) => Promise<void>;\n upload: (url: string, token: string, projectId: string, tarPath: string) => Promise<string>;\n}\n\nconst DEFAULT_STEPS: RebuildSourceSteps = {\n list: projectRoot => listSourceFiles(projectRoot),\n pack: packSource,\n upload: uploadRebuildSource\n};\n\n/**\n * List, pack and upload the project's source. Never throws.\n *\n * Returns what the trigger should carry, or null — after a warning saying why\n * and what it costs — when the source could not be sent. The caller deploys\n * either way.\n */\nexport async function prepareRebuildSource(opts: {\n projectRoot: string;\n url: string;\n /** The access token, read when the upload is sent rather than before the packing. */\n token: () => Promise<string>;\n projectId: string;\n manifest?: RebaseProjectManifest;\n progress: (line: string) => void;\n warn: (message: string, hint?: string) => void;\n steps?: Partial<RebuildSourceSteps>;\n maxBytes?: number;\n}): Promise<RebuildSource | null> {\n const steps = { ...DEFAULT_STEPS, ...opts.steps };\n const maxBytes = opts.maxBytes ?? MAX_SOURCE_UPLOAD_BYTES;\n const cost = \"Platform upgrades will not rebuild this project until a later deploy uploads its source.\";\n\n try {\n // A directory of this run's own: see `withTempArchive`.\n return await withTempArchive(\"rebase-rebuild-src\", async (tarPath) => {\n const listing = steps.list(opts.projectRoot);\n await steps.pack(listing, tarPath);\n const size = fs.statSync(tarPath).size;\n const mb = (bytes: number): string => (bytes / 1024 / 1024).toFixed(1);\n if (size > maxBytes) {\n opts.warn(\n `The project source is ${mb(size)} MB compressed, over the ${Math.round(maxBytes / 1024 / 1024)} MB ` +\n `upload limit, so it was not uploaded. ${cost}`,\n listing.fromGit\n ? \"Stop tracking large assets and build output in git, or pass --no-source to skip it on purpose.\"\n : \"Initialise a git repository with a .gitignore to choose what is source, or pass --no-source.\"\n );\n return null;\n }\n opts.progress(` Uploading source (${listing.files.length} files, ${mb(size)} MB)...`);\n const sourceId = await steps.upload(opts.url, await opts.token(), opts.projectId, tarPath);\n return {\n sourceId,\n projectPath: listing.projectPath,\n buildEnv: collectBuildEnv(opts.projectRoot, staticAppRoots(opts.manifest))\n };\n });\n } catch (err) {\n opts.warn(\n `The project source was not uploaded: ${err instanceof Error ? err.message : String(err)}. ${cost}`,\n \"The deploy continues with the bundle alone.\"\n );\n return null;\n }\n}\n","/**\n * Preview deployments: `rebase cloud deploy --preview`, and `rebase cloud\n * previews` to list and delete them.\n *\n * A preview is a build served on an address of its own —\n * `https://<project>--<name>.rebase.website` — while production keeps serving\n * whatever it served before. It exists because the only way to see a change on\n * the real platform was to ship it to the people using the app.\n *\n * ## Why previews have their own function\n *\n * A preview is triggered through `previews`, never through `deploy` with a flag\n * on it. The point of a preview is that production is untouched, and a flag is\n * something an older control plane does not know about: `deploy` would ignore\n * it and ship the build to production — the one outcome this command exists to\n * prevent. A control plane without previews answers an unknown function with a\n * 404 instead, and nothing deploys anywhere. So the refusal is a property of the\n * route, not of every control plane remembering to check a field.\n *\n * The bundle still goes up through the deploy function's bundle upload. Storing\n * an archive deploys nothing; the trigger is what decides where it runs.\n *\n * The control plane's half — the workload, the host, the database a preview\n * backend gets, expiry — is described in `docs/preview-deployments.md`.\n */\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n parseCloudArgs,\n emit,\n fail,\n reportError,\n requireKnownAction,\n confirmDestructive,\n success,\n type CloudClient\n} from \"./context\";\nimport { isMissingRoute } from \"./cron\";\nimport { cliUserAgent } from \"../../utils/version\";\n\n/** The control-plane function that creates, lists and deletes previews. */\nexport const PREVIEWS_FUNCTION = \"previews\";\n\n/**\n * The collection a preview's deployment row lives in.\n *\n * Not `deployments`. Every reader of that collection — `cloud status`, `cloud\n * logs`, rollback, the console's history, and every CLI already installed —\n * takes its newest row to be what production runs. A preview row there would be\n * reported as production by all of them, including the versions nobody can\n * update any more.\n */\nexport const PREVIEW_DEPLOYMENTS_COLLECTION = \"preview-deployments\";\n\n/** Longest preview name: what leaves the host inside one 63-character DNS label. */\nexport const MAX_PREVIEW_NAME_LENGTH = 24;\n\n/**\n * A preview name as typed, checked and lowercased — or a refusal.\n *\n * It becomes part of a hostname, `<project>--<name>`, so it is held to a DNS\n * label's alphabet. A double hyphen is refused because the host is split on\n * it: a name holding one could never be told apart from the project's own.\n */\nexport function normalizePreviewName(raw: string): string {\n const name = raw.trim().toLowerCase();\n const usage = (why: string): never => fail(\n `\"${raw}\" cannot name a preview: ${why}.`,\n `Use lowercase letters, digits and single hyphens, up to ${MAX_PREVIEW_NAME_LENGTH} characters — a branch name such as \\`new-quiz\\`.`,\n \"usage\"\n );\n if (name === \"\") usage(\"it is empty\");\n if (name.length > MAX_PREVIEW_NAME_LENGTH) usage(`it is longer than ${MAX_PREVIEW_NAME_LENGTH} characters`);\n if (!/^[a-z0-9-]+$/.test(name)) usage(\"it holds a character a hostname cannot\");\n if (name.startsWith(\"-\") || name.endsWith(\"-\")) usage(\"it starts or ends with a hyphen\");\n if (name.includes(\"--\")) usage(\"`--` is what separates it from the project's name in the address\");\n return name;\n}\n\n/** Which backend a preview's pages talk to. */\nexport type PreviewBackend = \"preview\" | \"production\";\n\n/** A preview as the control plane describes it. */\nexport interface Preview {\n name: string;\n /** `https://shop--new-quiz.rebase.website`. */\n url: string;\n /** The app it serves: a static app's name, or the backend. */\n app: string | null;\n /**\n * `preview` when the preview runs a backend of its own, with its own\n * database; `production` when it is only files, calling the production API.\n */\n backend: PreviewBackend | null;\n status: string | null;\n /** Why it is in its status, as the control plane wrote it — set for `paused` (its database outgrew the preview limit). */\n statusMessage: string | null;\n /** The deployment that built it, in {@link PREVIEW_DEPLOYMENTS_COLLECTION}. */\n deploymentId: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n /** When the control plane deletes it on its own, unless it is deployed again. */\n expiresAt: string | null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction text(row: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const value = row[key];\n if (typeof value === \"string\" && value.trim() !== \"\") return value.trim();\n if (typeof value === \"number\") return String(value);\n }\n return null;\n}\n\n/**\n * One preview out of an answer, read defensively — or null when it names no\n * address, which is the one field a preview cannot be reported without.\n */\nexport function previewFrom(value: unknown): Preview | null {\n if (!isRecord(value)) return null;\n const name = text(value, \"name\");\n const url = text(value, \"url\");\n if (!name || !url) return null;\n const backend = text(value, \"backend\");\n return {\n name,\n url: /^https?:\\/\\//.test(url) ? url : `https://${url}`,\n app: text(value, \"app\"),\n backend: backend === \"preview\" || backend === \"production\" ? backend : null,\n status: text(value, \"status\"),\n statusMessage: text(value, \"statusMessage\", \"status_message\"),\n deploymentId: text(value, \"deploymentId\", \"deployment_id\"),\n createdAt: text(value, \"createdAt\", \"created_at\"),\n updatedAt: text(value, \"updatedAt\", \"updated_at\"),\n expiresAt: text(value, \"expiresAt\", \"expires_at\")\n };\n}\n\n/**\n * Whether a refusal means \"this control plane has no previews\" — and not, say,\n * \"no such preview\".\n *\n * A control plane answers a function it does not serve with a 404 coded\n * `FUNCTION_NOT_FOUND`; one from before that envelope, with a bare `Not Found`\n * or `No route for …`. Either is a missing route.\n */\nexport function isPreviewsUnavailable(e: unknown): boolean {\n const err = e as { status?: number; message?: string; code?: string };\n return err?.status === 404 && (err.code === \"FUNCTION_NOT_FOUND\" || isMissingRoute(err.message));\n}\n\n/** Turn \"this control plane has no previews\" into a refusal that says so. */\nfunction previewsUnavailable(e: unknown): void {\n if (isPreviewsUnavailable(e)) {\n fail(\n \"This control plane does not serve preview deployments yet. Nothing was deployed.\",\n \"Production is untouched. Deploy without --preview to ship to production.\",\n \"previews_unavailable\"\n );\n }\n}\n\n/**\n * The intake code a control plane refuses a static app's own preview with when\n * nothing on it serves static sites by themselves (no front door). Rebase Cloud\n * is one, today: every host is served by the project's own pod.\n */\nexport const PREVIEW_STATIC_UNSERVED = \"PREVIEW_STATIC_UNSERVED\";\n\nfunction intakeCodeOf(e: unknown): string | undefined {\n if (!isRecord(e) || !isRecord(e.details)) return undefined;\n return typeof e.details.intakeCode === \"string\" ? e.details.intakeCode : undefined;\n}\n\n/**\n * Turn \"this cloud cannot serve a static app on its own\" into a refusal that\n * says what to do instead — which depends on whether the project has a\n * backend to fold the app into, so both ways are named.\n */\nfunction staticPreviewUnserved(e: unknown): void {\n if (intakeCodeOf(e) !== PREVIEW_STATIC_UNSERVED) return;\n fail(\n \"Previews of a static app on its own are not available on this cloud yet: nothing here serves a static site by itself. \"\n + \"Nothing was published, and production is untouched.\",\n \"With a managed backend in rebase.json, `rebase cloud deploy --preview` previews it with its static apps folded in, \"\n + \"this one included. Without one, deploy the app to production with `rebase cloud deploy <app>`.\",\n PREVIEW_STATIC_UNSERVED\n );\n}\n\n/** What the `previews` trigger answers. */\nexport interface PreviewTrigger {\n deploymentId: string;\n preview: Preview;\n}\n\n/**\n * Ask the control plane to build a preview from an uploaded bundle.\n *\n * The body is a bundle deploy's, plus `preview`; see `bundleDeployBody`. An\n * answer without a preview address is refused rather than followed: whatever\n * it built, this command cannot say where, and \"it is somewhere\" is not a\n * result.\n */\nexport async function triggerPreview(\n client: CloudClient,\n projectId: string,\n body: Record<string, unknown>,\n refusal: (e: unknown) => void\n): Promise<PreviewTrigger> {\n let res: unknown;\n try {\n res = await client.functions.invoke<unknown>(PREVIEWS_FUNCTION, body, { method: \"POST\", path: projectId });\n } catch (e) {\n previewsUnavailable(e);\n staticPreviewUnserved(e);\n refusal(e);\n reportError(e, \"Preview deploy failed to start\");\n }\n const deployment = isRecord(res) && isRecord(res.deployment) ? res.deployment : undefined;\n const deploymentId = deployment ? text(deployment, \"id\") : null;\n const preview = isRecord(res) ? previewFrom(res.preview) : null;\n if (!deploymentId || !preview) {\n fail(\n \"The control plane started a preview but did not say where it will be served.\",\n \"Run `rebase cloud previews` to find it.\",\n \"invalid_response\"\n );\n }\n return { deploymentId, preview: { ...preview, deploymentId: preview.deploymentId ?? deploymentId } };\n}\n\n/** The lines a finished preview deploy prints under its verdict. */\nexport function previewLines(preview: Preview): string[] {\n const lines = [`Preview ${chalk.bold(preview.name)}: ${chalk.cyan(preview.url)}`];\n if (preview.backend === \"production\") {\n lines.push(chalk.gray(\"Its pages call the production backend; only the files are a preview.\"));\n } else if (preview.backend === \"preview\") {\n lines.push(chalk.gray(\"It runs its own backend, on a database of its own — not production's data.\"));\n }\n lines.push(chalk.gray(\"Production is unchanged.\"));\n if (preview.expiresAt) lines.push(chalk.gray(`Expires ${preview.expiresAt} unless deployed again.`));\n return lines;\n}\n\n/** Where the docs state what a backend preview costs. */\nexport const PREVIEW_PRICING_DOCS = \"https://rebase.pro/docs/deployment/cloud/#preview-a-change\";\n\n/** The billing rule in words: what is printed when the control plane cannot put a number on it. */\nexport const PREVIEW_PRICING_RULE =\n \"A backend preview is billed like one app unit at the default size, at your app's rate for its region and capacity, \"\n + \"prorated for as long as it exists.\";\n\n/** What a backend preview costs, as the control plane quotes it. */\nexport interface PreviewCost {\n /** €/month one backend preview adds to the project's quote; null when it could not be priced. */\n perPreviewMonthlyEur: number | null;\n /** Backend previews the project runs, this one included; null when unknown. */\n backendPreviews: number | null;\n /** €/month all of them add together; null when unknown. */\n previewsMonthlyEur: number | null;\n /** The rule the numbers come from, in words. */\n rule: string;\n docs: string;\n}\n\ninterface QuoteAnswer {\n totalEur: number;\n backendPreviews?: number;\n}\n\nfunction quoteAnswerFrom(value: unknown): QuoteAnswer | null {\n if (!isRecord(value) || typeof value.totalEur !== \"number\" || !Number.isFinite(value.totalEur)) return null;\n return {\n totalEur: value.totalEur,\n backendPreviews: typeof value.backendPreviews === \"number\" ? value.backendPreviews : undefined\n };\n}\n\nconst cents = (eur: number) => Math.round(eur * 100) / 100;\n\n/**\n * What a backend preview costs, in the control plane's own numbers.\n *\n * No price is written down here: the control plane quotes the project's dials\n * with and without backend previews (`pricing/quote` with `backendPreviews`,\n * the call the console's quote makes) and the difference is what they add —\n * which follows the rate card, the app's region and its capacity class as\n * they change. One batched call, best-effort: a control plane that does not\n * price previews (its answer does not echo the count it was sent) or cannot be\n * asked leaves the numbers null, and the rule and the docs carry the answer.\n *\n * The quote is asked with no credential. The route is public — it prices a\n * hypothetical and reads nobody's data — and an access token would be refused\n * on it, holding no `functions:invoke:pricing`: no token capability names it,\n * and none needs to.\n */\nexport async function previewCost(client: CloudClient, url: string, projectId: string): Promise<PreviewCost> {\n const cost: PreviewCost = {\n perPreviewMonthlyEur: null,\n backendPreviews: null,\n previewsMonthlyEur: null,\n rule: PREVIEW_PRICING_RULE,\n docs: PREVIEW_PRICING_DOCS\n };\n let project: Record<string, unknown> | undefined;\n try {\n project = (await client.data.collection(\"projects\").findById(projectId)) as Record<string, unknown> | undefined;\n } catch {\n return cost;\n }\n if (!isRecord(project)) return cost;\n\n try {\n const res = await client.functions.invoke<unknown>(PREVIEWS_FUNCTION, undefined, { method: \"GET\", path: projectId });\n const rows = isRecord(res) && Array.isArray(res.previews) ? res.previews : undefined;\n if (rows) {\n // At least this one, should the list trail the trigger.\n cost.backendPreviews = Math.max(1, rows.map(previewFrom).filter(p => p !== null && p.backend !== \"production\").length);\n }\n } catch {\n // The count is a detail; the price of one preview does not need it.\n }\n\n const counts = [0, 1];\n if (cost.backendPreviews !== null && cost.backendPreviews > 1) counts.push(cost.backendPreviews);\n let quotes: Array<QuoteAnswer | null>;\n try {\n const res = await fetch(`${url}/api/functions/pricing/quote`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"User-Agent\": cliUserAgent() },\n body: JSON.stringify(counts.map(backendPreviews => ({ ...project, backendPreviews })))\n });\n if (!res.ok) return cost;\n const body: unknown = await res.json();\n quotes = isRecord(body) && Array.isArray(body.quotes) ? body.quotes.map(quoteAnswerFrom) : [];\n } catch {\n return cost;\n }\n const [none, one, all] = quotes;\n // A control plane that prices no previews answers the same total for both\n // and echoes no count: a €0.00 from it would be a guess, not a quote.\n if (!none || !one || one.backendPreviews !== 1) return cost;\n cost.perPreviewMonthlyEur = cents(one.totalEur - none.totalEur);\n if (cost.backendPreviews !== null && cost.backendPreviews <= 1) {\n cost.previewsMonthlyEur = cost.backendPreviews === 1 ? cost.perPreviewMonthlyEur : 0;\n } else if (all && all.backendPreviews !== undefined) {\n cost.backendPreviews = all.backendPreviews;\n cost.previewsMonthlyEur = cents(all.totalEur - none.totalEur);\n }\n return cost;\n}\n\n/** The line a preview deploy prints about its cost. */\nexport function previewCostLines(cost: PreviewCost, previewName: string): string[] {\n const stop = `\\`rebase cloud previews delete ${previewName}\\` stops it.`;\n if (cost.perPreviewMonthlyEur === null) {\n return [`${cost.rule} ${stop}`, `See ${cost.docs}`];\n }\n const lines = [\n `Billed while it exists: €${cost.perPreviewMonthlyEur.toFixed(2)}/month, prorated — the control plane's quote for one backend preview of this project. ${stop}`\n ];\n if (cost.backendPreviews !== null && cost.backendPreviews > 1 && cost.previewsMonthlyEur !== null) {\n lines.push(`The project runs ${cost.backendPreviews} backend previews: €${cost.previewsMonthlyEur.toFixed(2)}/month together.`);\n }\n return lines;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n previews list\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `previews list` parses — the help page lists exactly these. */\nexport const PREVIEWS_LIST_FLAGS = {};\n\nasync function listCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({\n spec: PREVIEWS_LIST_FLAGS,\n rawArgs,\n commandWords: 2, // cloud previews\n command: \"cloud previews list\",\n maxPositionals: 1 // the `list` action word, when written out\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: unknown;\n try {\n res = await client.functions.invoke<unknown>(PREVIEWS_FUNCTION, undefined, { method: \"GET\", path: projectId });\n } catch (e) {\n previewsUnavailable(e);\n reportError(e, \"Failed to list previews\");\n }\n const rows = isRecord(res) && Array.isArray(res.previews) ? res.previews : [];\n const previews = rows.map(previewFrom).filter((p): p is Preview => p !== null);\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔍 Previews — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (previews.length === 0) {\n console.log(chalk.gray(\" No previews. Make one with `rebase cloud deploy --preview`.\"));\n console.log(\"\");\n return;\n }\n const nameWidth = Math.max(4, ...previews.map(p => p.name.length));\n for (const p of previews) {\n const tags = [p.app, p.backend ? `${p.backend} backend` : null, p.status, p.expiresAt ? `expires ${p.expiresAt}` : null]\n .filter(Boolean)\n .join(\" · \");\n console.log(` ${chalk.bold(p.name.padEnd(nameWidth))} ${chalk.cyan(p.url)}`);\n if (tags) console.log(` ${\" \".repeat(nameWidth)} ${chalk.gray(tags)}`);\n if (p.statusMessage) console.log(` ${\" \".repeat(nameWidth)} ${chalk.yellow(p.statusMessage)}`);\n }\n console.log(\"\");\n },\n { previews }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n previews delete <name>\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `previews delete` parses, beyond the global `--yes`. */\nexport const PREVIEWS_DELETE_FLAGS = {};\n\nasync function deleteCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parseCloudArgs({\n spec: PREVIEWS_DELETE_FLAGS,\n rawArgs,\n commandWords: 3, // cloud previews delete\n command: \"cloud previews delete\",\n maxPositionals: 1\n });\n if (!positionals[0]) {\n fail(\"Name the preview: `rebase cloud previews delete <name>`.\", \"`rebase cloud previews` lists them.\", \"usage\");\n }\n const name = normalizePreviewName(positionals[0]);\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n await confirmDestructive({\n yes: flags[\"--yes\"] === true,\n prompt: `Delete preview \"${name}\"? Its address stops answering, and a preview backend's database is dropped.`\n });\n\n try {\n await client.functions.invoke<unknown>(PREVIEWS_FUNCTION, undefined, {\n method: \"DELETE\",\n path: `${projectId}/${encodeURIComponent(name)}`\n });\n } catch (e) {\n previewsUnavailable(e);\n const err = e as { status?: number };\n if (err?.status === 404) {\n fail(`No preview named \"${name}\" on this project.`, \"`rebase cloud previews` lists them.\", \"not_found\");\n }\n reportError(e, \"Failed to delete the preview\");\n }\n success(`Deleted preview ${chalk.bold(name)}. Production is unchanged.`);\n emit(() => console.log(\"\"), { success: true, deleted: name });\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\nconst PREVIEWS_ACTIONS = [\"list\", \"delete\", \"rm\"] as const;\n\nexport async function previewsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n requireKnownAction(\"previews\", action, PREVIEWS_ACTIONS);\n if (action === \"delete\" || action === \"rm\") {\n await deleteCommand(rawArgs);\n return;\n }\n await listCommand(rawArgs);\n}\n","/**\n * `rebase cloud logs --runtime`: what the running app prints, once or followed.\n *\n * The control plane's `runtime-logs` route reads every pod behind the project\n * (or behind one backend preview, with `?preview=`) and answers a poll, not a\n * stream: its SDK transport buffers the whole body, so there is nothing to hold\n * open. A follow is therefore a loop of polls, each asking only for what came\n * after the newest line already printed. Everything below is about making that\n * loop print each line exactly once, survive what happens to pods while it\n * runs, and stop cleanly.\n *\n * - **Cursor.** The next poll starts from the newest line's own timestamp —\n * the kubelet's clock, never ours, so a skewed laptop cannot open a gap. It\n * asks from one millisecond earlier, because the control plane compares at\n * millisecond precision while Kubernetes writes nanoseconds: two lines in the\n * same millisecond would otherwise lose the second. The lines that overlap\n * are dropped here by identity ({@link FollowCursor}).\n * - **Restarts.** A container that crashes and comes back between two polls\n * starts a fresh log; its last lines, usually the reason, are only in the\n * previous instance. The route reports each pod's restart count; when it\n * rises, the follower reads that instance once and prints its tail.\n * - **Pods coming and going** (a rolling deploy, a scale-down) are announced,\n * and \"no pods\" is a state to wait through, not an error.\n * - **Network blips** back off and retry from the same cursor, so nothing in\n * between is lost while the pod keeps its log. A refusal (401, 403, 404)\n * ends the follow — it will say the same next time.\n * - **Ctrl-C** ends the follow and exits 0: stopping a tail is how it is used.\n */\nimport chalk from \"chalk\";\nimport { fail, type CloudClient } from \"./context\";\nimport { isErrorLine, parseLogLine, parseSince, SERVER_MAX_TAIL_LINES, type RuntimeLogsPod } from \"./debug\";\n\n/** The control-plane function this module reads. */\nexport const RUNTIME_LOGS_FUNCTION = \"runtime-logs\";\n\n/** How often a follow polls. The console polls at the same rate. */\nexport const FOLLOW_INTERVAL_MS = 2_000;\n/** The longest a follow waits between retries of a failed poll. */\nexport const MAX_BACKOFF_MS = 30_000;\n/** A poll with no answer by then is treated as a dropped connection. */\nexport const POLL_TIMEOUT_MS = 30_000;\n\n/** What one request asks the route for. `sinceTime` and `sinceSeconds` are exclusive. */\nexport interface RuntimeLogsQuery {\n sinceSeconds?: number;\n /** RFC3339. */\n sinceTime?: string;\n tailLines?: number;\n previous?: boolean;\n /** One backend preview's pod instead of production's. */\n preview?: string;\n}\n\nexport interface RuntimeLogsPodState extends RuntimeLogsPod {\n /** The container's restart count. Absent from control planes before it was reported; null when unknown. */\n restarts?: number | null;\n}\n\n/** The route's answer, read defensively: every field may be missing on an older control plane. */\nexport interface RuntimeLogsPage {\n logs?: string;\n pods?: RuntimeLogsPodState[];\n ordering?: string;\n truncated?: boolean;\n previous?: boolean;\n /** Echoed by control planes that understand `?preview=`. */\n preview?: string | null;\n nextSinceTime?: string | null;\n state?: \"ok\" | \"no_pods\" | \"error\" | string;\n message?: string | null;\n}\n\n/** The request path for a query: `<projectId>?…`. Timestamps are always asked for — the cursor is built from them. */\nexport function runtimeLogsPath(projectId: string, q: RuntimeLogsQuery): string {\n const params = new URLSearchParams();\n if (q.sinceTime !== undefined) params.set(\"sinceTime\", q.sinceTime);\n else if (q.sinceSeconds !== undefined) params.set(\"sinceSeconds\", String(q.sinceSeconds));\n if (q.tailLines !== undefined) params.set(\"tailLines\", String(q.tailLines));\n if (q.previous) params.set(\"previous\", \"true\");\n if (q.preview !== undefined) params.set(\"preview\", q.preview);\n params.set(\"timestamps\", \"true\");\n return `${projectId}?${params.toString()}`;\n}\n\n/**\n * Read one page, refusing to pass off production's log as a preview's.\n *\n * A control plane from before `?preview=` ignores the parameter and answers with\n * production's pods. It does not echo `preview`, and that silence is the tell.\n */\nexport async function fetchRuntimeLogsPage(client: CloudClient, projectId: string, q: RuntimeLogsQuery): Promise<RuntimeLogsPage> {\n const page = await client.functions.invoke<RuntimeLogsPage>(RUNTIME_LOGS_FUNCTION, undefined, {\n method: \"GET\",\n path: runtimeLogsPath(projectId, q)\n });\n if (q.preview !== undefined && page?.preview !== q.preview) {\n fail(\n \"This control plane cannot read a preview's runtime log yet; it would have answered with production's.\",\n `\\`rebase cloud logs --preview ${q.preview}\\` (without --runtime) shows the preview's build log.`,\n \"preview_runtime_unavailable\"\n );\n }\n return page ?? {};\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Flags\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * `--since`: a duration (`30s`, `5m`, `1h`, `2d`) or an RFC3339 instant.\n * Returns null for anything else.\n */\nexport function parseSinceFlag(input: string): { sinceSeconds: number } | { sinceTime: string } | null {\n const seconds = parseSince(input);\n if (seconds !== null) return { sinceSeconds: seconds };\n // An instant needs at least a date and a time; `Date.parse` alone would\n // take \"5\" or \"May\" and invent one.\n if (/^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}/.test(input.trim())) {\n const ms = Date.parse(input.trim());\n if (!Number.isNaN(ms)) return { sinceTime: new Date(ms).toISOString() };\n }\n return null;\n}\n\n/** Severity, as the console's log explorer reads it. */\nexport type LogLevel = \"error\" | \"warn\" | \"info\" | \"debug\" | \"unknown\";\n\n/** `--level` names a floor: `warn` keeps warnings and errors. */\nexport const LEVEL_FLOOR: Record<Exclude<LogLevel, \"unknown\">, number> = { error: 0, warn: 1, info: 2, debug: 3 };\n\nconst LEVEL_ALIASES: Record<string, LogLevel> = {\n emerg: \"error\", alert: \"error\", crit: \"error\", critical: \"error\",\n fatal: \"error\", error: \"error\", err: \"error\", severe: \"error\",\n warn: \"warn\", warning: \"warn\", notice: \"warn\",\n info: \"info\", information: \"info\", log: \"info\", default: \"info\",\n debug: \"debug\", trace: \"debug\", verbose: \"debug\", fine: \"debug\"\n};\nconst LEVEL_KEYS = [\"severity\", \"level\", \"levelname\", \"loglevel\", \"lvl\"];\n/** A level token at the head of an unstructured line: `ERROR`, `[warn]`, `info:`. */\nconst BARE_LEVEL = /^[\\s[(]*([A-Za-z]{4,7})\\b[\\s\\])]*[:-]?\\s/;\n\nfunction normalizeLevel(value: unknown): LogLevel {\n if (typeof value === \"number\") {\n // pino/bunyan: 50+ error, 40 warn, 30 info, below that debug.\n if (value >= 50) return \"error\";\n if (value >= 40) return \"warn\";\n if (value >= 30) return \"info\";\n return \"debug\";\n }\n if (typeof value !== \"string\") return \"unknown\";\n return LEVEL_ALIASES[value.trim().toLowerCase()] ?? \"unknown\";\n}\n\n/**\n * A line's severity: the structured field when the payload is a JSON object\n * (a Rebase backend logs `{\"severity\":\"ERROR\",…}`), else a level token at the\n * head of the line — the console explorer's rules. A line with neither that\n * `cloud debug errors` would flag (`Error:`, `EACCES`, a refusal) counts as an\n * error, because an unstructured stack trace is exactly what `--level error`\n * is run to find.\n */\nexport function lineLevel(text: string): LogLevel {\n const body = text.trim();\n if (body.startsWith(\"{\") && body.endsWith(\"}\")) {\n try {\n const parsed: unknown = JSON.parse(body);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const obj = parsed as Record<string, unknown>;\n const key = LEVEL_KEYS.find((k) => Object.prototype.hasOwnProperty.call(obj, k));\n if (key) {\n const level = normalizeLevel(obj[key]);\n if (level !== \"unknown\") return level;\n }\n }\n } catch {\n // Not JSON after all: read it as text.\n }\n }\n const bare = BARE_LEVEL.exec(body);\n const level = bare ? normalizeLevel(bare[1]) : \"unknown\";\n if (level !== \"unknown\") return level;\n // `TypeError: …`, `UnhandledPromiseRejection…Exception: …` — the head of an\n // unstructured stack trace, which `isErrorLine`'s `\\bError:` misses when\n // the word is part of a class name.\n return isErrorLine(body) || /^\\w*(?:Error|Exception):\\s/.test(body) ? \"error\" : \"unknown\";\n}\n\n/**\n * `--grep`: a case-insensitive substring of the whole line (timestamp and pod\n * included, as in the console), or a regular expression written `/re/flags`.\n */\nexport function grepMatcher(pattern: string): (line: string) => boolean {\n const re = /^\\/(.+)\\/([a-z]*)$/.exec(pattern);\n if (re) {\n let compiled: RegExp;\n try {\n compiled = new RegExp(re[1], re[2].replace(/[gy]/g, \"\"));\n } catch (e) {\n fail(`--grep ${pattern} is not a valid regular expression: ${e instanceof Error ? e.message : String(e)}`, undefined, \"usage\");\n }\n return (line) => compiled.test(line);\n }\n const needle = pattern.toLowerCase();\n return (line) => line.toLowerCase().includes(needle);\n}\n\n/** Read `--level`, refusing anything that is not a level. */\nexport function parseLevelFlag(value: string): Exclude<LogLevel, \"unknown\"> {\n const level = value.trim().toLowerCase();\n if (level === \"error\" || level === \"warn\" || level === \"info\" || level === \"debug\") return level;\n if (level === \"warning\") return \"warn\";\n fail(`--level must be error, warn, info or debug; received \"${value}\".`, undefined, \"usage\");\n}\n\n/** One printed line, parsed. */\nexport interface LogRecord {\n /** The kubelet's RFC3339(Nano) timestamp, or null when the line carried none. */\n ts: string | null;\n pod: string | null;\n text: string;\n /** The line exactly as the control plane rendered it. */\n raw: string;\n}\n\nexport function parseRecords(logs: string | undefined): LogRecord[] {\n if (!logs) return [];\n const out: LogRecord[] = [];\n for (const raw of logs.split(\"\\n\")) {\n if (raw === \"\") continue;\n const { ts, pod, text } = parseLogLine(raw);\n out.push({ ts, pod, text, raw });\n }\n return out;\n}\n\n/** The lines `--grep` and `--level` keep. Both unset keeps everything. */\nexport function recordFilter(opts: { grep?: string; level?: Exclude<LogLevel, \"unknown\"> }): (rec: LogRecord) => boolean {\n const grep = opts.grep !== undefined && opts.grep !== \"\" ? grepMatcher(opts.grep) : null;\n const floor = opts.level !== undefined ? LEVEL_FLOOR[opts.level] : null;\n return (rec) => {\n if (grep && !grep(rec.raw)) return false;\n if (floor !== null) {\n const level = lineLevel(rec.text);\n if (level === \"unknown\" || LEVEL_FLOOR[level] > floor) return false;\n }\n return true;\n };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Cursor\n ═══════════════════════════════════════════════════════════════ */\n\nfunction msOf(ts: string | null): number | null {\n if (ts === null) return null;\n const ms = Date.parse(ts);\n return Number.isNaN(ms) ? null : ms;\n}\n\n/**\n * The newest line printed so far, and which lines share its millisecond.\n *\n * Polls overlap by design (see the module docs), so a line can arrive twice.\n * A line older than the cursor was printed by an earlier poll — every pod is\n * read at the same instant, so nothing older can still be on its way. A line\n * in the cursor's own millisecond was printed if it is one of the lines\n * remembered there. A line with no timestamp cannot be placed and is printed:\n * a duplicate is a kinder failure than a lost line.\n */\nexport class FollowCursor {\n private ms: number | null = null;\n private boundary = new Set<string>();\n\n /** Keep the lines of one page that have not been printed, and move the cursor past them. */\n admit(records: LogRecord[]): LogRecord[] {\n const prevMs = this.ms;\n const prevBoundary = this.boundary;\n const fresh = records.filter((r) => {\n const ms = msOf(r.ts);\n if (ms === null || prevMs === null) return true;\n if (ms < prevMs) return false;\n return !(ms === prevMs && prevBoundary.has(r.raw));\n });\n let newest = prevMs;\n for (const r of fresh) {\n const ms = msOf(r.ts);\n if (ms !== null && (newest === null || ms > newest)) newest = ms;\n }\n if (newest !== null && newest !== prevMs) {\n this.boundary = new Set(fresh.filter((r) => msOf(r.ts) === newest).map((r) => r.raw));\n } else if (newest !== null) {\n for (const r of fresh) if (msOf(r.ts) === newest) this.boundary.add(r.raw);\n }\n this.ms = newest;\n return fresh;\n }\n\n /** Where the next poll starts: one millisecond before the newest line, or null before any. */\n sinceTime(): string | null {\n return this.ms === null ? null : new Date(this.ms - 1).toISOString();\n }\n}\n\n/** Order lines by timestamp, keeping each pod's order among equals (`sort` is stable). */\nfunction byTime(records: LogRecord[]): LogRecord[] {\n if (!records.every((r) => msOf(r.ts) !== null)) return records;\n return [...records].sort((a, b) => (msOf(a.ts) as number) - (msOf(b.ts) as number));\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Follow\n ═══════════════════════════════════════════════════════════════ */\n\n/** Something a follower says besides a log line. */\nexport type FollowEvent =\n | { event: \"no_pods\"; message: string }\n | { event: \"pod_added\"; pod: string }\n | { event: \"pod_removed\"; pod: string }\n | { event: \"pod_state\"; pod: string; state: string; message: string | null }\n | { event: \"pod_restarted\"; pod: string; restarts: number; missed: number }\n | { event: \"truncated\"; message: string }\n | { event: \"server_error\"; message: string }\n | { event: \"reconnecting\"; message: string; retryInMs: number }\n | { event: \"reconnected\" };\n\nexport interface FollowSink {\n line(rec: LogRecord): void;\n event(e: FollowEvent): void;\n}\n\nexport interface FollowDeps {\n fetch(q: RuntimeLogsQuery): Promise<RuntimeLogsPage>;\n /** Resolves after `ms`, or as soon as `signal` aborts. */\n sleep(ms: number, signal: AbortSignal): Promise<void>;\n signal: AbortSignal;\n sink: FollowSink;\n /** A monotonic clock, in milliseconds. */\n now(): number;\n /** Whether a failed poll is worth retrying. */\n isTransient(e: unknown): boolean;\n intervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport interface FollowOptions {\n /** The first poll, as the flags asked for it. */\n initial: RuntimeLogsQuery;\n filter: (rec: LogRecord) => boolean;\n}\n\nclass PollTimeout extends Error {\n constructor(ms: number) {\n super(`no answer within ${Math.round(ms / 1000)}s`);\n }\n}\n\n/** Resolve with `p`, or reject when `ms` passes or `signal` aborts (resolving undefined then). */\nfunction bounded<T>(p: Promise<T>, ms: number, signal: AbortSignal): Promise<T | undefined> {\n return new Promise<T | undefined>((resolve, reject) => {\n const timer = setTimeout(() => reject(new PollTimeout(ms)), ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve(undefined);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n p.then(\n (v) => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", onAbort);\n resolve(v);\n },\n (e: unknown) => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", onAbort);\n reject(e);\n }\n );\n });\n}\n\n/** The delay before retry `attempt` (1-based): 2s, 4s, 8s, 16s, then 30s. */\nexport function backoffMs(attempt: number, base = FOLLOW_INTERVAL_MS): number {\n return Math.min(MAX_BACKOFF_MS, base * 2 ** Math.max(0, attempt - 1));\n}\n\n/**\n * Poll until `deps.signal` aborts. Returns normally then; throws only a\n * failure that is not worth retrying (the caller reports it).\n */\nexport async function followRuntimeLogs(deps: FollowDeps, opts: FollowOptions): Promise<void> {\n const interval = deps.intervalMs ?? FOLLOW_INTERVAL_MS;\n const timeoutMs = deps.pollTimeoutMs ?? POLL_TIMEOUT_MS;\n const { signal, sink } = deps;\n const cursor = new FollowCursor();\n\n /** Pod name → last state and restart count seen. Null until the first answer with pods. */\n let known: Map<string, { state: string; restarts: number | null }> | null = null;\n let waitingForPods = false;\n let failures = 0;\n let lastServerError: string | null = null;\n let first = true;\n /** When the last poll was sent, for the cursor-less window. */\n let lastSentAt: number | null = null;\n\n const nextQuery = (): RuntimeLogsQuery => {\n if (first) return opts.initial;\n const base: RuntimeLogsQuery = {\n // As wide as the route allows: a chatty app writes more than the\n // default 500 lines in two seconds, and the window is only as old\n // as the last line printed anyway.\n tailLines: SERVER_MAX_TAIL_LINES,\n preview: opts.initial.preview\n };\n const since = cursor.sinceTime();\n if (since !== null) return { ...base, sinceTime: since };\n // Nothing timestamped printed yet. Everything up to the last poll was\n // read and was empty, so ask for the time since then — a duration,\n // measured on our clock and applied on the kubelet's, so their skew\n // does not matter. One second more, for the rounding.\n if (lastSentAt !== null) {\n return { ...base, sinceSeconds: Math.max(1, Math.ceil((deps.now() - lastSentAt) / 1000) + 1) };\n }\n return opts.initial;\n };\n\n while (!signal.aborted) {\n const q = nextQuery();\n const sentAt = deps.now();\n let page: RuntimeLogsPage | undefined;\n try {\n page = await bounded(deps.fetch(q), timeoutMs, signal);\n } catch (e) {\n if (!(e instanceof PollTimeout) && !deps.isTransient(e)) throw e;\n failures += 1;\n const retryInMs = backoffMs(failures, interval);\n sink.event({ event: \"reconnecting\", message: e instanceof Error ? e.message : String(e), retryInMs });\n await deps.sleep(retryInMs, signal);\n continue;\n }\n if (signal.aborted || page === undefined) break;\n if (failures > 0) sink.event({ event: \"reconnected\" });\n failures = 0;\n first = false;\n lastSentAt = sentAt;\n\n if (page.state === \"no_pods\") {\n if (!waitingForPods) sink.event({ event: \"no_pods\", message: page.message ?? \"No pods are running for this project.\" });\n waitingForPods = true;\n if (known) for (const pod of known.keys()) sink.event({ event: \"pod_removed\", pod });\n known = new Map();\n await deps.sleep(interval, signal);\n continue;\n }\n if (page.state === \"error\") {\n const message = page.message ?? \"The control plane could not read the logs.\";\n if (message !== lastServerError) sink.event({ event: \"server_error\", message });\n lastServerError = message;\n failures += 1;\n await deps.sleep(backoffMs(failures, interval), signal);\n continue;\n }\n lastServerError = null;\n waitingForPods = false;\n\n const pods = page.pods ?? [];\n const restarted: Array<{ pod: string; restarts: number; missed: number }> = [];\n const next = new Map<string, { state: string; restarts: number | null }>();\n for (const p of pods) {\n const restarts = typeof p.restarts === \"number\" ? p.restarts : null;\n const before = known?.get(p.pod);\n next.set(p.pod, { state: p.state, restarts });\n if (known && !before) sink.event({ event: \"pod_added\", pod: p.pod });\n // A state worth saying out loud: the first time a pod is seen in\n // it, and each time it changes. Never on every poll.\n if ((before?.state ?? \"ok\") !== p.state && p.state !== \"ok\") {\n sink.event({ event: \"pod_state\", pod: p.pod, state: p.state, message: p.message ?? null });\n } else if (before && before.state !== \"ok\" && p.state === \"ok\") {\n sink.event({ event: \"pod_state\", pod: p.pod, state: \"ok\", message: null });\n }\n if (before && before.restarts !== null && restarts !== null && restarts > before.restarts) {\n restarted.push({ pod: p.pod, restarts, missed: restarts - before.restarts - 1 });\n }\n }\n if (known) for (const pod of known.keys()) if (!next.has(pod)) sink.event({ event: \"pod_removed\", pod });\n known = next;\n\n let records = parseRecords(page.logs);\n\n // The instance that died between the two polls: its tail is the\n // reason, and it is only in `previous`. Read over the same window.\n if (restarted.length > 0) {\n for (const r of restarted) sink.event({ event: \"pod_restarted\", ...r });\n try {\n const prev = await bounded(deps.fetch({ ...q, previous: true }), timeoutMs, signal);\n const names = new Set(restarted.map((r) => r.pod));\n const tail = parseRecords(prev?.logs).filter((r) => r.pod !== null && names.has(r.pod));\n records = byTime([...tail, ...records]);\n } catch (e) {\n if (!(e instanceof PollTimeout) && !deps.isTransient(e)) throw e;\n // The live log is still worth printing; the dead instance's\n // tail stays readable with --previous.\n }\n }\n\n for (const rec of cursor.admit(records)) {\n if (opts.filter(rec)) sink.line(rec);\n }\n\n // A follow poll cut short skipped lines: by a byte budget, or — after\n // the first poll, whose tail is what the flags asked for — by the line\n // limit, which only a burst of more than that many lines reaches.\n const tailCut = q !== opts.initial && q.tailLines !== undefined\n && pods.some((p) => p.state === \"ok\" && p.lines >= (q.tailLines as number));\n if (page.truncated || pods.some((p) => p.truncated) || tailCut) {\n sink.event({\n event: \"truncated\",\n message: \"More was written than one poll returns; some lines in this window were skipped.\"\n });\n }\n\n await deps.sleep(interval, signal);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Output\n ═══════════════════════════════════════════════════════════════ */\n\n/** Colour a line by its severity on a terminal; the text itself is never changed. */\nexport function paintLine(rec: LogRecord): string {\n const level = lineLevel(rec.text);\n if (level === \"error\") return chalk.red(rec.raw);\n if (level === \"warn\") return chalk.yellow(rec.raw);\n return rec.raw;\n}\n\n/** The human sentence for an event, or null for one that needs none. */\nexport function describeEvent(e: FollowEvent, opts: { preview?: string } = {}): string | null {\n const previous = opts.preview !== undefined\n ? `rebase cloud logs --runtime --previous --preview ${opts.preview}`\n : \"rebase cloud logs --runtime --previous\";\n switch (e.event) {\n case \"no_pods\":\n return `${e.message} Waiting for one to start…`;\n case \"pod_added\":\n return `Pod ${e.pod} started.`;\n case \"pod_removed\":\n return `Pod ${e.pod} is gone.`;\n case \"pod_state\":\n if (e.state === \"ok\") return `Pod ${e.pod} is running again.`;\n if (e.state === \"not_ready\") {\n return `Pod ${e.pod} is not running${e.message ? ` (${e.message})` : \"\"}. Its crashed instance: \\`${previous}\\`.`;\n }\n return `Pod ${e.pod}: ${e.state}${e.message ? ` — ${e.message}` : \"\"}`;\n case \"pod_restarted\":\n return e.missed > 0\n ? `Pod ${e.pod} restarted ${e.missed + 1} times since the last poll (restart ${e.restarts}); the last instance's final lines follow.`\n : `Pod ${e.pod} restarted (restart ${e.restarts}); the previous instance's final lines follow.`;\n case \"truncated\":\n return e.message;\n case \"server_error\":\n return `The control plane could not read the logs: ${e.message} Retrying…`;\n case \"reconnecting\":\n return `Lost the connection (${e.message}). Retrying in ${Math.round(e.retryInMs / 1000)}s…`;\n case \"reconnected\":\n return \"Reconnected.\";\n }\n}\n","/**\n * A syntax check over a static app's built output, run before it is deployed.\n *\n * Why it exists: a static app's files are served exactly as they are. A project\n * whose \"build\" only copies hand-written `.js` into the output folder (no\n * bundler, so nothing ever parsed them) deployed a file with a syntax error.\n * The deploy succeeded, because nothing on the way checks JavaScript, and the\n * live page died on load. Its developer's fix was to run `node --check` before\n * every deploy. This does the same job, for every file, before anything is\n * uploaded.\n *\n * What is checked:\n * - every `.js`, `.mjs` and `.cjs` file under the output directory;\n * - every inline `<script>` in an `.html`/`.htm` file that a browser would\n * run as JavaScript: no `type`, a JavaScript MIME type, or `module`.\n * JSON, import maps, templates and any other `type` are left alone, and so\n * is a `<script src>`, whose body a browser ignores.\n *\n * Parsing uses acorn rather than `vm.Script`: V8's module parser reports\n * no position, and a check that says \"somewhere in this file\" is not much help.\n *\n * Pure apart from reading the directory, so the deploy decides what a failure\n * means and the tests can drive it with a fixture.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { parse, type Options } from \"acorn\";\n\n/** One syntax error, located the way an editor wants it: 1-based line and column. */\nexport interface StaticSyntaxError {\n /** The file, relative to the directory the caller asked to show paths from. */\n file: string;\n line: number;\n column: number;\n message: string;\n /** The offending source line, trimmed to something printable. */\n excerpt?: string;\n}\n\nexport interface StaticSyntaxReport {\n /** JavaScript files plus inline scripts parsed. */\n checked: number;\n errors: StaticSyntaxError[];\n}\n\n/** How a source is run: a classic script, a module, or unknown (a `.js` file). */\nexport type ScriptKind = \"script\" | \"module\" | \"auto\";\n\nconst SCRIPT_EXTENSIONS = new Set([\".js\", \".mjs\", \".cjs\"]);\nconst HTML_EXTENSIONS = new Set([\".html\", \".htm\"]);\n\n/** The `type` values the HTML spec runs as a classic script. */\nconst CLASSIC_SCRIPT_TYPES = new Set([\n \"\",\n \"text/javascript\",\n \"application/javascript\",\n \"application/ecmascript\",\n \"application/x-ecmascript\",\n \"application/x-javascript\",\n \"text/ecmascript\",\n \"text/javascript1.0\",\n \"text/javascript1.1\",\n \"text/javascript1.2\",\n \"text/javascript1.3\",\n \"text/javascript1.4\",\n \"text/javascript1.5\",\n \"text/jscript\",\n \"text/livescript\",\n \"text/x-ecmascript\",\n \"text/x-javascript\"\n]);\n\ninterface ParseFailure {\n line: number;\n /** 0-based, as acorn reports it. */\n column: number;\n /** Offset into the source, used to pick the more informative of two parses. */\n pos: number;\n message: string;\n}\n\nfunction tryParse(source: string, options: Options): ParseFailure | null {\n try {\n parse(source, options);\n return null;\n } catch (err) {\n if (!(err instanceof SyntaxError)) throw err;\n // acorn's SyntaxError carries `loc` and `pos` beside the message.\n const loc = \"loc\" in err && typeof err.loc === \"object\" && err.loc !== null ? err.loc : undefined;\n const line = loc && \"line\" in loc && typeof loc.line === \"number\" ? loc.line : 1;\n const column = loc && \"column\" in loc && typeof loc.column === \"number\" ? loc.column : 0;\n return {\n line,\n column,\n pos: \"pos\" in err && typeof err.pos === \"number\" ? err.pos : 0,\n // acorn appends \" (line:column)\"; the caller prints its own.\n message: err.message.replace(/\\s*\\(\\d+:\\d+\\)$/, \"\")\n };\n }\n}\n\n/**\n * Parse one source and return its first syntax error, or null.\n *\n * A `.js` file can be loaded either way — `<script src>` runs it as a classic\n * script, `<script type=\"module\">` or an `import` as a module — and each mode\n * rejects code the other accepts (`import` in a script, `with` in a module).\n * So `auto` accepts a source that parses either way, and when neither does,\n * reports the parse that got further: that is the one that tripped over the\n * actual mistake rather than over the choice of mode.\n */\nexport function findSyntaxError(source: string, kind: ScriptKind, cjs = false): ParseFailure | null {\n const base: Options = { ecmaVersion: \"latest\",\nlocations: true,\nallowHashBang: true };\n const asScript = (): ParseFailure | null => tryParse(source, {\n ...base,\n sourceType: \"script\",\n allowReturnOutsideFunction: cjs\n });\n const asModule = (): ParseFailure | null => tryParse(source, { ...base,\nsourceType: \"module\" });\n\n if (kind === \"script\") return asScript();\n if (kind === \"module\") return asModule();\n\n const script = asScript();\n if (!script) return null;\n const module = asModule();\n if (!module) return null;\n return module.pos > script.pos ? module : script;\n}\n\n/** An inline script found in an HTML document, positioned in that document. */\nexport interface InlineScript {\n source: string;\n kind: \"script\" | \"module\";\n /** 1-based line of the script body's first character. */\n line: number;\n /** 0-based column of that character. */\n column: number;\n}\n\nfunction attribute(attrs: string, name: string): string | undefined {\n const match = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s\"'>]+))`, \"i\").exec(attrs);\n if (!match) return undefined;\n return match[1] ?? match[2] ?? match[3] ?? \"\";\n}\n\nfunction hasAttribute(attrs: string, name: string): boolean {\n return new RegExp(`(?:^|\\\\s)${name}(?:\\\\s*=|\\\\s|$)`, \"i\").test(attrs);\n}\n\n/**\n * The inline scripts of an HTML document that a browser would run as\n * JavaScript, each with the position its body starts at.\n *\n * HTML comments are blanked first, keeping every newline, so a commented-out\n * `<script>` is not checked and the line numbers of everything after it are\n * still right.\n */\nexport function inlineScripts(html: string): InlineScript[] {\n const uncommented = html.replace(/<!--[\\s\\S]*?-->/g, (comment) => comment.replace(/[^\\n]/g, \" \"));\n const scripts: InlineScript[] = [];\n const pattern = /<script\\b([^>]*)>([\\s\\S]*?)<\\/script\\s*>/gi;\n for (const match of uncommented.matchAll(pattern)) {\n const attrs = match[1];\n const body = match[2];\n if (hasAttribute(attrs, \"src\")) continue;\n if (body.trim() === \"\") continue;\n\n const type = (attribute(attrs, \"type\") ?? \"\").trim().toLowerCase();\n let kind: InlineScript[\"kind\"];\n if (type === \"module\") kind = \"module\";\n else if (CLASSIC_SCRIPT_TYPES.has(type)) kind = \"script\";\n else continue; // JSON, importmap, a template, or anything else a browser does not run.\n\n const bodyStart = (match.index ?? 0) + match[0].indexOf(\">\") + 1;\n const before = uncommented.slice(0, bodyStart);\n const line = before.split(\"\\n\").length;\n const column = bodyStart - (before.lastIndexOf(\"\\n\") + 1);\n scripts.push({ source: body,\nkind,\nline,\ncolumn });\n }\n return scripts;\n}\n\n/** Markup a server-side template leaves in a script it has not rendered yet. */\nconst TEMPLATE_MARKERS = /\\{\\{|\\{%|<%|<\\?/;\n\nfunction excerptOf(source: string, line: number, column: number): string | undefined {\n const text = source.split(\"\\n\")[line - 1];\n if (text === undefined) return undefined;\n const clean = text.replace(/\\t/g, \" \").replace(/\\r$/, \"\");\n // A minified bundle is one line of megabytes: show the neighbourhood.\n if (clean.length <= 120) return clean.trimEnd();\n const start = Math.max(0, column - 60);\n return `${start > 0 ? \"…\" : \"\"}${clean.slice(start, start + 120)}…`;\n}\n\nfunction walk(dir: string, out: string[]): void {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\") continue;\n walk(full, out);\n } else if (entry.isFile()) {\n out.push(full);\n }\n }\n}\n\n/**\n * Parse every JavaScript file and inline script under `dir`.\n *\n * `displayRoot` is what reported paths are relative to: the project root, so\n * an error reads `web/cloud.js:42:7` and can be opened as written.\n */\nexport function checkStaticSyntax(dir: string, displayRoot: string = dir): StaticSyntaxReport {\n const files: string[] = [];\n walk(dir, files);\n files.sort();\n\n const errors: StaticSyntaxError[] = [];\n let checked = 0;\n for (const file of files) {\n const ext = path.extname(file).toLowerCase();\n const shown = path.relative(displayRoot, file).split(path.sep).join(\"/\");\n\n if (SCRIPT_EXTENSIONS.has(ext)) {\n const source = fs.readFileSync(file, \"utf8\");\n checked++;\n const kind: ScriptKind = ext === \".mjs\" ? \"module\" : ext === \".cjs\" ? \"script\" : \"auto\";\n const failure = findSyntaxError(source, kind, ext === \".cjs\");\n if (failure) {\n errors.push({\n file: shown,\n line: failure.line,\n column: failure.column + 1,\n message: failure.message,\n excerpt: excerptOf(source, failure.line, failure.column)\n });\n }\n } else if (HTML_EXTENSIONS.has(ext)) {\n const html = fs.readFileSync(file, \"utf8\");\n for (const script of inlineScripts(html)) {\n checked++;\n const failure = findSyntaxError(script.source, script.kind);\n if (!failure) continue;\n // An unrendered template is not JavaScript yet; whether it will\n // be is for whatever renders it to say.\n if (TEMPLATE_MARKERS.test(script.source)) continue;\n const line = script.line + failure.line - 1;\n const column = failure.line === 1 ? script.column + failure.column : failure.column;\n errors.push({\n file: shown,\n line,\n column: column + 1,\n message: `${failure.message} (inline <script${script.kind === \"module\" ? \" type=\\\"module\\\"\" : \"\"}>)`,\n excerpt: excerptOf(html, line, column)\n });\n }\n }\n }\n return { checked,\nerrors };\n}\n\n/** The errors as the lines a person reads: `file:line:col message`, then the line itself. */\nexport function formatSyntaxErrors(errors: StaticSyntaxError[], limit = 10): string[] {\n const lines: string[] = [];\n for (const error of errors.slice(0, limit)) {\n lines.push(`${error.file}:${error.line}:${error.column} ${error.message}`);\n if (error.excerpt !== undefined) lines.push(` ${error.line} | ${error.excerpt}`);\n }\n if (errors.length > limit) lines.push(`…and ${errors.length - limit} more`);\n return lines;\n}\n","/**\n * `rebase cloud deploy` and `rebase cloud logs`.\n *\n * `deploy` triggers the control-plane `deploy` function, then tails the build\n * logs from the deployment record until it succeeds or fails. `logs` shows the\n * latest build log, or runtime logs with `--runtime`.\n *\n * There are three deploys behind the one verb, and which one runs depends on the\n * flags: `--bundle` builds and uploads a managed bundle, `--source .` uploads\n * this directory as a build context, and the bare form uploads nothing and asks\n * the control plane to rebuild what it already holds. That last one is the\n * dangerous one — see `planBareDeploy`.\n *\n * `--preview` is the bundle deploy aimed somewhere else: the same build and\n * upload, triggered through the `previews` function so it is served on an\n * address of its own and production is never touched. See `previews.ts`.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { durationBucket, recordEvent } from \"../../telemetry\";\nimport {\n requireClient,\n resolveProjectRef,\n parseCloudArgs,\n colorStatus,\n emit,\n isJsonMode,\n printJson,\n fail,\n freshAccessToken,\n warn,\n reportError,\n resolveTimeoutMs,\n note,\n fetchTenantBaseDomain,\n projectHost,\n type CloudClient,\n billingAccountIdOf\n} from \"./context\";\nimport { latestDeployment, fmtDate } from \"./projects\";\nimport { appKeyPayload, mintMissingAppKey, reportMintedAppKey } from \"./init\";\nimport {\n readBundleManifest,\n packBundleForUpload,\n uploadBundle,\n bundleDeployBody,\n bundleCommit,\n declaredAppsFrom,\n deployHostsFrom,\n pendingHostNotices,\n type DeployHost\n} from \"./bundle-deploy\";\nimport {\n bundleApps,\n sourceBuildApps,\n deployHosts,\n checkLive,\n deploySummaryLines,\n liveVerdict,\n failureLine,\n failureHint,\n failureReason,\n DEFAULT_LIVE_TIMEOUT_MS,\n type DeployedApp,\n type LiveCheck\n} from \"./deploy-summary\";\nimport { listContextFiles, MAX_SOURCE_UPLOAD_BYTES, packSource, prepareRebuildSource, type RebuildSource } from \"./rebuild-source\";\nimport {\n PREVIEW_DEPLOYMENTS_COLLECTION,\n PREVIEWS_FUNCTION,\n isPreviewsUnavailable,\n normalizePreviewName,\n previewFrom,\n previewCost,\n previewCostLines,\n previewLines,\n triggerPreview,\n type Preview,\n type PreviewCost\n} from \"./previews\";\nimport { resolveTail, type TailLimit } from \"./debug\";\nimport {\n describeEvent,\n fetchRuntimeLogsPage,\n followRuntimeLogs,\n paintLine,\n parseLevelFlag,\n parseRecords,\n parseSinceFlag,\n recordFilter,\n type FollowSink,\n type LogRecord,\n type RuntimeLogsPage,\n type RuntimeLogsQuery\n} from \"./runtime-logs\";\nimport { buildBundle } from \"../../bundle\";\nimport { buildAssetApp } from \"../build\";\nimport { foldableApps, foldFrontendIntoBundle } from \"../../fold-static\";\nimport { checkStaticSyntax, formatSyntaxErrors, type StaticSyntaxError } from \"../../static-syntax-check\";\nimport { loadManifest, findBackendApp, formatAppAddress, resolveBackendPaths, selectDeployApp } from \"../../manifest\";\nimport { findProjectRoot, requireProjectRoot } from \"../../utils/project\";\nimport { withTempArchive } from \"../../utils/temp-archive\";\nimport { deriveOptionsFor, deriveResourceGraph } from \"../../resources/derive\";\nimport type { RebaseAppConfig, RebaseBackendAppConfig, RebaseProjectManifest } from \"@rebasepro/types\";\n\ninterface Deployment {\n id: string | number;\n status?: string;\n logs?: string;\n createdAt?: string;\n}\n\n/**\n * What the control plane says about the deployment holding the lock, when it\n * refuses a trigger. Absent on control planes older than that change.\n */\ninterface BlockingDeployment {\n id?: string;\n createdAt?: string | null;\n status?: string | null;\n triggerSource?: string;\n /**\n * Whether the same user triggered the blocking deployment. Never that it\n * is this trigger's own: a replay of that is answered 200 `deduplicated`.\n */\n mine?: boolean;\n}\n\nconst POLL_INTERVAL_MS = 1500;\nconst POLL_TIMEOUT_MS = 15 * 60 * 1000; // 15 min hard stop\n/** How long a follow keeps retrying a status it cannot read before it says so. */\nconst UNREADABLE_STATUS_MS = 60 * 1000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\n/**\n * Package `sourceDir` into a gzipped tarball at `tarPath`.\n *\n * What goes in is {@link listContextFiles}: `.gitignore` read the way git reads\n * it, `.rebaseignore` beside it, and never an env file, a database dump or the\n * CLI's local state, whatever either says. The control plane keeps the archive\n * as the project's source, so this is the last point anything can be kept back.\n */\nasync function createSourceTarball(sourceDir: string, tarPath: string): Promise<void> {\n const dir = path.resolve(sourceDir);\n if (!fs.existsSync(dir)) fail(`Source directory not found: ${dir}`);\n\n try {\n const files = listContextFiles(dir);\n await packSource({ root: fs.realpathSync(dir), files }, tarPath);\n } catch (e) {\n fail(`Failed to package source: ${e instanceof Error ? e.message : String(e)}`);\n }\n}\n\n/**\n * The `@rebasepro/*` version this source directory actually resolves.\n *\n * Recorded on the deployment so a row in Deployment History says which\n * framework build shipped. Nothing else on the platform knows: an app that\n * links the framework locally pins it at package time, and a silent bump is\n * invisible afterwards — it has already cost one debugging session.\n *\n * `@rebasepro/server` first, because that is what the deployed backend runs;\n * `@rebasepro/client` is the fallback for a frontend-only bundle. Resolution is\n * a plain walk up from the source directory rather than `require.resolve`,\n * which would answer for the CLI's own install tree instead of the app's.\n *\n * Best effort by construction: a version that cannot be read is simply not\n * recorded. Nothing about a deploy should fail over a bookkeeping string.\n */\nfunction resolveFrameworkVersion(sourceDir: string): string | undefined {\n let dir = path.resolve(sourceDir);\n for (;;) {\n for (const pkg of [\"@rebasepro/server\", \"@rebasepro/client\"]) {\n try {\n const manifest = path.join(dir, \"node_modules\", ...pkg.split(\"/\"), \"package.json\");\n const version = (JSON.parse(fs.readFileSync(manifest, \"utf8\")) as { version?: unknown }).version;\n if (typeof version === \"string\" && version.trim() !== \"\") return version.trim();\n } catch {\n /* not here — keep walking */\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n/**\n * A progress line for a human — dropped entirely in JSON mode.\n *\n * Progress is not a result. In JSON mode stdout carries the one result value\n * and nothing else, so every unguarded `console.log` on a deploy path was a\n * line printed in front of the JSON, breaking the parser meant to read it.\n * Warnings are the other half of this rule and go the other way: they are\n * `warn`, which prints in every mode, to stderr. See `warn` in `context.ts`.\n */\nfunction progress(line: string): void {\n if (!isJsonMode()) console.log(line);\n}\n\n/**\n * The token for one of the raw uploads below, read as it is sent.\n *\n * They are plain `fetch` calls, which never refresh a session the way the\n * SDK's own requests do, and each is sent after work that can outlive a token:\n * a type check and a build, or packing a large directory. Read once at the\n * start, the token had lapsed by then, the upload was refused with a 401, and\n * the build was thrown away.\n */\nasync function uploadToken(client: CloudClient, url: string): Promise<string> {\n try {\n return await freshAccessToken(client);\n } catch {\n fail(\n `Your session for ${url} has expired.`,\n \"Run `rebase cloud login` to sign in again, then deploy again.\",\n \"session_expired\"\n );\n }\n}\n\n/** Upload a build-context tarball; returns the opaque `source` ref for deploy. */\nasync function uploadSource(url: string, token: string, projectId: string, tarPath: string): Promise<string> {\n const bytes = fs.readFileSync(tarPath);\n const sizeMb = (bytes.length / 1024 / 1024).toFixed(1);\n if (bytes.length > MAX_SOURCE_UPLOAD_BYTES) {\n fail(\n `Source context is ${sizeMb} MB — the upload cap is ${Math.round(MAX_SOURCE_UPLOAD_BYTES / 1024 / 1024)} MB.`,\n \"Trim the build context: exclude sourcemaps (*.map), build output and large assets via .rebaseignore or .gitignore.\"\n );\n }\n progress(chalk.gray(` Uploading source (${sizeMb} MB)...`));\n const res = await fetch(`${url}/api/functions/deploy/upload?projectId=${encodeURIComponent(projectId)}`, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${token}`,\n\"Content-Type\": \"application/gzip\" },\n body: bytes\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n fail(`Source upload failed (${res.status}): ${body || res.statusText}`);\n }\n const data = (await res.json()) as { source?: string };\n if (!data.source) fail(\"Upload endpoint did not return a source reference.\");\n return data.source;\n}\n\n/**\n * Build, upload and deploy a project as a managed bundle.\n *\n * Builds the backend app into `dist-bundle` (unless one is pointed at with\n * `--bundle-dir`), packs it with the dependency tree the build vendored into it,\n * uploads it, and triggers a deploy carrying the manifest so the control plane\n * can validate intake fast.\n */\nasync function deployBundle(opts: {\n client: CloudClient;\n url: string;\n projectId: string;\n projectRef: string;\n bundleDir?: string;\n message?: string;\n /** Which app to deploy, when this repository declares more than one. */\n appName?: string;\n /** Compile without type checking, exactly as `rebase build` does. */\n skipTypeCheck?: boolean;\n /** Keep the committed Drizzle schema rather than regenerating it, as `rebase build --skip-schema` does. */\n skipSchema?: boolean;\n /** Leave the static apps out of the backend bundle, as `rebase build --no-static` does. */\n noStatic?: boolean;\n /** Parse the static apps' JavaScript before uploading. Default on; `--no-verify` off. */\n verify: boolean;\n /** Follow the deployment to a terminal state. Default on; `--no-follow` off. */\n follow: boolean;\n /** Ceiling on the follow, in milliseconds. */\n timeoutMs: number;\n /** How long to wait for the new version to answer, in milliseconds; 0 skips the check. */\n liveTimeoutMs: number;\n /** Upload the project's source beside a backend bundle. Default on; `--no-source` off. */\n uploadSource: boolean;\n /** `--allow-downgrade`: deploy a bundle built on an older release than the project runs. */\n allowDowngrade: boolean;\n /** When the command started, for the `cli.deploy` event's duration. */\n startedAt: number;\n /** `--preview`: serve this build on a preview address instead of production. */\n preview?: PreviewRequest;\n}): Promise<void> {\n // Nothing here reads client/url/projectId/projectRef any more: everything\n // that needs them is reached through `uploadAndTrigger({ ...opts })`, which\n // takes the whole object. Destructuring them anyway is four values computed\n // and dropped.\n const projectRoot = requireProjectRoot();\n\n let bundleDir = opts.bundleDir\n ? path.resolve(process.cwd(), opts.bundleDir)\n : path.join(projectRoot, \"dist-bundle\");\n\n // Build the bundle unless the caller pointed at a prebuilt one.\n if (!opts.bundleDir) {\n // Every refusal before the build goes through `fail`: a throw reached\n // stdout in JSON mode as nothing at all.\n let loaded: ReturnType<typeof loadManifest>;\n try {\n loaded = loadManifest(projectRoot);\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err), undefined, \"invalid_manifest\");\n }\n\n // Which app, decided once and by the manifest. A repository declares\n // apps and a project owns them, so a repository holding only an admin\n // panel is an ordinary thing rather than a repository with a missing\n // backend — which is what this used to call it, refusing the deploy.\n let target: { name: string; app: RebaseAppConfig };\n try {\n target = selectDeployApp(loaded.manifest, opts.appName);\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err));\n return;\n }\n\n if (target.app.type === \"static\" && opts.noStatic) {\n fail(\n `--no-static leaves a backend's frontend out of its bundle, and \"${target.name}\" is a static app: ` +\n \"its bundle is nothing but its frontend.\",\n \"Deploy it without --no-static.\",\n \"usage\"\n );\n }\n\n if (target.app.type === \"static\") {\n // A static app deploys through the identical path — upload, trigger,\n // same endpoint — and differs only in what it builds and in the\n // `kind` its manifest carries. The control plane routes on that.\n progress(chalk.gray(` Building static app \"${target.name}\"...`));\n let staticDir: string | undefined;\n try {\n staticDir = await buildAssetApp(\n projectRoot,\n target.name,\n target.app,\n loaded.manifest.rebase,\n undefined,\n { quietStdout: isJsonMode() }\n );\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err));\n }\n if (!staticDir) {\n fail(\n `App \"${target.name}\" produced no bundle.`,\n \"A static app needs both a `build` command and an `output` directory in rebase.json.\"\n );\n return;\n }\n bundleDir = staticDir;\n if (opts.verify) verifyStaticOutput(projectRoot, [{ name: target.name,\noutput: target.app.output }]);\n await uploadAndTrigger({ ...opts,\nprojectRoot,\nbundleDir,\nappName: target.name });\n return;\n }\n\n progress(chalk.gray(\" Building bundle...\"));\n // `target` is decided above, by the manifest. Naming it `backend` here\n // is what the rest of this block reads.\n const backend = { name: target.name,\napp: target.app as RebaseBackendAppConfig };\n\n // Same derivation `rebase build` does, and fatal for the same reason: a\n // bundle whose manifest is missing a bucket the code declares deploys\n // into a tenant with nothing provisioned for it. After `backend` on\n // purpose — the config directory it reads comes from that app.\n const { graph: resourceGraph, issues: resourceIssues } = await deriveResourceGraph(\n deriveOptionsFor(projectRoot, backend.app)\n );\n if (resourceIssues.length > 0) {\n fail(\n `${resourceIssues.length} problem(s) in the declared resources:\\n` +\n resourceIssues.map(i => ` ${i.path} ${i.message}`).join(\"\\n\"),\n undefined,\n \"build_failed\"\n );\n }\n // A build that fails is the deploy's answer, in either output mode: in\n // JSON mode an error thrown past here reached stdout as nothing at all.\n let result: Awaited<ReturnType<typeof buildBundle>>;\n try {\n result = await buildBundle({\n projectRoot,\n appName: backend.name,\n app: backend.app,\n runtimeRange: loaded.manifest.rebase,\n resources: resourceGraph,\n skipTypeCheck: opts.skipTypeCheck,\n skipSchema: opts.skipSchema,\n // The upload leaves `node_modules` out (see packBundleForUpload),\n // so installing it here would be 35-55s spent on a tree nobody ships.\n vendor: false,\n log: (m: string) => progress(chalk.gray(m)),\n quietStdout: isJsonMode()\n });\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err), undefined, \"build_failed\");\n }\n bundleDir = result.outDir;\n\n /* Fold the frontend in, exactly as `rebase build` does. This path builds\n its own bundle, so without the same step a deploy shipped a bundle with\n no site in it — the managed pod then served the API perfectly and 404'd\n every page, which is precisely the failure folding exists to prevent.\n Two callers producing the same artefact have to share the step that\n completes it, and the same way out of it: `--no-static`. */\n if (!opts.noStatic) {\n try {\n const folded = await foldFrontendIntoBundle({\n projectRoot,\n manifest: loaded.manifest as never,\n bundleDir,\n log: (m: string) => progress(m),\n quietStdout: isJsonMode()\n });\n for (const outcome of folded) {\n progress(chalk.gray(\n ` folded ${outcome.appName} in (${outcome.fileCount} file(s), served at ${formatAppAddress(outcome)})`\n ));\n }\n } catch (err) {\n fail(\n err instanceof Error ? err.message : String(err),\n \"Fix the frontend build, or pass --no-static to deploy the API alone.\"\n );\n }\n if (opts.verify) verifyStaticOutput(projectRoot, foldableApps(loaded.manifest).apps);\n }\n }\n\n await uploadAndTrigger({ ...opts,\nprojectRoot,\nbundleDir });\n}\n\n/** Printed under a successful deploy: the way back, where it is needed. */\nexport const ROLLBACK_HINT = \"Something wrong? `rebase cloud rollback` puts the previous deployment back.\";\n\n/**\n * The same line for a static app deployed on its own. Its deployment records\n * no bundle, so the control plane has nothing to roll back to (see the\n * \"Roll back\" section of the cloud deployment docs). Pointing at\n * `rollback` here would restore the backend instead, or refuse.\n */\nexport const STATIC_UNDO_HINT =\n \"Something wrong? A static app deployed on its own cannot be rolled back yet: deploy its last good version again.\";\n\n/**\n * Stop the deploy on a syntax error in a static app's output, before anything\n * is uploaded. See `checkStaticSyntax`.\n *\n * A static app's files are served as they are, so a broken script that no\n * bundler ever parsed went live and took the page down with it. Nothing on the\n * way said so: the build \"succeeded\" by copying it, and the deploy succeeded\n * by uploading it. `--no-verify` is the way past for a file the check gets\n * wrong.\n */\nexport function verifyStaticOutput(projectRoot: string, apps: { name: string; output?: string }[]): void {\n const errors: StaticSyntaxError[] = [];\n let checked = 0;\n for (const app of apps) {\n if (!app.output) continue;\n const dir = path.join(projectRoot, app.output);\n if (!fs.existsSync(dir)) continue;\n const report = checkStaticSyntax(dir, projectRoot);\n checked += report.checked;\n errors.push(...report.errors);\n }\n if (errors.length > 0) {\n fail(\n `${errors.length === 1 ? \"A syntax error\" : `${errors.length} syntax errors`} in the static output, `\n + \"so nothing was deployed:\\n\"\n + formatSyntaxErrors(errors).map(line => ` ${line}`).join(\"\\n\"),\n \"Fix it and deploy again, or pass --no-verify to deploy anyway.\",\n \"syntax_error\"\n );\n }\n if (checked > 0) progress(chalk.gray(` Syntax-checked ${checked} script(s) in the static output.`));\n}\n\n/**\n * Pack a built bundle, upload it, and trigger the deploy.\n *\n * Shared by every managed deploy, whichever kind of app produced the bundle: a\n * backend and a static app differ in what is built and in the `kind` their\n * manifest carries, and in nothing after that. Keeping one tail is what makes\n * that true rather than nearly true — the folding step was once missing from\n * one of two callers producing the same artifact, and the deploy shipped a\n * bundle with no site in it.\n */\nasync function uploadAndTrigger(opts: {\n client: CloudClient;\n url: string;\n projectId: string;\n projectRef: string;\n /**\n * The directory holding `rebase.json`. Everything about the project — its\n * declared apps, its commit, its source — is read from here, never from\n * the working directory, which may be `backend/` or anywhere else inside it.\n */\n projectRoot: string;\n bundleDir: string;\n message?: string;\n appName?: string;\n follow: boolean;\n timeoutMs: number;\n liveTimeoutMs: number;\n uploadSource: boolean;\n allowDowngrade: boolean;\n /** When the command started, for the `cli.deploy` event's duration. */\n startedAt: number;\n /** `--preview`: serve this build on a preview address instead of production. */\n preview?: PreviewRequest;\n}): Promise<void> {\n const { client, url, projectId, projectRef, projectRoot, bundleDir } = opts;\n let manifest: ReturnType<typeof readBundleManifest>;\n try {\n manifest = readBundleManifest(bundleDir);\n } catch (err) {\n fail(err instanceof Error ? err.message : String(err), undefined, \"invalid_bundle\");\n }\n // `cli.deploy`, recorded for a bundle deploy as for a source build: this is\n // the default deploy of every scaffold, and it recorded nothing.\n const record = (followed: boolean, status: string): Promise<void> => recordDeploy({\n followed,\n status,\n deduplicated: false,\n frameworkVersion: manifest.runtime?.builtAgainst,\n startedAt: opts.startedAt,\n projectRoot\n });\n\n // Native modules cannot run on the managed runtime — the server rejects them\n // at intake anyway, but catching it here saves a pointless upload of a bundle\n // that cannot be deployed. Checked against the manifest, so it covers a\n // prebuilt `--bundle-dir` bundle just as much as one we just built.\n if (manifest.hooks?.native) {\n const names = (manifest.hooks.nativeModules ?? []).map(m => m.name).join(\", \");\n fail(\n `This bundle depends on native modules${names ? ` (${names})` : \"\"}, which the managed runtime cannot run.`,\n \"Remove the native dependency, or deploy on the custom runtime.\"\n );\n }\n\n // Pack + upload, into a directory of this run's own: see `withTempArchive`.\n let bundleId: string;\n try {\n bundleId = await withTempArchive(\"rebase-bundle\", async (tarPath) => {\n const packed = await packBundleForUpload(bundleDir, tarPath, manifest);\n if (packed.modulesLeftOut) {\n warn(\n \"This bundle's installed dependencies are not uploaded: a managed pod installs them when it starts.\",\n \"Build it with `rebase build --no-vendor` to skip installing a tree the upload leaves out.\"\n );\n }\n const sizeMb = (packed.bytes / 1024 / 1024).toFixed(1);\n progress(chalk.gray(` Uploading bundle (${sizeMb} MB)...`));\n return uploadBundle(url, await uploadToken(client, url), projectId, tarPath);\n });\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e));\n return;\n }\n\n // Guarded for the same reason as the source-deploy banner below: the JSON\n // result on this path is printed to stdout too.\n if (!isJsonMode()) {\n console.log(\"\");\n console.log(opts.preview\n ? ` 🔍 Triggering a preview of ${chalk.bold(projectRef)}${opts.preview.name ? ` named ${chalk.bold(opts.preview.name)}` : \"\"} (schema ${manifest.schemaVersion}) — production is not touched...`\n : ` 🚀 Triggering managed deployment for ${chalk.bold(projectRef)} (schema ${manifest.schemaVersion})...`);\n }\n\n // Tell the platform about every app this repo declares, not only the one\n // whose bundle is being uploaded. A deploy ships one app; the Apps page is\n // meant to show the set, and without this it only ever knew about the backend.\n let projectManifest: RebaseProjectManifest | undefined;\n try {\n projectManifest = loadManifest(projectRoot).manifest;\n } catch {\n // A project with no readable rebase.json still deploys; it just cannot\n // describe its other apps.\n }\n // Not for a preview: registering the declared apps, and the hostnames\n // they name, is a change to the production project.\n const declaredApps = opts.preview ? [] : declaredAppsFrom(projectManifest);\n\n // The source this bundle was built from, so a platform upgrade can rebuild\n // it on a newer release. A backend only: a static app's bundle is its\n // built files and nothing more, and has nothing to rebuild against.\n // Best effort — see `prepareRebuildSource`, which warns and returns null\n // rather than fail a deploy over it.\n let rebuildSource: RebuildSource | null = null;\n if (opts.preview) {\n // The stored source is what a platform upgrade rebuilds PRODUCTION\n // from. A preview's source replacing it would ship the preview to\n // production on the next rollout — nothing is uploaded for one.\n } else if (opts.uploadSource && manifest.kind !== \"static\" && await platformRebuildsOff(client, projectId)) {\n // The owner turned platform rebuilds off: the platform keeps no copy\n // of this app's source, so none leaves the machine. Asked before\n // packing anything; the control plane refuses the upload regardless.\n progress(chalk.gray(\n \" Platform rebuilds are off for this project, so its source is not uploaded \" +\n \"(turn them on with `rebase cloud settings set --platform-rebuilds on`).\"\n ));\n } else if (opts.uploadSource && manifest.kind !== \"static\") {\n rebuildSource = await prepareRebuildSource({\n projectRoot,\n url,\n // Read after packing, just before the upload — see `uploadToken`. A\n // session that cannot be refreshed costs the source, as a warning.\n token: () => freshAccessToken(client),\n projectId,\n manifest: projectManifest,\n progress: (line) => progress(chalk.gray(line)),\n warn\n });\n }\n\n const body = bundleDeployBody({\n projectId,\n bundleId,\n manifest,\n app: opts.appName,\n message: opts.message,\n declaredApps,\n // Read here because here is the only place it exists: a bundle deploy\n // uploads a tarball, so nothing near the control plane has a repository\n // to ask. See `bundleCommit`.\n commit: bundleCommit(projectRoot),\n rebuildSource,\n allowFrameworkDowngrade: opts.allowDowngrade\n });\n\n if (opts.preview) {\n await triggerAndFollowPreview({ ...opts, body, record });\n return;\n }\n\n let deploymentId: string;\n let managed: boolean;\n let hosts: DeployHost[] | undefined;\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string | number };\n managed?: boolean;\n hosts?: unknown;\n }>(\"deploy\", body);\n if (!res?.deployment?.id) fail(\"Control plane did not return a deployment id.\");\n deploymentId = String(res.deployment.id);\n managed = res.managed === true;\n hosts = deployHostsFrom(res);\n } catch (e) {\n // The same refusals as a source build, answered the same way: the\n // control plane sends both doors identical envelopes. This path used\n // to read only the intake code, so a 409 lost the blocking deploy's id\n // and the way to cancel it, and a 402 the way to billing.\n resolveTriggerFailure(e, \"Managed deploy failed to start\");\n }\n\n // Followed to a terminal state, like the source path beside it.\n //\n // This half used to stop at \"deploy started\" and print \"track it with\n // `rebase cloud logs`\", so `rebase cloud deploy` meant two different things\n // depending on which runtime the project happened to declare: on one path\n // it waited and the exit code was the verdict, on the other it returned 0\n // the moment the trigger was accepted — including for builds that went on\n // to fail. Every caller then wrote its own poll loop, with its own timeout,\n // against the same two fields this function already had in hand.\n //\n // One rule now: `deploy` follows unless told not to. `--no-follow` is that\n // instruction and keeps the old shape for anyone who wants it.\n const appsAt = (host: string | undefined): DeployedApp[] => bundleApps(manifest, host);\n if (!opts.follow) {\n await reportTriggered({\n client,\n url,\n projectId,\n deploymentId,\n appsAt,\n registeredHosts: hosts,\n headline: ` ✓ Managed deploy started (deployment ${deploymentId}).`,\n json: { success: true,\ndeploymentId,\nmanaged,\nsourceUploaded: rebuildSource !== null,\nfollowing: false }\n });\n await record(false, \"not_followed\");\n return;\n }\n\n if (!isJsonMode()) {\n console.log(chalk.green(` ✓ Managed deploy started (deployment ${deploymentId}).`));\n console.log(chalk.gray(\" Streaming build logs (Ctrl-C to stop watching — the build keeps running):\"));\n console.log(\"\");\n }\n\n const { status } = await streamBuildLogs(client, deploymentId, {\n quiet: isJsonMode(),\n timeoutMs: opts.timeoutMs,\n projectId,\n url,\n announce: false,\n failedApps: appsAt(undefined).map(a => a.name),\n onTerminal: (ended) => record(true, ended)\n });\n // The app is built now, so an unclaimed project's app can mint the key\n // `init` could not: see `mintMissingAppKey`. Never fails the deploy.\n const appKey = await mintMissingAppKey({ url, projectId, root: projectRoot });\n reportMintedAppKey(appKey);\n await reportDeployed({\n undo: manifest.kind === \"static\" ? STATIC_UNDO_HINT : ROLLBACK_HINT,\n client,\n url,\n projectId,\n projectRef,\n deploymentId,\n startedAt: opts.startedAt,\n liveTimeoutMs: opts.liveTimeoutMs,\n appsAt,\n registeredHosts: hosts,\n json: { success: true,\ndeploymentId,\nmanaged,\nsourceUploaded: rebuildSource !== null,\nfollowing: true,\nstatus,\n...(appKey ? { appKey: appKeyPayload(appKey) } : {}) }\n });\n}\n\n/**\n * The end of a deploy that was followed to success: resolve where each app\n * answers, check that the new version does, and print the summary — or, in\n * JSON mode, the one object carrying the same facts.\n *\n * The object keeps every key it had and gains `project`, `apps`, `durationMs`,\n * `live` and `liveChecks`; `hosts` lists the project's own host first.\n */\nasync function reportDeployed(o: {\n client: CloudClient;\n url: string;\n projectId: string;\n projectRef: string;\n deploymentId: string;\n startedAt: number;\n liveTimeoutMs: number;\n appsAt: (projectHost: string | undefined) => DeployedApp[];\n registeredHosts: DeployHost[] | undefined;\n /** How to undo this deploy, printed under the summary. */\n undo?: string;\n json: Record<string, unknown>;\n}): Promise<void> {\n const host = await deployedUrl(o.client, { projectId: o.projectId, url: o.url });\n const apps = o.appsAt(host);\n const hosts = deployHosts(o.registeredHosts, host);\n\n let live: LiveCheck[] | undefined;\n if (o.liveTimeoutMs > 0) {\n progress(chalk.gray(\" Checking that the new version answers...\"));\n live = await checkLive(apps, { deploymentId: o.deploymentId, hosts, timeoutMs: o.liveTimeoutMs });\n }\n const verdict = liveVerdict(live, o.liveTimeoutMs);\n const elapsedMs = Date.now() - o.startedAt;\n\n emit(\n () => {\n const lines = deploySummaryLines({\n projectRef: o.projectRef,\n deploymentId: o.deploymentId,\n elapsedMs,\n apps,\n live,\n liveTimeoutMs: o.liveTimeoutMs\n });\n // The way back, under the verdict that says whether it is needed.\n if (o.undo) lines.splice(lines.length - 1, 0, chalk.gray(` ${o.undo}`));\n for (const line of lines) console.log(line);\n printPendingHosts(hosts);\n },\n { ...o.json,\nproject: o.projectRef,\napps,\n...hostsField(hosts, o.registeredHosts),\ndurationMs: elapsedMs,\nlive: verdict.live,\nliveChecks: live ?? [] }\n );\n}\n\n/**\n * The end of a `--no-follow` deploy: it was triggered, and here is where it\n * will answer. No live check — nothing is waiting for it to finish.\n */\nasync function reportTriggered(o: {\n client: CloudClient;\n url: string;\n projectId: string;\n deploymentId: string;\n appsAt: (projectHost: string | undefined) => DeployedApp[];\n registeredHosts: DeployHost[] | undefined;\n /** Printed first in human mode; empty for none. */\n headline: string;\n json: Record<string, unknown>;\n}): Promise<void> {\n const host = await deployedUrl(o.client, { projectId: o.projectId, url: o.url });\n const apps = o.appsAt(host);\n const hosts = deployHosts(o.registeredHosts, host);\n emit(\n () => {\n if (o.headline) console.log(chalk.green(o.headline));\n console.log(chalk.gray(\" Not following (--no-follow). Track it with `rebase cloud logs`.\"));\n const addressed = apps.filter(a => a.url);\n if (addressed.length > 0) {\n console.log(chalk.gray(\" When it finishes it will answer at:\"));\n for (const app of addressed) console.log(` ${app.name} ${chalk.cyan(app.url ?? \"\")}`);\n }\n console.log(\"\");\n printPendingHosts(hosts);\n },\n { ...o.json,\napps,\n...hostsField(hosts, o.registeredHosts),\nlive: null }\n );\n}\n\n/**\n * `hosts` for the JSON result, or no field at all when there is nothing to say:\n * a control plane that predates the field and a project host that could not be\n * resolved. An empty list would claim the deploy looked and found none.\n */\nfunction hostsField(hosts: DeployHost[], registered: DeployHost[] | undefined): { hosts?: DeployHost[] } {\n return hosts.length > 0 || registered !== undefined ? { hosts } : {};\n}\n\n/** What `--preview` and `--preview-name` asked for. */\nexport interface PreviewRequest {\n /** A stable name, so later deploys update the same address; absent, the control plane picks one. */\n name?: string;\n}\n\n/**\n * `--preview` / `--preview-name <name>` off the parsed flags, or undefined for\n * a production deploy. A name alone is a preview: nobody names a production\n * deploy's address.\n */\nexport function resolvePreviewRequest(flags: { \"--preview\"?: boolean; \"--preview-name\"?: string }): PreviewRequest | undefined {\n if (flags[\"--preview-name\"] !== undefined) return { name: normalizePreviewName(flags[\"--preview-name\"]) };\n return flags[\"--preview\"] === true ? {} : undefined;\n}\n\n/**\n * The tail of a preview deploy: trigger it through `previews`, follow its\n * build, and report the preview's address rather than production's.\n */\nasync function triggerAndFollowPreview(opts: {\n client: CloudClient;\n projectId: string;\n url: string;\n follow: boolean;\n timeoutMs: number;\n /** How long to wait for the preview to answer once built; 0 skips the check. */\n liveTimeoutMs: number;\n preview?: PreviewRequest;\n body: Record<string, unknown>;\n record: (followed: boolean, status: string) => Promise<void>;\n}): Promise<void> {\n const { client, projectId } = opts;\n const { deploymentId, preview } = await triggerPreview(\n client,\n projectId,\n { ...opts.body, preview: opts.preview?.name ? { name: opts.preview.name } : {} },\n (e) => {\n const refusal = intakeRefusal(e);\n if (refusal) fail(refusal.message, refusal.hint, refusal.code);\n }\n );\n\n // What it costs, in the control plane's numbers. Only a backend preview\n // is billed: one that is only files runs no pod of its own.\n const costOf = async (): Promise<PreviewCost | null> =>\n preview.backend === \"production\" ? null : previewCost(client, opts.url, projectId);\n\n if (!opts.follow) {\n const cost = await costOf();\n emit(\n () => {\n console.log(chalk.green(` ✓ Preview deploy started (deployment ${deploymentId}).`));\n for (const line of previewLines(preview)) console.log(` ${line}`);\n if (cost) for (const line of previewCostLines(cost, preview.name)) console.log(chalk.gray(` ${line}`));\n console.log(chalk.gray(` Not following (--no-follow). Follow its build with \\`rebase cloud logs --preview ${preview.name} -f\\`.`));\n },\n { success: true, deploymentId, following: false, preview, cost }\n );\n await opts.record(false, \"not_followed\");\n return;\n }\n\n if (!isJsonMode()) {\n console.log(chalk.green(` ✓ Preview deploy started (deployment ${deploymentId}).`));\n console.log(chalk.gray(\" Streaming build logs (Ctrl-C to stop watching — the build keeps running):\"));\n console.log(\"\");\n }\n const { status } = await streamBuildLogs(client, deploymentId, {\n quiet: isJsonMode(),\n timeoutMs: opts.timeoutMs,\n projectId,\n url: opts.url,\n collection: PREVIEW_DEPLOYMENTS_COLLECTION,\n preview,\n onTerminal: (ended) => opts.record(true, ended)\n });\n // The control plane's `ready` is a pod that passed its readiness probe,\n // not an address that answers: the preview's certificate, and its Ingress\n // rule, can trail it. So the same live check a production deploy runs,\n // against the preview's own address.\n const live = opts.liveTimeoutMs > 0 ? await checkPreviewLive(preview, deploymentId, opts.liveTimeoutMs) : undefined;\n const cost = await costOf();\n emit(\n () => {\n if (cost) {\n for (const line of previewCostLines(cost, preview.name)) console.log(chalk.gray(` ${line}`));\n console.log(\"\");\n }\n if (!live) return;\n const down = live.filter(check => !check.live);\n console.log(down.length === 0\n ? chalk.green(` Live: the preview answers at ${preview.url}.`)\n : chalk.yellow(` Not confirmed live after ${Math.max(1, Math.round(opts.liveTimeoutMs / 1000))}s: ${down.map(c => c.reason ?? \"no answer\").join(\", \")}. `\n + \"The build succeeded; a new preview's certificate can take a minute or two. Open the address again shortly.\")\n );\n console.log(\"\");\n },\n { success: true, deploymentId, following: true, status, preview, cost, live: liveVerdict(live, opts.liveTimeoutMs).live, liveChecks: live ?? [] }\n );\n}\n\n/** Probe a preview's own address until it answers, like {@link checkLive} for a deploy. */\nasync function checkPreviewLive(preview: Preview, deploymentId: string, timeoutMs: number): Promise<LiveCheck[]> {\n let host: string;\n try {\n host = new URL(preview.url).host;\n } catch {\n return [];\n }\n progress(chalk.gray(\" Checking that the preview answers...\"));\n const app: DeployedApp = {\n name: preview.app ?? (preview.backend === \"production\" ? \"site\" : \"backend\"),\n // A backend preview is live when its health route says so; a static\n // one when its address answers.\n type: preview.backend === \"production\" ? \"static\" : \"backend\",\n url: preview.url,\n host\n };\n return checkLive([app], { deploymentId, hosts: [], timeoutMs });\n}\n\n/**\n * Say which of a deploy's hostnames are not live yet, and how to make them so.\n *\n * Printed last, under the verdict, because that is where somebody looks for\n * the address they just deployed to — and an app on a hostname whose DNS was\n * never published would otherwise read as a deploy that succeeded and serves\n * nothing. In JSON mode the same facts travel as `hosts` in the result.\n */\nfunction printPendingHosts(hosts: DeployHost[] | undefined): void {\n const notices = pendingHostNotices(hosts ?? []);\n if (notices.length === 0) return;\n console.log(\"\");\n for (const notice of notices) {\n console.log(chalk.yellow(` ⚠ ${notice.headline}`));\n for (const line of notice.details) console.log(` ${line}`);\n console.log(\"\");\n }\n}\n\n/* ─── what a deploy with nothing attached is actually going to build ─────────\n *\n * `rebase cloud deploy` with neither `--source` nor `--bundle` uploads nothing.\n * It asks the control plane to rebuild what it already holds — a git checkout,\n * or the newest source archive some earlier `--source` deploy left in object\n * storage. Both are legitimate; neither is this working directory, and the\n * command said nothing about which one it meant, so a deploy that shipped\n * month-old code was indistinguishable from one that shipped today's.\n *\n * For a project on the managed runtime it is worse than stale: a successful\n * source build sets `runtimeMode: \"custom\"` server-side, so the bare form\n * silently swaps a managed project back onto a container image. That one is a\n * refusal rather than a note — `--bundle` is what was meant, and `--eject`\n * ejects on purpose.\n */\n\n/** A project row, reduced to what says how it deploys (camel or snake columns). */\nexport interface DeployProjectRow {\n runtimeMode?: string;\n runtime_mode?: string;\n gitRepoUrl?: string;\n git_repo_url?: string;\n gitBranch?: string;\n git_branch?: string;\n}\n\n/** A deployment row, reduced to what says what it was built from. */\nexport interface DeploySourceRow {\n id?: string | number;\n status?: string;\n createdAt?: string | Date;\n created_at?: string | Date;\n sourceRef?: string;\n source_ref?: string;\n bundleId?: string;\n bundle_id?: string;\n}\n\nexport interface BareDeployPlan {\n /**\n * Whether the project runs the platform runtime — in which case any source\n * build here ejects it back onto a container image.\n */\n managed: boolean;\n /**\n * `git` — the control plane will clone the configured repository.\n * `snapshot` — it will rebuild the newest uploaded source archive.\n * `none` — it holds neither, and will refuse.\n */\n source: \"git\" | \"snapshot\" | \"none\";\n /** Lines describing the build, printed before it is triggered. */\n lines: string[];\n}\n\nfunction pick(row: Record<string, unknown> | undefined, ...keys: string[]): string | undefined {\n for (const key of keys) {\n const raw = row?.[key];\n if (typeof raw === \"string\" && raw.trim() !== \"\") return raw.trim();\n }\n return undefined;\n}\n\n/** Rough age of a timestamp, for \"…uploaded 6d ago\". Undefined if unreadable. */\nexport function timeAgo(value: string | Date | undefined, now: Date): string | undefined {\n if (value === undefined) return undefined;\n const then = value instanceof Date ? value.getTime() : new Date(value).getTime();\n if (Number.isNaN(then)) return undefined;\n const ms = now.getTime() - then;\n // A clock skewed into the future is not an age; saying nothing beats a lie.\n if (ms < 0) return undefined;\n const minutes = Math.floor(ms / 60_000);\n if (minutes < 1) return \"just now\";\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n return `${Math.floor(hours / 24)}d ago`;\n}\n\n/**\n * Whether this project runs on the managed runtime.\n *\n * `runtimeMode` on the project row is the authority — the control plane writes\n * it. The bundle-id fallback covers a control plane that does not return the\n * field: a successful deploy that served a bundle only happens on the managed\n * path.\n */\nexport function isManagedProject(\n project: DeployProjectRow | undefined,\n latest: DeploySourceRow | undefined\n): boolean {\n if (pick(project as Record<string, unknown> | undefined, \"runtimeMode\", \"runtime_mode\") === \"managed\") return true;\n return latest?.status === \"success\"\n && pick(latest as Record<string, unknown> | undefined, \"bundleId\", \"bundle_id\") !== undefined;\n}\n\n/** A row's own `createdAt`, in ms; 0 when it has none that parses. */\nfunction createdAtMs(row: DeploySourceRow): number {\n const raw = row.createdAt ?? row.created_at;\n const at = raw instanceof Date ? raw.getTime() : typeof raw === \"string\" ? new Date(raw).getTime() : NaN;\n return Number.isNaN(at) ? 0 : at;\n}\n\n/**\n * The deployment whose uploaded archive a bare deploy rebuilds, if any.\n *\n * The control plane's own rule (`reusableSourceRef`, over the newest 25 rows):\n * the newest row, by its own `createdAt`, carrying a build-context ref. Not the\n * newest row — a rollback or a bundle deploy carries none, and the upload\n * rebuilt then is the one before it.\n */\nexport function snapshotDeployment(recent: readonly DeploySourceRow[]): DeploySourceRow | undefined {\n let best: { row: DeploySourceRow; at: number } | undefined;\n for (const row of recent) {\n const ref = pick(row as Record<string, unknown>, \"sourceRef\", \"source_ref\");\n if (!ref || ref.includes(\"..\") || !ref.endsWith(\".tar.gz\")) continue;\n const at = createdAtMs(row);\n if (!best || at > best.at) best = { row, at };\n }\n return best?.row;\n}\n\n/**\n * What a `deploy` with nothing attached will build, in the words to print.\n *\n * `recent` is the project's newest deployments, newest first — the same page\n * the control plane reads to choose an archive.\n */\nexport function planBareDeploy(\n project: DeployProjectRow | undefined,\n recent: readonly DeploySourceRow[],\n now: Date\n): BareDeployPlan {\n const projectRow = project as Record<string, unknown> | undefined;\n const latest = recent[0];\n const managed = isManagedProject(project, latest);\n\n const repo = pick(projectRow, \"gitRepoUrl\", \"git_repo_url\");\n if (repo) {\n const branch = pick(projectRow, \"gitBranch\", \"git_branch\");\n return { managed,\nsource: \"git\",\nlines: [`Building from git: ${repo}${branch ? ` (${branch})` : \"\"}.`] };\n }\n\n const snapshot = snapshotDeployment(recent);\n if (snapshot) {\n const age = timeAgo(snapshot.createdAt ?? snapshot.created_at, now);\n const lines = [\n `Rebuilding the stored source archive${snapshot.id !== undefined ? ` from deployment ${snapshot.id}` : \"\"}` +\n `${age ? `, uploaded ${age}` : \"\"}.`\n ];\n if (latest && snapshot !== latest && latest.id !== undefined) {\n lines.push(`Deployment ${latest.id}, the newest, carried no archive of its own, so this is not what it deployed.`);\n }\n lines.push(\"This directory is NOT uploaded — pass `--source .` to build what is on disk.\");\n return { managed,\nsource: \"snapshot\",\nlines };\n }\n\n return {\n managed,\n source: \"none\",\n lines: [\n \"This project has no git repository configured and no stored source archive to rebuild.\",\n \"Upload this directory with `--source .`, or set a repository URL in the project settings.\"\n ]\n };\n}\n\n/**\n * A warning attached to a deploy: printed for the human, carried in the JSON.\n *\n * `code` is the stable half — the message is prose and will be reworded, so it\n * is the code that CI or an agent branches on.\n */\nexport interface DeployWarning {\n code: string;\n message: string;\n hint?: string;\n}\n\n/** `code` of the warning below, and the field name it sets in the payload. */\nexport const EJECTS_MANAGED_RUNTIME = \"ejects_managed_runtime\";\n\n/** The one sentence that says a source build undoes `runtimeMode: managed`. */\nexport function ejectWarning(projectRef: string): DeployWarning {\n return {\n code: EJECTS_MANAGED_RUNTIME,\n message: `${projectRef} runs on the managed runtime — this build ejects it to a custom container.`,\n hint: \"Use `rebase cloud deploy --bundle` to stay on managed.\"\n };\n}\n\n/** How a container-image deploy was asked for — the input to both rules below. */\nexport interface EjectContext {\n /** The project currently runs on the managed runtime. */\n managed: boolean;\n /** `--source` was passed: build this directory. */\n source: boolean;\n /** `--eject` was passed: leave the managed runtime on purpose. */\n eject: boolean;\n}\n\n/**\n * Why a container-image deploy of a managed project is refused — or `undefined`\n * to let it through.\n *\n * Every path below this point builds a container image, and a successful one\n * sets `runtimeMode: \"custom\"` server-side. So the question is never \"which flag\n * was used\" but \"did the caller ask to leave the managed runtime\", and only\n * `--eject` answers it.\n *\n * The flag was `--force` until the 2026-09-06 sweep. `--force` means four\n * different things across this CLI — overwrite a file, disconnect other\n * Postgres sessions, set a build-time key anyway — and three of them are\n * recoverable in a minute. This one moves a live project off the managed\n * runtime, which is the least recoverable thing the CLI can be asked to do,\n * and it had the same name as \"overwrite this file\". Renamed rather than\n * aliased: an alias would leave the dangerous spelling working.\n *\n * `--source` used to be read as answering it too, on the theory that uploading a\n * build context is self-evidently a deliberate eject. It is not: `--source`\n * picks *which source* gets built — this directory, rather than the stale\n * archive the control plane is holding — and the eject is a side effect of the\n * answer. That is exactly how a live project got flipped to `custom` by someone\n * whose actual intent was \"deploy what I have here\", and it is the same\n * ignorance the bare form is refused for. Same ignorance, same refusal.\n */\nexport function ejectRefusal(\n opts: EjectContext,\n projectRef: string\n): { message: string; hint: string; code: string } | undefined {\n if (!opts.managed || opts.eject) return undefined;\n const eject = \"To eject on purpose, add `--eject`.\";\n if (opts.source) {\n return {\n message:\n `${projectRef} runs on the managed runtime, and \\`--source\\` builds a container image from ` +\n \"this directory — which ejects it from managed. Picking a build method is not the same as \" +\n \"asking to leave the runtime.\",\n hint: `Deploy this directory to the managed runtime with \\`rebase cloud deploy --bundle\\`. ${eject}`,\n code: \"managed_project\"\n };\n }\n return {\n message:\n `${projectRef} runs on the managed runtime, and a plain \\`rebase cloud deploy\\` builds a ` +\n \"container image instead — ejecting it from managed, from source the control plane \" +\n \"already holds rather than this directory.\",\n hint:\n `Redeploy it with \\`rebase cloud deploy --bundle\\`. ${eject} ` +\n \"`--source . --eject` builds this directory; `--eject` alone builds what the control plane holds.\",\n code: \"managed_project\"\n };\n}\n\n/**\n * Which warnings a container-image deploy has earned.\n *\n * Pure, and separate from the printing, because the printing is what went\n * wrong: the eject warning used to be written inline behind `!isJsonMode()`, so\n * the fact that a deploy ejects a managed project existed only as a side effect\n * of a TTY being attached. Deciding here, emitting once at the call site, means\n * the decision cannot be output-mode-dependent again.\n *\n * The condition is just `managed`: anything reaching this point is a container\n * image build that `ejectRefusal` has already let through, and on a managed\n * project that is an eject however it was spelled. A caller who passed `--eject`\n * knows — the warning is for the transcript and the payload, which is what\n * anyone reviewing the deploy afterwards actually reads.\n */\nexport function deployWarnings(opts: EjectContext, projectRef: string): DeployWarning[] {\n return opts.managed ? [ejectWarning(projectRef)] : [];\n}\n\n/** The warning half of a deploy's JSON payload — merged into whatever it emits. */\nexport function warningPayload(warnings: DeployWarning[]): Record<string, unknown> {\n return {\n warnings: warnings.map((w) => ({\n code: w.code,\n message: w.message,\n hint: w.hint ?? null\n })),\n // Denormalised from `warnings` on purpose: a boolean is what a CI step\n // can test without walking an array, and this is the one consequence\n // worth failing a pipeline over.\n ejectsManagedRuntime: warnings.some((w) => w.code === EJECTS_MANAGED_RUNTIME)\n };\n}\n\n/**\n * Read what the preflight needs: the project row and its newest deployments.\n *\n * `readable: false` when either read failed. The plan lines are best effort and\n * say nothing then; the managed refusal is not — see the caller.\n */\nasync function readDeployContext(\n client: CloudClient,\n projectId: string\n): Promise<{ project?: DeployProjectRow; recent: DeploySourceRow[]; readable: boolean }> {\n try {\n const [project, recent] = await Promise.all([\n client.data.collection(\"projects\").findById(projectId),\n // The page the control plane chooses an archive from — see\n // `snapshotDeployment`.\n client.data.collection(\"deployments\").find({\n where: { project: [\"==\", projectId] },\n orderBy: [\"createdAt\", \"desc\"],\n limit: 25\n })\n ]);\n return {\n project: project as DeployProjectRow | undefined,\n recent: recent.data as DeploySourceRow[],\n readable: true\n };\n } catch {\n return { recent: [],\nreadable: false };\n }\n}\n\n/* ─── billing, asked before the build rather than after the upload ─────────── */\n\n/**\n * What the billing pre-check managed to learn about the organization paying for\n * this project. `null` means \"could not tell\", and is never a refusal.\n */\nexport interface BillingState {\n /** The billing account's plan, or null when the row could not be read. */\n plan: string | null;\n /** Whether the control plane reports a card on file, or null when it could not be asked. */\n hasPaymentMethod: boolean | null;\n /** The control plane has no Stripe configured — a local or staging control plane. */\n simulated: boolean;\n}\n\n/**\n * Whether a deploy should be refused here, before anything is built or uploaded.\n *\n * The server's gate (`ensureProjectComputeBilling`) is the authority and stays\n * the authority; this only moves the same refusal earlier in the sequence. A\n * managed deploy type-checks, builds a bundle, packs it and uploads it before it\n * triggers anything, so a 402 arrived after several minutes of work whose only\n * outcome was a discarded tarball.\n *\n * One direction only. A positive \"no card\" refuses; every other answer proceeds,\n * including every answer we could not obtain. That asymmetry is the whole design:\n * a pre-check that guesses wrong in the refusing direction blocks a deploy the\n * platform would have accepted, and there are two states this client cannot see —\n * an internal billing account (skipped server-side) and `REBASE_BYO_FREE` — so\n * \"unknown\" has to mean \"carry on and let the server decide\".\n */\nexport function billingBlocksDeploy(state: BillingState): boolean {\n // No Stripe behind the control plane: `hasPaymentMethod` is inferred from a\n // simulated setup, and a false there is not a card that is missing.\n if (state.simulated) return false;\n // Platform-internal projects skip billing entirely, server-side.\n if (state.plan === \"internal\") return false;\n return state.hasPaymentMethod === false;\n}\n\n/**\n * Ask the control plane whether the organization behind this project has a card.\n *\n * Best-effort throughout, for the reason above: every failure resolves to a\n * state that {@link billingBlocksDeploy} lets through.\n */\nexport async function readBillingState(client: CloudClient, projectId: string): Promise<BillingState> {\n const unknown: BillingState = { plan: null,\nhasPaymentMethod: null,\nsimulated: false };\n try {\n const project = (await client.data.collection(\"projects\").findById(projectId)) as\n | Record<string, unknown>\n | undefined;\n const orgRaw = project?.organization ?? project?.organizationId ?? project?.organization_id;\n const org = orgRaw == null ? \"\" : String(orgRaw);\n if (!org) return unknown;\n\n const card = await client.functions\n .invoke<{ hasPaymentMethod?: boolean; simulated?: boolean }>(\n \"stripe-billing\",\n undefined,\n { method: \"GET\",\npath: `payment-method/${encodeURIComponent(org)}` }\n )\n .catch(() => undefined);\n if (!card) return unknown;\n\n // The plan lives on the billing account, and an org that has none has no\n // plan to read — which is not \"internal\", so it does not exempt anything.\n let plan: string | null = null;\n try {\n const billingId = billingAccountIdOf(await client.data.collection(\"organizations\").findById(org));\n if (billingId != null) {\n const acct = (await client.data.collection(\"billing-accounts\").findById(billingId)) as\n | { plan?: string }\n | undefined;\n plan = typeof acct?.plan === \"string\" ? acct.plan : null;\n }\n } catch {\n // Unreadable: `plan: null`, which exempts nothing and refuses nothing\n // on its own.\n }\n\n return {\n plan,\n hasPaymentMethod: typeof card.hasPaymentMethod === \"boolean\" ? card.hasPaymentMethod : null,\n simulated: card.simulated === true\n };\n } catch {\n return unknown;\n }\n}\n\n/** Refuse a deploy the control plane would 402, before the build starts. */\nasync function requirePaymentMethod(client: CloudClient, projectId: string): Promise<void> {\n if (!billingBlocksDeploy(await readBillingState(client, projectId))) return;\n fail(\n \"This project's organization has no payment method on file, so the deploy would be refused.\",\n \"Attach a card once with `rebase cloud billing setup`, then deploy again.\",\n \"payment_required\"\n );\n}\n\n/**\n * Whether this repository's backend declares the managed runtime.\n *\n * Deliberately quiet: a directory that is not a Rebase project, or whose\n * manifest does not parse, simply does not route this way — `rebase build` is\n * where a broken manifest gets reported, and a deploy refusing on one before it\n * has even said what it is doing would be the wrong place to find out.\n */\nfunction declaresManagedRuntime(appName?: string): boolean {\n try {\n const projectRoot = findProjectRoot();\n if (!projectRoot) return false;\n const manifest = loadManifest(projectRoot).manifest;\n\n // A static app has no runtime to declare and never builds an image. It\n // is always a bundle deploy, so it takes this branch on its own — which\n // is what lets a repository with no backend at all reach the platform.\n if (appName) {\n const app = manifest.apps[appName];\n if (app?.type === \"static\") return true;\n if (app?.type === \"backend\") return app.runtime === \"managed\";\n }\n\n const backend = findBackendApp(manifest);\n // A repository declaring no backend has nothing that could be a source\n // build, so its apps are bundles by construction.\n if (!backend) return Object.keys(manifest.apps).length > 0;\n return backend.app.runtime === \"managed\";\n } catch {\n return false;\n }\n}\n\n/**\n * Every flag `rebase cloud deploy` accepts.\n *\n * Hoisted out of the `parseCloudArgs` call so that one declaration serves three\n * readers: the parser, `action-help.ts`'s page for this command, and the test\n * that holds the two to each other. A flag added here with no line in the help\n * page is a failing test rather than a flag nobody can discover.\n */\nexport const DEPLOY_FLAGS = {\n \"--no-follow\": Boolean,\n /* `--wait` is the explicit spelling of what this command already does — it\n follows the deployment to a terminal state and exits non-zero if that\n state is a failure. It exists because *asking* for that was the only way\n to find out it was the default, and because the managed-bundle path did\n not do it: that half returned as soon as the trigger was accepted, so\n every caller wrote its own poll loop against `cloud logs`. Both paths\n follow now; `--wait` is here so a script can say so, and so a reader\n looking for it in `--help` finds it rather than concluding it is absent. */\n \"--wait\": Boolean,\n /* Seconds. Bounds the follow on both paths — without it the only ceiling\n was a hardcoded 15 minutes, which is the wrong number for a CI step and\n for an overnight build alike. */\n \"--timeout\": String,\n /* Seconds. How long a followed deploy waits, after the build succeeds, for\n each app's address to answer with the new version; 0 skips the check. */\n \"--live-timeout\": String,\n \"--source\": String,\n \"--message\": String,\n \"--bundle\": Boolean,\n \"--bundle-dir\": String,\n /* Same flag `rebase build` has, for the same reason. Without it here, the\n only way to deploy a bundle without type checking was to run the build\n by hand and then point `--bundle-dir` at the result. */\n \"--skip-type-check\": Boolean,\n /* `rebase build`'s other two, which the deploy's own remedies name: a\n frontend that fails to fold says to deploy the API alone with\n `--no-static`, and a schema that fails to generate says `--skip-schema`\n for one that is hand-maintained. */\n \"--no-static\": Boolean,\n \"--skip-schema\": Boolean,\n /* Skip parsing the static apps' JavaScript before the upload. The check\n exists because a static app's files are served as they are: a syntax\n error nothing parsed went live and took the page down. This is the way\n past it for a file the check gets wrong. */\n \"--no-verify\": Boolean,\n /* Leave the managed runtime on purpose. The ONLY way to build a container\n image for a project the platform runs as managed — for the bare form and\n for `--source` alike, because neither of those says so by itself. See\n `ejectRefusal`.\n\n Spelled `--force` until 2026-09-06, which put the CLI's least reversible\n action under the same word as \"overwrite this file\". No alias: the old\n spelling is an unknown option now, so a script carrying it stops rather\n than ejecting a project on a name it no longer means. */\n \"--eject\": Boolean,\n /* Do not upload the project's source beside a backend bundle. The deploy\n is the same; what it gives up is being rebuilt by a platform upgrade,\n until a later deploy uploads the source. */\n \"--no-source\": Boolean,\n /* Deploy a bundle built on an older framework release than the project\n runs. The control plane refuses that by default (FRAMEWORK_DOWNGRADE),\n because it is usually a stale checkout, not a decision. */\n \"--allow-downgrade\": Boolean,\n /* Serve this build on an address of its own and leave production alone.\n A bundle deploy only — static apps and managed backends. See previews.ts. */\n \"--preview\": Boolean,\n /* Name the preview, so the next `--preview-name` deploy with the same name\n updates the same address. Implies `--preview`. */\n \"--preview-name\": String,\n \"-m\": \"--message\"\n} as const;\n\n/**\n * `rebase cloud deploy [app]` — its flags, and which app of this repository the\n * line named.\n *\n * Parsed through `parseCloudArgs` rather than `arg` directly, and the reason is\n * the positional. This command used to parse `rawArgs.slice(2)` permissively\n * and read `_[0]` as the app name — but `rawArgs` is the WHOLE `process.argv`,\n * so `_` opens with the command words themselves. `_[0]` was therefore the\n * literal string `\"cloud\"` on every run, which then went to `selectDeployApp`\n * and came back as:\n *\n * This repository declares no app named \"cloud\". It declares: backend, web.\n *\n * So the documented `rebase cloud deploy --bundle` failed on every project that\n * did not happen to declare an app called `cloud`, `rebase cloud deploy web`\n * could not reach `web`, and the refusal named the user's real apps — reading\n * as a fault in their `rebase.json` rather than in the CLI's own parse.\n *\n * `commandWords` counts from `cloud` itself, so `cloud deploy` is 2, and it is\n * applied to the PARSED positionals: a flag written before the group no longer\n * shifts the app name either.\n */\nexport function resolveDeployArgs(rawArgs: string[]) {\n const { flags, positionals } = parseCloudArgs({\n spec: DEPLOY_FLAGS,\n rawArgs,\n commandWords: 2, // cloud deploy\n command: \"cloud deploy\",\n maxPositionals: 1\n });\n return { flags,\nappName: positionals[0] as string | undefined };\n}\n\n/**\n * `cli.deploy` — the event that says whether anyone ever ships.\n *\n * Declared in `TelemetryEventName` from the start and recorded nowhere, so a\n * consenting user reported scaffolding, dev servers and schema pushes and never\n * the one act the product exists for.\n *\n * What it carries is deliberately thin. No project id, no app name, no\n * deployment id, no URL: those are the \"project names\" and \"URLs\" the consent\n * screen promises are never sent, and a deployment id is a durable handle on\n * somebody's infrastructure. `frameworkVersion` is *our* version, not the\n * user's data, and it is the one field that makes the rest legible — a failure\n * rate means nothing without knowing which release it is a rate for.\n */\nasync function recordDeploy(o: {\n followed: boolean;\n status: string;\n deduplicated: boolean;\n frameworkVersion?: string | null;\n startedAt: number;\n /** The project deployed; the working directory when the command has none. */\n projectRoot?: string;\n}): Promise<void> {\n await recordEvent(\"cli.deploy\", {\n followed: o.followed,\n status: o.status,\n deduplicated: o.deduplicated,\n framework_version: o.frameworkVersion ?? null,\n duration: durationBucket(Date.now() - o.startedAt)\n }, { projectRoot: o.projectRoot ?? process.cwd() });\n}\n\nexport async function deployCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const startedAt = Date.now();\n const { flags: args, appName } = resolveDeployArgs(rawArgs);\n\n // A piped deploy printed JSON until it was made to print its summary (see\n // `initOutputMode`). A script that parsed it now gets prose, so it is told,\n // on stderr, how to get the object back.\n if (!isJsonMode() && process.stdout.isTTY !== true) {\n note(chalk.gray(\"Printing the deploy summary. For the machine-readable result, pass --json.\"));\n }\n\n // Refused rather than resolved in one direction or the other: they are\n // opposite instructions, and either interpretation makes the command do\n // something the line explicitly asked it not to.\n if (args[\"--wait\"] && args[\"--no-follow\"]) {\n fail(\n \"--wait and --no-follow ask for opposite things.\",\n \"`deploy` follows by default — pass neither, or `--no-follow` to return as soon as the build is triggered.\",\n \"usage\"\n );\n }\n if (args[\"--source\"] && args[\"--no-source\"]) {\n fail(\n \"--source and --no-source ask for opposite things.\",\n \"`--source <path>` builds a container image from a directory; `--no-source` skips uploading the source \"\n + \"beside a managed bundle. Pass one.\",\n \"usage\"\n );\n }\n\n // A preview is a bundle deploy aimed at another address. The container\n // build has no preview to aim at, and `--eject` changes the production\n // project by definition — refused before anything is resolved or built.\n const preview = resolvePreviewRequest(args);\n if (preview && (args[\"--source\"] || args[\"--eject\"])) {\n fail(\n `--preview cannot be combined with ${args[\"--source\"] ? \"--source\" : \"--eject\"}: a preview is built from a managed bundle, `\n + \"and that flag builds a container image for production.\",\n \"Drop it to deploy a preview, or drop --preview to deploy production.\",\n \"usage\"\n );\n }\n if (preview && !args[\"--bundle\"] && !declaresManagedRuntime(appName)) {\n fail(\n \"Previews are built from managed bundles, and this app builds a container image.\",\n \"Declare `runtime: \\\"managed\\\"` on the backend in rebase.json to preview it, with its static apps folded in. \"\n + \"A static app cannot be previewed on its own on Rebase Cloud yet.\",\n \"preview_unsupported\"\n );\n }\n\n const { client, url } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n // Before the build, not after the upload. The managed path type-checks,\n // builds, packs and uploads a bundle before it triggers anything, so a\n // billing 402 used to arrive at the end of all of it — with nothing to show\n // for the wait but a discarded tarball.\n await requirePaymentMethod(client, projectId);\n\n // Managed bundle deploy. Builds the project into a bundle, uploads it, and\n // lets the control plane run the platform runtime with it.\n //\n // Taken either because `--bundle` said so, or because this repository's\n // backend *declares* `runtime: \"managed\"`. That declaration is the whole\n // point of the field: a project that has written down which runtime it wants\n // should not also have to remember a flag, and forgetting the flag used to\n // mean a plain `deploy` tried to build a container image and eject the\n // project — which is why the refusal further down exists.\n //\n // `--source` and `--bundle-dir` are explicit acts and still route away from\n // here — though on a project the platform *runs* as managed, routing away\n // is now where `ejectRefusal` stops them without `--eject`.\n // `rebase cloud deploy <app>` — which app of the project this repository is\n // shipping. Positional because it is the subject of the sentence, not an\n // option: a repository holding only an admin panel deploys it by name, and a\n // repository with one backend keeps saying nothing at all. Resolved by\n // `resolveDeployArgs` above, off the parsed positionals.\n\n const declaredManaged = !args[\"--source\"] && !args[\"--bundle\"] && declaresManagedRuntime(appName);\n if (args[\"--bundle\"] || declaredManaged) {\n if (args[\"--bundle\"] && args[\"--source\"]) {\n fail(\"--bundle and --source cannot be combined: one is a managed bundle, the other a source build.\");\n }\n if (declaredManaged && !isJsonMode()) {\n console.log(chalk.gray(\" rebase.json declares runtime: managed — deploying a bundle.\"));\n }\n await deployBundle({\n client,\n url,\n projectId,\n projectRef,\n bundleDir: args[\"--bundle-dir\"],\n message: args[\"--message\"],\n appName,\n skipTypeCheck: args[\"--skip-type-check\"] === true,\n skipSchema: args[\"--skip-schema\"] === true,\n noStatic: args[\"--no-static\"] === true,\n verify: args[\"--no-verify\"] !== true,\n follow: args[\"--no-follow\"] !== true,\n timeoutMs: resolveDeployTimeout(args[\"--timeout\"]),\n liveTimeoutMs: resolveLiveTimeout(args[\"--live-timeout\"]),\n uploadSource: args[\"--no-source\"] !== true,\n allowDowngrade: args[\"--allow-downgrade\"] === true,\n startedAt,\n preview\n });\n return;\n }\n\n // Everything below builds a container image from source. Say what that\n // source is before anything is uploaded or triggered, and refuse the one\n // case where the command would quietly undo the project's runtime.\n const { project, recent, readable } = await readDeployContext(client, projectId);\n const plan = planBareDeploy(project, recent, new Date());\n\n // The refusal below is the only thing between a managed project and a\n // container build: the control plane does not refuse one, and a\n // successful build moves the project to `custom`. So a read that failed\n // is not \"not managed\" — it is not knowing, and only `--eject` says the\n // answer does not matter.\n if (!readable && args[\"--eject\"] !== true) {\n fail(\n `Could not read ${projectRef}, so this deploy cannot tell whether it would eject the project from the managed runtime.`,\n \"Try again in a moment. If leaving the managed runtime is intended, pass `--eject`.\",\n \"preflight_unreadable\"\n );\n }\n\n const eject: EjectContext = {\n managed: plan.managed,\n source: Boolean(args[\"--source\"]),\n eject: args[\"--eject\"] === true\n };\n const refusal = ejectRefusal(eject, projectRef);\n if (refusal) fail(refusal.message, refusal.hint, refusal.code);\n\n // What survived that refusal is a deliberate eject, and still worth saying.\n // Warn in every output mode — `warn` writes to stderr, which is not the JSON\n // stream — and carry the same fact into the payload, the half CI reads.\n const warnings = deployWarnings(eject, projectRef);\n for (const w of warnings) warn(w.message, w.hint);\n\n if (!args[\"--source\"] && !isJsonMode()) {\n console.log(\"\");\n for (const line of plan.lines) console.log(chalk.gray(` ${line}`));\n }\n\n // Optional fly-style local source upload: `deploy --source .`\n let source: string | undefined;\n if (args[\"--source\"]) {\n const sourceDir = args[\"--source\"];\n source = await withTempArchive(\"rebase-src\", async (tarPath) => {\n await createSourceTarball(sourceDir, tarPath);\n return uploadSource(url, await uploadToken(client, url), projectId, tarPath);\n });\n }\n\n // Guarded: this is stdout, and in JSON mode stdout carries the one JSON\n // value and nothing else — an unguarded banner here put a 🚀 line in front\n // of it and broke every parser reading the result.\n if (!isJsonMode()) {\n console.log(\"\");\n console.log(` 🚀 Triggering deployment for project ${chalk.bold(projectRef)}${source ? \" from uploaded source\" : \"\"}...`);\n }\n\n const body: Record<string, unknown> = { projectId };\n if (source) body.source = source;\n if (args[\"--message\"]) body.message = args[\"--message\"];\n // `client` is what the control plane records as `triggerSource`. Omitting it\n // is why every deployment this command has ever created reads `unknown` in\n // Deployment History — `rollback` next door has always sent it.\n body.client = \"cli\";\n const frameworkVersion = resolveFrameworkVersion(args[\"--source\"] ?? process.cwd());\n if (frameworkVersion) body.frameworkVersion = frameworkVersion;\n\n let triggered: { deploymentId: string; deduplicated: boolean; hosts: DeployHost[] | undefined };\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string | number };\n deduplicated?: boolean;\n hosts?: unknown;\n }>(\"deploy\", body);\n if (!res?.deployment?.id) fail(\"Control plane did not return a deployment id.\");\n triggered = { deploymentId: String(res.deployment.id),\ndeduplicated: res.deduplicated === true,\nhosts: deployHostsFrom(res) };\n } catch (e) {\n resolveTriggerFailure(e);\n }\n const { deploymentId, deduplicated, hosts } = triggered;\n\n if (!isJsonMode()) {\n console.log(\n chalk.gray(\n deduplicated\n ? ` Deployment ${deploymentId} is already running — following it.`\n : ` Deployment ${deploymentId} created.${frameworkVersion ? ` (@rebasepro/* ${frameworkVersion})` : \"\"}`\n )\n );\n }\n\n const appsAt = (host: string | undefined): DeployedApp[] => sourceBuildApps(sourceBuildAppName(), host);\n if (args[\"--no-follow\"]) {\n await reportTriggered({\n client,\n url,\n projectId,\n deploymentId,\n appsAt,\n registeredHosts: hosts,\n headline: \"\",\n json: { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: false,\n...warningPayload(warnings) }\n });\n await recordDeploy({ followed: false, status: \"not_followed\", deduplicated, frameworkVersion, startedAt });\n return;\n }\n\n if (!isJsonMode()) {\n console.log(chalk.gray(\" Streaming build logs (Ctrl-C to stop watching — the build keeps running):\"));\n console.log(\"\");\n }\n\n // In JSON mode the build log is not streamed: interleaving it with the\n // result object would make neither parseable. The deploy is still followed\n // to completion — a caller waiting on the exit code still waits — and the\n // one object printed at the end carries the outcome.\n //\n // Recorded as the follow ends, whatever it ends in: a failed build exits\n // non-zero from inside the follow, and recording after it only ever\n // recorded successes.\n const { status } = await streamBuildLogs(client, deploymentId, {\n quiet: isJsonMode(),\n timeoutMs: resolveDeployTimeout(args[\"--timeout\"]),\n projectId,\n url,\n announce: false,\n failedApps: appsAt(undefined).map(a => a.name),\n onTerminal: (ended) => recordDeploy({ followed: true, status: ended, deduplicated, frameworkVersion, startedAt })\n });\n const appKey = await mintMissingAppKey({ url, projectId });\n reportMintedAppKey(appKey);\n await reportDeployed({\n undo: ROLLBACK_HINT,\n client,\n url,\n projectId,\n projectRef,\n deploymentId,\n startedAt,\n liveTimeoutMs: resolveLiveTimeout(args[\"--live-timeout\"]),\n appsAt,\n registeredHosts: hosts,\n json: { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: true,\nstatus,\n...(appKey ? { appKey: appKeyPayload(appKey) } : {}),\n...warningPayload(warnings) }\n });\n}\n\n/** The backend this repository declares, for naming a source build in its summary. */\nfunction sourceBuildAppName(): string | undefined {\n try {\n const projectRoot = findProjectRoot();\n return projectRoot ? findBackendApp(loadManifest(projectRoot).manifest)?.name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * `--live-timeout <seconds>`: how long a deploy waits for the new version to\n * answer before saying it could not confirm it. `0` skips the check. Default 60.\n *\n * Its own reader rather than `resolveTimeoutMs`, which refuses 0 — right for a\n * follow, where 0 would mean \"give up at once\", and wrong here, where it is the\n * documented way to say \"do not check\".\n */\nexport function resolveLiveTimeout(value: string | undefined): number {\n if (value === undefined) return DEFAULT_LIVE_TIMEOUT_MS;\n const seconds = Number(value);\n if (!Number.isFinite(seconds) || seconds < 0) {\n fail(\n `--live-timeout takes a number of seconds, or 0 to skip the check (got \"${value}\").`,\n \"Run `rebase cloud deploy --help`.\",\n \"usage\"\n );\n }\n return seconds * 1000;\n}\n\n/** `--timeout <seconds>` for a deploy, or the 15-minute default. */\nexport function resolveDeployTimeout(value: string | undefined): number {\n return resolveTimeoutMs(value, { fallbackMs: POLL_TIMEOUT_MS,\ncommand: \"cloud deploy\" });\n}\n\n/**\n * Turn a failed trigger into an exit that says why.\n *\n * A 409 is a refusal, whoever holds the lock. The control plane answers a\n * replay of this very trigger — the same user sending the same uploaded\n * archive — with a 200 carrying `deduplicated: true`, which the success path\n * follows. So the deployment a 409 names is always a different one, and\n * `mine` means only that the same user started it: an earlier deploy, building\n * earlier code. Following it reported that deploy's verdict as this one's, and\n * the code just uploaded was never built.\n *\n * The refusal names the blocker, because \"which one, since when, from where\"\n * is the difference between an actionable refusal and a dead end.\n */\nfunction resolveTriggerFailure(e: unknown, fallback = \"Failed to trigger deployment\"): never {\n const err = e as {\n status?: number;\n message?: string;\n code?: string;\n details?: { deployment?: BlockingDeployment };\n };\n\n if (err?.status === 409) {\n const blocking = err.details?.deployment;\n const where = blocking?.triggerSource && blocking.triggerSource !== \"unknown\"\n ? ` from the ${blocking.triggerSource}`\n : \"\";\n const who = blocking?.mine ? \", triggered by you\" : where ? \", triggered\" : \"\";\n // Older control planes send a bare 409 with no `details`; the message\n // then stays the honest general one rather than a fabricated id.\n fail(\n blocking?.id\n ? `Deployment ${blocking.id} is already in progress for this project${who}${where}` +\n `${blocking.createdAt ? ` at ${fmtDate(blocking.createdAt)}` : \"\"}.`\n : \"A deployment is already in progress for this project.\",\n blocking?.id\n ? `Nothing was deployed. Wait for it (\\`rebase cloud logs -f\\`) or stop it with \\`rebase cloud cancel ${blocking.id}\\`, then deploy again.`\n : \"Nothing was deployed. Wait for it (`rebase cloud logs -f`), then deploy again.\",\n \"deploy_in_progress\"\n );\n }\n\n if (err?.status === 402) {\n // Billing gate: no card on file, card declined, or needs auth.\n fail(\n err.message || \"Payment required before deploying.\",\n \"Attach a card once with `rebase cloud billing setup`, then deploy again.\",\n \"payment_required\"\n );\n }\n\n const refusal = intakeRefusal(e);\n if (refusal) fail(refusal.message, refusal.hint, refusal.code);\n\n reportError(e, fallback);\n}\n\n/**\n * Whether the project's owner turned platform rebuilds off.\n *\n * Only an explicit `false` counts: a project row that predates the switch, or\n * one that could not be read, is on — which is the default, and the control\n * plane refuses an upload it should not have anyway.\n */\nexport async function platformRebuildsOff(client: CloudClient, projectId: string): Promise<boolean> {\n try {\n const row: unknown = await client.data.collection(\"projects\").findById(projectId);\n return typeof row === \"object\" && row !== null && \"platformRebuilds\" in row && row.platformRebuilds === false;\n } catch {\n return false;\n }\n}\n\n/** The intake code for a bundle built on an older framework release than the project runs. */\nexport const FRAMEWORK_DOWNGRADE = \"FRAMEWORK_DOWNGRADE\";\n\n/**\n * An intake refusal, which is a decision about what was deployed rather than a\n * transport error — or undefined for anything else.\n *\n * It carries a stable code in `details.intakeCode` and usually a remedy in\n * `details.hint`, and both used to be discarded: the deploy printed `Failed to\n * trigger deployment (400): …` and threw the hint away. The managed path, where\n * bundles are refused, never looked for either. Both paths answer through this\n * now, in the three-argument shape `fail` takes, so `--json` carries the code\n * and a person sees the fix.\n *\n * A downgrade gets one more line, because its two remedies are both in this\n * CLI: move the project forward, or say the step back is meant.\n */\nexport function intakeRefusal(e: unknown): { message: string; hint: string; code: string } | undefined {\n if (typeof e !== \"object\" || e === null) return undefined;\n const status = \"status\" in e && typeof e.status === \"number\" ? e.status : undefined;\n const details = \"details\" in e && typeof e.details === \"object\" && e.details !== null ? e.details : undefined;\n const code = details && \"intakeCode\" in details && typeof details.intakeCode === \"string\" ? details.intakeCode : undefined;\n if (status === undefined || status < 400 || status >= 500 || !code) return undefined;\n\n const message = \"message\" in e && typeof e.message === \"string\" && e.message !== \"\" ? e.message : \"This bundle was refused.\";\n const serverHint = details && \"hint\" in details && typeof details.hint === \"string\" && details.hint !== \"\"\n ? details.hint\n : undefined;\n if (code === FRAMEWORK_DOWNGRADE) {\n const remedy = \"Run `rebase upgrade` to move this project's @rebasepro packages forward and deploy again, \"\n + \"or pass `--allow-downgrade` to deploy the older release on purpose.\";\n return { message, hint: serverHint ? `${serverHint}\\n ${remedy}` : remedy, code };\n }\n return { message, hint: serverHint ?? \"Run `rebase cloud compute` to see what this project reserves.\", code };\n}\n\n/**\n * Poll a deployment record and print new log output as it arrives. Returns the\n * terminal status; a non-success still exits non-zero, as it always has.\n *\n * `quiet` follows without printing — JSON mode, where the log stream would\n * corrupt the one object the caller is parsing.\n */\n/**\n * The host a project answers on — the same one `cloud status` prints, resolved\n * the same way, so the two commands cannot disagree about where the app is.\n *\n * `undefined` on any failure: the control plane may not report a base domain,\n * and a deploy that just succeeded must not be reported as anything else\n * because a cosmetic lookup did not.\n */\nexport async function deployedUrl(\n client: CloudClient,\n opts: { projectId?: string; url?: string }\n): Promise<string | undefined> {\n if (!opts.projectId || !opts.url) return undefined;\n try {\n const [project, baseDomain] = await Promise.all([\n client.data.collection(\"projects\").findById(opts.projectId),\n fetchTenantBaseDomain(client, opts.url)\n ]);\n if (!project) return undefined;\n return projectHost(project as { subdomain?: string; host?: string }, baseDomain);\n } catch {\n return undefined;\n }\n}\n\n/**\n * The line an in-progress build keeps rewriting at the end of its log, to prove\n * to the control plane that it is still alive.\n *\n * The control plane's own format — `HEARTBEAT_MARKER` and `heartbeatSuffix` in\n * its `functions/deploy.ts` — which appends `\\n<marker><ISO time>\\n` to the log\n * on every write and every 30 seconds, and drops it on the terminal write.\n */\nexport const BUILD_HEARTBEAT_MARKER = \"⏳ Build in progress — control-plane heartbeat \";\n\n/**\n * A deployment's log without its trailing heartbeat line: the build log itself.\n *\n * Only a heartbeat that is the last line is one. The same text anywhere else is\n * the build quoting it.\n */\nexport function withoutHeartbeat(logs: string): string {\n const at = logs.lastIndexOf(`\\n${BUILD_HEARTBEAT_MARKER}`);\n if (at < 0) return logs;\n const newline = logs.indexOf(\"\\n\", at + 1);\n return newline === -1 || newline === logs.length - 1 ? logs.slice(0, at) : logs;\n}\n\n/**\n * What to print of a deployment's log, given everything printed so far.\n *\n * The `logs` column is not append-only. Its heartbeat line is rewritten at the\n * end on every write, and a failed static deploy replaces its whole log with\n * one line. Diffing the raw column by length therefore cut the start off every\n * new chunk — as many characters as the heartbeat that had been there — and\n * printed heartbeat fragments in their place: a failed managed deploy lost the\n * first half of its reason.\n *\n * So the heartbeat is stripped first, and the log printed so far is compared\n * with the log now. When it has only grown, the new text is printed. When it\n * was rewritten, printing resumes from the start of the first line that\n * differs, on a line of its own.\n */\nexport function nextLogChunk(printed: string, rowLogs: string): { chunk: string; printed: string } {\n const logs = withoutHeartbeat(rowLogs);\n if (logs.startsWith(printed)) return { chunk: logs.slice(printed.length), printed: logs };\n // Shorter and already printed: nothing new to say.\n if (printed.startsWith(logs)) return { chunk: \"\", printed };\n\n let same = 0;\n while (same < logs.length && logs[same] === printed[same]) same++;\n const lineStart = logs.lastIndexOf(\"\\n\", same - 1) + 1;\n return { chunk: `${printed.endsWith(\"\\n\") ? \"\" : \"\\n\"}${logs.slice(lineStart)}`, printed: logs };\n}\n\nasync function streamBuildLogs(\n client: CloudClient,\n deploymentId: string,\n opts: {\n quiet?: boolean;\n timeoutMs?: number;\n projectId?: string;\n url?: string;\n /**\n * Print \"Deployment succeeded\" and the URL on success. On by default\n * (`cloud logs --follow`); `deploy` turns it off and prints its own\n * summary instead, which says the same and more.\n */\n announce?: boolean;\n /** The apps this deployment ships, named in the one-line failure. */\n failedApps?: string[];\n /**\n * Called once with the state the follow ended in (a terminal status, or\n * `timeout`) before anything else happens, a non-zero exit included.\n */\n onTerminal?: (status: string) => Promise<void>;\n /**\n * How to undo this deploy, printed under the verdict when it succeeded.\n * A deploy that has just gone live is the moment somebody finds out it\n * should not have, and \"how do I go back\" was a question with no answer\n * in sight.\n */\n undo?: string;\n /**\n * Where the deployment row lives: `deployments`, or a preview's\n * `preview-deployments`. See `PREVIEW_DEPLOYMENTS_COLLECTION`.\n */\n collection?: string;\n /**\n * A preview being followed. Its address is printed on success instead\n * of the project's, which is production's and did not change.\n */\n preview?: Preview;\n } = {}\n): Promise<{ status: string; logs: string }> {\n const quiet = opts.quiet === true;\n const timeoutMs = opts.timeoutMs ?? POLL_TIMEOUT_MS;\n // Where the rest of this build's log is. Bare `rebase cloud logs` reads\n // production's newest deployment, never a preview's.\n const logsCommandHint = opts.preview\n ? `\\`rebase cloud logs --preview ${opts.preview.name} -f\\``\n : \"`rebase cloud logs`\";\n let printed = \"\";\n const started = Date.now();\n /** When the current run of failed status reads began. */\n let unreadableSince: number | undefined;\n const stopIfTimedOut = async (): Promise<void> => {\n if (Date.now() - started <= timeoutMs) return;\n await opts.onTerminal?.(\"timeout\");\n if (!quiet) console.log(\"\");\n fail(\n `Timed out after ${Math.round(timeoutMs / 1000)}s waiting for the build to finish.`,\n `The deployment may still be running — check ${logsCommandHint}.`,\n \"timeout\"\n );\n };\n\n for (;;) {\n let dep: Deployment | undefined;\n try {\n dep = (await client.data.collection(opts.collection ?? \"deployments\").findById(deploymentId)) as Deployment | undefined;\n unreadableSince = undefined;\n } catch (e) {\n // A read that failed says nothing about the build. A control plane\n // mid-rollout answers a request or two with a 502, and a connection\n // drops; ending the follow there reported a deploy that went on to\n // succeed as a failure, through the exit code that is its verdict.\n // So those are read again, for a while. A refusal is not transient.\n if (!transientReadFailure(e)) reportError(e, \"Failed to read deployment status\");\n unreadableSince ??= Date.now();\n if (Date.now() - unreadableSince > UNREADABLE_STATUS_MS) {\n await opts.onTerminal?.(\"status_unreadable\");\n fail(\n `Could not read deployment ${deploymentId}'s status for over a minute: ` +\n `${e instanceof Error ? e.message : String(e)}`,\n `The deployment may still be running — check ${logsCommandHint}.`,\n \"status_unreadable\"\n );\n }\n await stopIfTimedOut();\n await sleep(POLL_INTERVAL_MS);\n continue;\n }\n if (!dep) fail(`Deployment ${deploymentId} disappeared.`, undefined, \"not_found\");\n\n const next = nextLogChunk(printed, dep.logs ?? \"\");\n if (!quiet && next.chunk !== \"\") process.stdout.write(next.chunk);\n printed = next.printed;\n\n if (dep.status && dep.status !== \"deploying\") {\n await opts.onTerminal?.(dep.status);\n if (dep.status !== \"success\") {\n const logs = withoutHeartbeat(dep.logs ?? \"\");\n const line = failureLine({ apps: opts.failedApps ?? [], status: dep.status, deploymentId, logs });\n if (quiet) {\n // The failure still has to be reportable, and in JSON mode\n // the build log is the only place that says why.\n printJson({\n error: {\n message: line,\n code: \"deploy_failed\",\n status: null,\n deploymentId,\n apps: opts.failedApps ?? [],\n reason: failureReason(logs) ?? null,\n hint: failureHint(deploymentId, opts.preview?.name),\n logs\n }\n });\n process.exit(1);\n }\n // One line that says which app and why, under the log it came\n // from — a person scrolling up through a build log to find the\n // reason was the whole failure report before.\n console.log(\"\");\n console.log(chalk.bold.red(` ✗ ${line}`));\n console.log(chalk.gray(` ${failureHint(deploymentId, opts.preview?.name)}`));\n console.log(\"\");\n process.exit(1);\n }\n if (!quiet && opts.announce !== false) {\n console.log(\"\");\n if (opts.preview) {\n console.log(chalk.bold.green(\" ✓ Preview deployed\"));\n for (const line of previewLines(opts.preview)) console.log(` ${line}`);\n console.log(\"\");\n return { status: dep.status, logs: withoutHeartbeat(dep.logs ?? \"\") };\n }\n console.log(chalk.bold.green(\" ✓ Deployment succeeded\"));\n // The URL. A deploy that says only \"succeeded\" leaves the one\n // thing the whole command was for — the address the app now\n // answers on — to a second command (`cloud status`), and the\n // person who just watched a build finish has to go and ask.\n //\n // Best-effort and silent when it cannot be resolved: a URL is\n // not worth failing a successful deploy over, and a fabricated\n // host is worse than none.\n const url = await deployedUrl(client, opts);\n if (url) console.log(` ${chalk.cyan(`https://${url}`)}`);\n if (opts.undo) console.log(chalk.gray(` ${opts.undo}`));\n console.log(\"\");\n }\n return { status: dep.status, logs: withoutHeartbeat(dep.logs ?? \"\") };\n }\n\n await stopIfTimedOut();\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\n/**\n * Whether a failed status read is worth reading again: no answer at all (the\n * connection failed), or one saying the control plane could not answer now.\n * Anything else — a 401, a 403, a 404 — will say the same next time.\n */\nfunction transientReadFailure(e: unknown): boolean {\n const status = typeof e === \"object\" && e !== null && \"status\" in e && typeof e.status === \"number\"\n ? e.status\n : undefined;\n return status === undefined || status === 408 || status === 429 || status >= 500;\n}\n\n/** What `rebase cloud logs` parses. Its page pairs against this. */\nexport const LOGS_FLAGS = {\n \"--runtime\": Boolean,\n \"--follow\": Boolean,\n \"-f\": \"--follow\",\n \"--since\": String,\n \"--tail\": Number,\n \"--previous\": Boolean,\n \"--grep\": String,\n \"--level\": String,\n // Boolean, with the preview named by the one positional: `deploy --preview`\n // is a boolean too, and the dispatcher's value-flag list has to be one list\n // (`value-flags.test.ts`) — a value `--preview` would eat `deploy`'s app name.\n \"--preview\": Boolean\n} as const;\n\n/** The flags that read the running app's log, and mean nothing for a build log. */\nconst RUNTIME_ONLY_FLAGS = [\"--since\", \"--tail\", \"--previous\", \"--grep\", \"--level\"] as const;\n\nexport async function logsCommand(rawArgs: string[], projectRef: string): Promise<void> {\n // Strict: `--folow` used to be dropped, so a caller that asked to follow\n // the log got one snapshot and an exit code.\n const { flags: args, positionals } = parseCloudArgs({\n spec: LOGS_FLAGS,\n rawArgs,\n commandWords: 2, // cloud logs\n command: \"cloud logs\",\n maxPositionals: 1 // the preview, after --preview\n });\n const previewRef = positionals[0];\n if (previewRef !== undefined && !args[\"--preview\"]) {\n fail(\n `\\`rebase cloud logs ${previewRef}\\`: a name here is a preview's, and needs --preview.`,\n `\\`rebase cloud logs --preview ${previewRef}\\` reads that preview's log.`,\n \"usage\"\n );\n }\n\n // Checked before anything is read, so a typo is a usage error rather than\n // a log that silently ignored half of what was asked.\n if (!args[\"--runtime\"]) {\n const stray = RUNTIME_ONLY_FLAGS.filter((f) => args[f] !== undefined);\n if (stray.length > 0) {\n fail(\n `${stray.join(\", \")} ${stray.length === 1 ? \"reads\" : \"read\"} the running app's log; add --runtime.`,\n \"`rebase cloud logs` alone is the build log.\",\n \"usage\"\n );\n }\n }\n if (args[\"--previous\"] && args[\"--follow\"]) {\n fail(\n \"--previous reads a container instance that has already stopped, so there is nothing to follow.\",\n \"Drop --follow, or --previous to follow the running instance.\",\n \"usage\"\n );\n }\n const since = args[\"--since\"] === undefined ? undefined : parseSinceFlag(args[\"--since\"]);\n if (since === null) {\n fail(`--since must be a duration like 30s, 5m or 1h, or an RFC3339 time; received \"${args[\"--since\"]}\".`, undefined, \"usage\");\n }\n let tail: TailLimit | undefined;\n if (args[\"--tail\"] !== undefined) {\n if (!Number.isInteger(args[\"--tail\"]) || args[\"--tail\"] <= 0) {\n fail(`--tail must be a positive whole number of lines; received \"${args[\"--tail\"]}\".`, undefined, \"usage\");\n }\n tail = resolveTail(args[\"--tail\"], true);\n }\n const level = args[\"--level\"] === undefined ? undefined : parseLevelFlag(args[\"--level\"]);\n // Compiled now, so a broken pattern is refused before any request.\n const filter = recordFilter({ grep: args[\"--grep\"], level });\n const filtered = args[\"--grep\"] !== undefined || level !== undefined;\n\n const { client, url } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n const preview = args[\"--preview\"]\n ? await resolvePreviewRef(client, projectId, previewRef)\n : undefined;\n\n if (args[\"--runtime\"]) {\n if (preview && preview.backend === \"production\") {\n fail(\n `Preview \"${preview.name}\" is a static app: it runs no server of its own and calls the production backend.`,\n `Its build log is \\`rebase cloud logs --preview ${preview.name}\\`; production's runtime log is \\`rebase cloud logs --runtime\\`.`,\n \"preview_static\"\n );\n }\n const query: RuntimeLogsQuery = {\n ...(since ?? {}),\n ...(tail ? { tailLines: tail.applied } : {}),\n ...(args[\"--previous\"] ? { previous: true } : {}),\n ...(preview ? { preview: preview.name } : {})\n };\n const subject = preview ? `preview ${preview.name}` : `project ${projectRef}`;\n if (tail?.note) note(chalk.yellow(tail.note));\n if (args[\"--follow\"]) {\n await followRuntime(client, projectId, { query, filter, subject, preview: preview?.name });\n return;\n }\n let page: RuntimeLogsPage;\n try {\n page = await fetchRuntimeLogsPage(client, projectId, query);\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n const records = parseRecords(page.logs).filter(filter);\n const logs = filtered ? records.map((r) => r.raw).join(\"\\n\") : (page.logs ?? null);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 📄 Runtime logs — ${subject}`) + (args[\"--previous\"] ? chalk.gray(\" previous instance\") : \"\"));\n console.log(\"\");\n printRuntimePodStates(page, preview?.name);\n if (records.length > 0) for (const r of records) console.log(paintLine(r));\n else console.log(chalk.gray(filtered && page.logs ? \" (no line matches)\" : \" (no logs)\"));\n console.log(\"\");\n },\n {\n runtime: true,\n preview: preview?.name ?? null,\n logs,\n pods: page.pods ?? [],\n state: page.state ?? null,\n message: page.message ?? null,\n truncated: page.truncated === true,\n // Where a script resumes from: pass it back as --since.\n nextSinceTime: page.nextSinceTime ?? null\n }\n );\n return;\n }\n\n if (preview) {\n await previewBuildLogs(client, preview, { follow: args[\"--follow\"] === true, projectId, url });\n return;\n }\n\n // Build logs: latest deployment, optionally follow if still running.\n //\n // In JSON mode the page is one object, `{ deploymentId, status, logs }`: it\n // used to be the human page whatever the mode, so `cloud logs --json | jq`\n // failed on every run. The log is the build's, without the heartbeat line a\n // running build keeps rewriting at its end.\n try {\n const dep = (await latestDeployment(client, projectId)) as Deployment | undefined;\n if (!dep) {\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.gray(\" No deployments yet for this project.\"));\n console.log(\"\");\n },\n { deploymentId: null,\nstatus: null,\nlogs: null }\n );\n return;\n }\n\n const deploymentId = String(dep.id);\n if (args[\"--follow\"] && dep.status === \"deploying\") {\n if (!isJsonMode()) {\n console.log(\"\");\n console.log(chalk.bold(` 📄 Build logs — deployment ${dep.id}`) + ` ${colorStatus(dep.status)}`);\n console.log(\"\");\n }\n // Hand off to the streamer, which prints from the top and tails live.\n const { status, logs } = await streamBuildLogs(client, deploymentId, { quiet: isJsonMode(),\nprojectId,\nurl });\n emit(() => {}, { deploymentId,\nstatus,\nlogs });\n return;\n }\n\n const logs = dep.logs == null ? null : withoutHeartbeat(dep.logs);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 📄 Build logs — deployment ${dep.id}`) + ` ${colorStatus(dep.status)}`);\n console.log(\"\");\n console.log(logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n },\n { deploymentId,\nstatus: dep.status ?? null,\nlogs }\n );\n } catch (e) {\n reportError(e, \"Failed to fetch build logs\");\n }\n}\n\n\n/* ═══════════════════════════════════════════════════════════════\n cloud logs --preview / --runtime helpers\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The preview `--preview <ref>` names: by name, or by the id of the\n * deployment that built it (what a failed preview deploy prints). With no ref,\n * the project's only preview — and when there are several, their names.\n */\nasync function resolvePreviewRef(client: CloudClient, projectId: string, ref: string | undefined): Promise<Preview> {\n let res: unknown;\n try {\n res = await client.functions.invoke<unknown>(PREVIEWS_FUNCTION, undefined, { method: \"GET\", path: projectId });\n } catch (e) {\n if (isPreviewsUnavailable(e)) {\n fail(\"This control plane does not serve preview deployments.\", undefined, \"previews_unavailable\");\n }\n reportError(e, \"Failed to list previews\");\n }\n const rows = typeof res === \"object\" && res !== null && \"previews\" in res && Array.isArray(res.previews) ? res.previews : [];\n const previews = rows.map(previewFrom).filter((p): p is Preview => p !== null);\n if (ref === undefined) {\n if (previews.length === 1) return previews[0];\n fail(\n previews.length === 0 ? \"This project has no previews.\" : \"Which preview? This project has several.\",\n previews.length === 0\n ? \"Make one with `rebase cloud deploy --preview`.\"\n : `Name one: ${previews.map((p) => `\\`rebase cloud logs --preview ${p.name}\\``).join(\", \")}.`,\n previews.length === 0 ? \"not_found\" : \"usage\"\n );\n }\n const wanted = ref.trim();\n const found = previews.find((p) => p.name === wanted.toLowerCase()) ?? previews.find((p) => p.deploymentId === wanted);\n if (!found) {\n fail(\n `No preview named \"${wanted}\" on this project.`,\n previews.length > 0\n ? `Its previews: ${previews.map((p) => p.name).join(\", \")}.`\n : \"It has none. Make one with `rebase cloud deploy --preview`.\",\n \"not_found\"\n );\n }\n return found;\n}\n\n/** A preview's build log: printed, or followed while it is still building. */\nasync function previewBuildLogs(\n client: CloudClient,\n preview: Preview,\n opts: { follow: boolean; projectId: string; url: string }\n): Promise<void> {\n if (!preview.deploymentId) {\n fail(`Preview \"${preview.name}\" has no deployment yet.`, undefined, \"not_found\");\n }\n const deploymentId = preview.deploymentId;\n try {\n const dep = (await client.data.collection(PREVIEW_DEPLOYMENTS_COLLECTION).findById(deploymentId)) as Deployment | undefined;\n if (!dep) fail(`Preview \"${preview.name}\"'s deployment ${deploymentId} is gone.`, undefined, \"not_found\");\n const heading = (): void => {\n console.log(\"\");\n console.log(chalk.bold(` 📄 Build logs — preview ${preview.name}, deployment ${deploymentId}`) + ` ${colorStatus(dep.status)}`);\n console.log(\"\");\n };\n if (opts.follow && dep.status === \"deploying\") {\n if (!isJsonMode()) heading();\n const { status, logs } = await streamBuildLogs(client, deploymentId, {\n quiet: isJsonMode(),\n projectId: opts.projectId,\n url: opts.url,\n collection: PREVIEW_DEPLOYMENTS_COLLECTION,\n preview\n });\n emit(() => {}, { preview: preview.name, deploymentId, status, logs });\n return;\n }\n const logs = dep.logs == null ? null : withoutHeartbeat(dep.logs);\n emit(\n () => {\n heading();\n console.log(logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n },\n { preview: preview.name, deploymentId, status: dep.status ?? null, logs }\n );\n } catch (e) {\n reportError(e, \"Failed to fetch the preview's build log\");\n }\n}\n\n/** The pods that are not plainly running, and what to do about each. */\nfunction printRuntimePodStates(page: RuntimeLogsPage, preview?: string): void {\n if (page.state === \"no_pods\") {\n console.log(chalk.yellow(` ${page.message ?? \"No pods are running for this project.\"}`));\n console.log(\"\");\n return;\n }\n if (page.state === \"error\" && page.message) {\n console.log(chalk.red(` ${page.message}`));\n console.log(\"\");\n return;\n }\n let any = false;\n for (const p of page.pods ?? []) {\n if (p.state === \"ok\") continue;\n any = true;\n const line = describeEvent({ event: \"pod_state\", pod: p.pod, state: p.state, message: p.message ?? null }, { preview });\n if (line) console.log(chalk.yellow(` ${line}`));\n }\n if (any) console.log(\"\");\n}\n\n/** Resolve after `ms`, or at once when `signal` aborts. Never keeps the process alive past an abort. */\nfunction abortableSleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/**\n * `cloud logs --runtime --follow`: poll until Ctrl-C, then exit 0.\n *\n * In JSON mode stdout is NDJSON — one compact object per line, `{\"type\":\"line\",\n * \"ts\",\"pod\",\"text\"}` for a log line and `{\"type\":\"event\",\"event\",…}` for a pod\n * starting, restarting or going, a reconnect — so a reader can act on each as\n * it arrives. On a terminal the events are narration, on stderr.\n */\nasync function followRuntime(\n client: CloudClient,\n projectId: string,\n opts: {\n query: RuntimeLogsQuery;\n filter: (rec: LogRecord) => boolean;\n subject: string;\n preview?: string;\n }\n): Promise<void> {\n const json = isJsonMode();\n const controller = new AbortController();\n const onSigint = (): void => controller.abort();\n // `once`: a second Ctrl-C while a request is in flight kills the process\n // the ordinary way instead of queueing another stop.\n process.once(\"SIGINT\", onSigint);\n\n const sink: FollowSink = json\n ? {\n line: (r) => process.stdout.write(`${JSON.stringify({ type: \"line\", ts: r.ts, pod: r.pod, text: r.text })}\\n`),\n event: (e) => process.stdout.write(`${JSON.stringify({ type: \"event\", ...e })}\\n`)\n }\n : {\n line: (r) => console.log(paintLine(r)),\n event: (e) => {\n const text = describeEvent(e, { preview: opts.preview });\n if (text) note(chalk.gray(text), \"\");\n }\n };\n\n if (!json) {\n console.log(\"\");\n console.log(chalk.bold(` 📄 Runtime logs — ${opts.subject}`) + chalk.gray(\" following, Ctrl-C to stop\"));\n console.log(\"\");\n }\n try {\n await followRuntimeLogs(\n {\n fetch: (q) => fetchRuntimeLogsPage(client, projectId, q),\n sleep: abortableSleep,\n signal: controller.signal,\n sink,\n now: () => performance.now(),\n isTransient: transientReadFailure\n },\n { initial: opts.query, filter: opts.filter }\n );\n } catch (e) {\n reportError(e, \"Failed to follow runtime logs\");\n } finally {\n process.removeListener(\"SIGINT\", onSigint);\n }\n if (!json) note(chalk.gray(\"Stopped.\"), \"\");\n}\n\n","/**\n * `rebase cloud orgs` — list / create / members / invites.\n *\n * Members: list, invite by email, remove, change a role. Inviting goes through\n * the control plane's `invites` function, which always opens an invitation —\n * nobody joins an organization until they accept, an existing account\n * included: a link, valid 7 days, that only an account which has verified that\n * address can accept. Nobody is invited as owner; an owner promotes them once\n * they have joined. The link is printed, because the control plane may send no email;\n * the output says whether it did. Inviting takes a `rebase cloud login`\n * session — a token cannot hand out access to an organization.\n */\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n parseCloudArgs,\n getContextOrg,\n setContextOrg,\n colorStatus,\n success,\n fail,\n reportError,\n emit,\n printGroupHelp,\n note,\n requireInteractive,\n cloudRows,\n requireCloudRow,\n requireSessionClient,\n confirmDestructive,\n warn,\n type CloudClient\n} from \"./context\";\n\ninterface OrgRow {\n id: string | number;\n name?: string;\n slug?: string;\n description?: string;\n createdAt?: string;\n}\n\nexport async function orgsCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n switch (subcommand) {\n case \"list\":\n case undefined:\n await listOrgs(rawArgs);\n break;\n case \"create\":\n await createOrg(rawArgs);\n break;\n case \"members\":\n await membersCommand(rawArgs);\n break;\n case \"invites\":\n await invitesCommand(rawArgs);\n break;\n case \"--help\":\n printOrgsHelp();\n break;\n default:\n fail(`Unknown orgs command: ${subcommand}`, \"Run `rebase cloud orgs --help`.\", \"unknown_command\");\n }\n}\n\nasync function listOrgs(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud orgs\",\nmaxPositionals: 0 });\n const { client, url } = await requireClient(rawArgs);\n try {\n const orgs = cloudRows<OrgRow>((await client.data.collection(\"organizations\").find({ limit: 100 })).data);\n const active = getContextOrg(url);\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(\" 🏢 Organizations\"));\n console.log(\"\");\n if (orgs.length === 0) {\n console.log(chalk.gray(\" You are not a member of any organization.\"));\n console.log(\"\");\n return;\n }\n for (const o of orgs) {\n const marker = String(o.id) === active ? chalk.green(\" ●\") : \" \";\n console.log(`${marker}${chalk.bold(o.name ?? \"(unnamed)\")} ${chalk.gray(`[${o.id}]`)}${o.slug ? chalk.gray(` ${o.slug}`) : \"\"}`);\n }\n console.log(\"\");\n // The legend explains the ● glyph, which only exists in the\n // human rendering — `active: true` needs no legend.\n note(chalk.gray(\"● = active organization. Switch with `rebase cloud use <id>`.\"));\n console.log(\"\");\n },\n {\n activeOrg: active ?? null,\n organizations: orgs.map((o) => ({\n id: String(o.id),\n name: o.name ?? null,\n slug: o.slug ?? null,\n active: String(o.id) === active\n }))\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list organizations\");\n }\n}\n\n/** What `rebase cloud orgs create` parses. Its page is the group's own. */\nexport const CREATE_ORG_FLAGS = {\n \"--name\": String,\n \"--slug\": String,\n \"-n\": \"--name\"\n} as const;\n\nasync function createOrg(rawArgs: string[]): Promise<void> {\n // Strict: `--nmae \"Acme\"` used to be dropped, and the command then prompted\n // for a name — or, off a terminal, refused for one that had been given.\n const { flags: args } = parseCloudArgs({\n spec: CREATE_ORG_FLAGS,\n rawArgs,\n commandWords: 3, // cloud orgs create\n command: \"cloud orgs\",\n maxPositionals: 0\n });\n const { client, url } = await requireClient(rawArgs);\n\n const prompts: Array<{ type: \"input\"; name: string; message: string }> = [];\n if (!args[\"--name\"]) {\n requireInteractive(\"an organization name\", \"--name <name>\");\n prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Organization name:\" });\n }\n const answers = prompts.length\n ? await inquirer.prompt(prompts)\n : {};\n\n const name = (args[\"--name\"] || (answers as { name?: string }).name || \"\").trim();\n if (!name) fail(\"Organization name is required.\", \"Pass `--name <name>`.\", \"input_required\");\n const slug = (args[\"--slug\"] || slugify(name)).trim();\n\n try {\n const created = requireCloudRow<OrgRow>(await client.data.collection(\"organizations\").create({\n name,\n slug,\n createdAt: new Date().toISOString()\n }), \"organization\");\n setContextOrg(url, String(created.id));\n success(`Created organization ${chalk.bold(name)} and set it active`);\n emit(() => {}, {\n success: true,\n id: String(created.id),\n name,\n slug,\n setActive: true\n });\n } catch (e) {\n reportError(e, \"Failed to create organization\");\n }\n}\n\n/** A membership row with the person's email, when the caller may read it. */\ninterface MemberRow {\n id: string;\n userId: string | null;\n email: string | null;\n role: string | null;\n}\n\n/** An open invitation, as the control plane lists it. Never the link. */\nexport interface CliInvite {\n id: string;\n email: string;\n role: string;\n invitedBy: { userId: string | null; email: string | null };\n expiresAt: string;\n expired: boolean;\n createdAt: string | null;\n}\n\ntype EmailDelivery = { sent: true } | { sent: false; reason: \"not_configured\" | \"failed\" };\n\nconst MEMBER_ROLES = [\"owner\", \"admin\", \"member\"] as const;\n\nconst MEMBERS_ACTIONS = [\"list\", \"invite\", \"remove\", \"role\"] as const;\nconst INVITES_ACTIONS = [\"list\", \"revoke\", \"resend\"] as const;\n\n/** The organization a members/invites command acts on: `--org`, else the active one. */\nfunction orgFor(flag: string | undefined, url: string): string {\n const org = flag || getContextOrg(url);\n if (!org) fail(\"No organization selected.\", `Pass ${chalk.bold(\"--org <id>\")} or run ${chalk.bold(\"rebase cloud use\")}.`, \"no_org\");\n return org;\n}\n\nasync function loadMembers(client: CloudClient, org: string): Promise<MemberRow[]> {\n const rows = cloudRows<{ id: string | number; userId?: string; role?: string }>((await client.data.collection(\"organization-members\").find({\n where: { organization: [\"==\", org] },\n limit: 200\n })).data);\n const ids = rows.map((m) => m.userId).filter((id): id is string => typeof id === \"string\" && id !== \"\");\n const emails = new Map<string, string>();\n if (ids.length > 0) {\n // The users read policy shows the people you share an organization\n // with, which is exactly this list. An unreadable row leaves the id.\n try {\n const users = cloudRows<{ id: string | number; email?: string }>((await client.data.collection(\"users\").find({\n where: { id: [\"in\", ids] },\n limit: 200\n })).data);\n for (const u of users) if (u.email) emails.set(String(u.id), u.email);\n } catch {\n /* ids only */\n }\n }\n return rows.map((m) => ({\n id: String(m.id),\n userId: m.userId ?? null,\n email: m.userId ? emails.get(m.userId) ?? null : null,\n role: m.role ?? null\n }));\n}\n\n/** The membership `ref` names — a user id or an email — or a refusal. */\nfunction pickMember(members: MemberRow[], ref: string | undefined, action: string): MemberRow {\n if (!ref) fail(`Name the member to ${action}.`, `Pass their email or user id: \\`rebase cloud orgs members ${action} <email|uid>\\`.`, \"usage\");\n const wanted = ref.trim().toLowerCase();\n const match = members.find((m) => m.userId === ref || (m.email ?? \"\").toLowerCase() === wanted);\n if (!match) {\n fail(`${ref} is not a member of this organization.`, \"Run `rebase cloud orgs members` to see who is.\", \"not_found\");\n }\n return match;\n}\n\nasync function membersCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parseCloudArgs({\n spec: { \"--role\": String, \"--org\": String },\n rawArgs,\n commandWords: 3, // cloud orgs members\n command: \"cloud orgs\",\n maxPositionals: 3\n });\n const [action = \"list\", ...rest] = positionals;\n if (!(MEMBERS_ACTIONS as readonly string[]).includes(action)) {\n fail(\n `Unknown orgs members command: ${action}`,\n `Run \\`rebase cloud orgs --help\\`. Actions: ${MEMBERS_ACTIONS.join(\", \")}.`,\n \"unknown_command\"\n );\n }\n if (flags[\"--role\"] !== undefined && action !== \"invite\") {\n fail(`--role belongs to \\`members invite\\`.`, \"To change a member's role: `rebase cloud orgs members role <email|uid> <role>`.\", \"usage\");\n }\n const expected = action === \"list\" ? 0 : action === \"role\" ? 2 : 1;\n if (rest.length > expected) {\n fail(`Too many arguments for \\`orgs members ${action}\\`: ${rest.slice(expected).join(\" \")}`, \"Run `rebase cloud orgs --help`.\", \"usage\");\n }\n if (action === \"role\" && rest[1] !== undefined && !(MEMBER_ROLES as readonly string[]).includes(rest[1])) {\n fail(`\"${rest[1]}\" is not a role.`, \"A role is owner, admin or member.\", \"usage\");\n }\n const role = flags[\"--role\"] ?? \"member\";\n if (action === \"invite\" && role === \"owner\") {\n const who = rest[0] ?? \"<email>\";\n fail(\n \"Nobody is invited as an owner.\",\n `Invite them with --role admin, and once they have joined: \\`rebase cloud orgs members role ${who} owner\\`.`,\n \"invite_role_not_allowed\"\n );\n }\n if (action === \"invite\" && !(MEMBER_ROLES as readonly string[]).includes(role)) {\n fail(`\"${role}\" is not a role.`, \"Pass --role admin or --role member.\", \"usage\");\n }\n\n switch (action) {\n case \"list\":\n return listMembers(rawArgs, flags[\"--org\"]);\n case \"invite\":\n return inviteMember(rawArgs, flags[\"--org\"], rest[0], role);\n case \"remove\":\n return removeMember(rawArgs, flags[\"--org\"], rest[0], Boolean(flags[\"--yes\"]));\n case \"role\":\n return changeRole(rawArgs, flags[\"--org\"], rest[0], rest[1]);\n }\n}\n\nasync function listMembers(rawArgs: string[], orgFlag: string | undefined): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = orgFor(orgFlag, url);\n let members: MemberRow[];\n try {\n members = await loadMembers(client, org);\n } catch (e) {\n reportError(e, \"Failed to list members\");\n }\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 👥 Members — org ${org}`));\n console.log(\"\");\n if (members.length === 0) {\n console.log(chalk.gray(\" No members found.\"));\n console.log(\"\");\n return;\n }\n for (const m of members) {\n const who = m.email ?? m.userId ?? \"?\";\n console.log(` ${chalk.bold(who)} ${colorStatus(m.role ?? undefined)}${m.email && m.userId ? chalk.gray(` ${m.userId}`) : \"\"}`);\n }\n console.log(\"\");\n note(chalk.gray(\"Invite someone: `rebase cloud orgs members invite <email>`. Pending: `rebase cloud orgs invites`.\"));\n console.log(\"\");\n },\n { org, members }\n );\n}\n\n/**\n * Whether the invitation email went out. Not sent is a warning, not a note: the\n * invitee hears nothing unless whoever ran this passes the link on, so it is\n * said in JSON mode too (stderr), and `emailDelivery` carries it in the value.\n */\nfunction reportDelivery(delivery: EmailDelivery, email: string): void {\n if (delivery.sent) {\n note(chalk.gray(`Emailed the invitation to ${email}.`));\n return;\n }\n warn(\n delivery.reason === \"failed\"\n ? `The invitation email to ${email} could not be sent.`\n : `This control plane sends no email, so nothing was sent to ${email}.`,\n \"Send them the link yourself.\"\n );\n}\n\nasync function inviteMember(rawArgs: string[], orgFlag: string | undefined, email: string | undefined, role: string): Promise<void> {\n if (!email) fail(\"Name the address to invite.\", \"`rebase cloud orgs members invite <email> [--role admin|member]`.\", \"usage\");\n const { client, url } = await requireSessionClient(rawArgs, \"invite people to an organization\");\n const org = orgFor(orgFlag, url);\n type Result =\n | { kind: \"added\"; userId: string; role: string; email: string }\n | { kind: \"invited\"; invite: CliInvite; link: string; emailDelivery: EmailDelivery };\n let result: Result;\n try {\n result = await client.functions.invoke<Result>(\"invites\", { organizationId: org, email: email.trim().toLowerCase(), role });\n } catch (e) {\n reportError(e, `Failed to invite ${email}`);\n }\n if (result.kind === \"added\") {\n // Only a control plane from before invitations-for-everyone adds\n // anyone directly; today's always answers \"invited\".\n emit(() => success(`${result.email} already had a verified account and is now a member (${result.role}) of org ${org}`), { org, ...result });\n return;\n }\n const invited = result;\n emit(\n () => {\n success(`Invitation sent to ${invited.invite.email} as ${invited.invite.role} — they join when they accept; the link works once, until ${invited.invite.expiresAt.slice(0, 10)}`);\n console.log(\"\");\n console.log(` ${chalk.cyan(invited.link)}`);\n console.log(\"\");\n note(chalk.gray(\"Only an account that has verified that address can accept it.\"));\n },\n { org, ...invited }\n );\n reportDelivery(invited.emailDelivery, invited.invite.email);\n}\n\nasync function removeMember(rawArgs: string[], orgFlag: string | undefined, ref: string | undefined, yes: boolean): Promise<void> {\n if (!ref) pickMember([], ref, \"remove\");\n const { client, url } = await requireClient(rawArgs);\n const org = orgFor(orgFlag, url);\n let members: MemberRow[];\n try {\n members = await loadMembers(client, org);\n } catch (e) {\n reportError(e, \"Failed to list members\");\n }\n const target = pickMember(members, ref, \"remove\");\n const who = target.email ?? target.userId ?? ref;\n await confirmDestructive({ yes, prompt: `Remove ${who} (${target.role ?? \"member\"}) from org ${org}? They lose access to its projects.` });\n try {\n await client.data.collection(\"organization-members\").delete(target.id);\n } catch (e) {\n // The server's words: the last owner, or an admin removing an owner.\n reportError(e, `Failed to remove ${who}`);\n }\n emit(() => success(`Removed ${who} from org ${org}`), { org, removed: { userId: target.userId, email: target.email, role: target.role } });\n}\n\nasync function changeRole(rawArgs: string[], orgFlag: string | undefined, ref: string | undefined, role: string | undefined): Promise<void> {\n if (!ref || !role) fail(\"Name the member and the role.\", \"`rebase cloud orgs members role <email|uid> <owner|admin|member>`.\", \"usage\");\n const { client, url } = await requireClient(rawArgs);\n const org = orgFor(orgFlag, url);\n let members: MemberRow[];\n try {\n members = await loadMembers(client, org);\n } catch (e) {\n reportError(e, \"Failed to list members\");\n }\n const target = pickMember(members, ref, \"role\");\n const who = target.email ?? target.userId ?? ref;\n if (target.role === role) {\n emit(() => success(`${who} is already ${role} in org ${org}`), { org, userId: target.userId, email: target.email, role, changed: false });\n return;\n }\n try {\n await client.data.collection(\"organization-members\").update(target.id, { role });\n } catch (e) {\n // The server's words: only an owner grants or removes owner; never the last owner.\n reportError(e, `Failed to change ${who}'s role`);\n }\n emit(() => success(`${who} is now ${role} in org ${org} (was ${target.role ?? \"member\"})`), {\n org, userId: target.userId, email: target.email, role, previousRole: target.role, changed: true\n });\n}\n\nasync function loadInvites(client: CloudClient, org: string): Promise<{ invites: CliInvite[]; canManage: boolean }> {\n return client.functions.invoke<{ invites: CliInvite[]; canManage: boolean }>(\n \"invites\",\n undefined,\n { method: \"GET\", path: `org/${encodeURIComponent(org)}` }\n );\n}\n\n/** The open invitation `ref` names — its id or its email — or a refusal. */\nfunction pickInvite(invites: CliInvite[], ref: string | undefined, action: string): CliInvite {\n if (!ref) fail(`Name the invitation to ${action}.`, `Pass its id or email: \\`rebase cloud orgs invites ${action} <id|email>\\`.`, \"usage\");\n const wanted = ref.trim().toLowerCase();\n const match = invites.find((i) => i.id === ref || i.email === wanted);\n if (!match) fail(`No pending invitation for ${ref}.`, \"Run `rebase cloud orgs invites` to see the pending ones.\", \"not_found\");\n return match;\n}\n\nasync function invitesCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parseCloudArgs({\n spec: { \"--org\": String },\n rawArgs,\n commandWords: 3, // cloud orgs invites\n command: \"cloud orgs\",\n maxPositionals: 2\n });\n const [action = \"list\", ref] = positionals;\n if (!(INVITES_ACTIONS as readonly string[]).includes(action)) {\n fail(\n `Unknown orgs invites command: ${action}`,\n `Run \\`rebase cloud orgs --help\\`. Actions: ${INVITES_ACTIONS.join(\", \")}.`,\n \"unknown_command\"\n );\n }\n if (action === \"list\" && ref !== undefined) {\n fail(`Too many arguments for \\`orgs invites\\`: ${ref}`, \"Run `rebase cloud orgs --help`.\", \"usage\");\n }\n if (action !== \"list\" && !ref) pickInvite([], ref, action);\n\n const { client, url } = await requireSessionClient(rawArgs, \"manage invitations\");\n const org = orgFor(flags[\"--org\"], url);\n let listed: { invites: CliInvite[]; canManage: boolean };\n try {\n listed = await loadInvites(client, org);\n } catch (e) {\n // A member: pending invitations, like inviting, are an owner's and\n // admin's. Said plainly rather than as a bare 403.\n if ((e as { status?: number } | null)?.status === 403) {\n fail(\n `Only owners and admins of org ${org} can see its pending invitations.`,\n \"Ask one of them; `rebase cloud orgs members` lists who they are.\",\n \"forbidden\"\n );\n }\n reportError(e, \"Failed to list invitations\");\n }\n\n if (action === \"list\") {\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ✉️ Pending invitations — org ${org}`));\n console.log(\"\");\n if (listed.invites.length === 0) {\n console.log(chalk.gray(\" No pending invitations.\"));\n console.log(\"\");\n return;\n }\n for (const i of listed.invites) {\n const when = i.expired ? chalk.yellow(\"expired\") : chalk.gray(`expires ${i.expiresAt.slice(0, 10)}`);\n console.log(` ${chalk.bold(i.email)} ${colorStatus(i.role)} ${when} ${chalk.gray(`by ${i.invitedBy.email ?? \"?\"} [${i.id}]`)}`);\n }\n console.log(\"\");\n },\n { org, invites: listed.invites }\n );\n return;\n }\n\n const target = pickInvite(listed.invites, ref, action);\n if (action === \"revoke\") {\n try {\n await client.functions.invoke(\"invites\", undefined, { method: \"DELETE\", path: encodeURIComponent(target.id) });\n } catch (e) {\n reportError(e, `Failed to revoke the invitation for ${target.email}`);\n }\n emit(() => success(`Revoked the invitation for ${target.email}; its link no longer works`), { org, revoked: target });\n return;\n }\n\n let resent: { invite: CliInvite; link: string; emailDelivery: EmailDelivery };\n try {\n resent = await client.functions.invoke<{ invite: CliInvite; link: string; emailDelivery: EmailDelivery }>(\n \"invites\", {}, { path: `${encodeURIComponent(target.id)}/resend` }\n );\n } catch (e) {\n reportError(e, `Failed to resend the invitation for ${target.email}`);\n }\n emit(\n () => {\n success(`New link for ${resent.invite.email}, valid until ${resent.invite.expiresAt.slice(0, 10)}; the old one no longer works`);\n console.log(\"\");\n console.log(` ${chalk.cyan(resent.link)}`);\n console.log(\"\");\n },\n { org, ...resent }\n );\n reportDelivery(resent.emailDelivery, resent.invite.email);\n}\n\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nexport function printOrgsHelp(): void {\n printGroupHelp({\n command: \"cloud orgs\",\n title: \"Organizations\",\n actions: [\n { action: \"list\",\ndescription: \"List organizations you belong to\" },\n {\n action: \"create\",\n description: \"Create a new organization\",\n flags: [\n [\"--name <name>\", \"Display name\"],\n [\"--slug <slug>\", \"URL slug. Derived from the name when omitted\"]\n ]\n },\n {\n action: \"members\",\n args: \"[list]\",\n section: \"Members\",\n description: \"List members of the organization, with their email and role\",\n flags: [[\"--org <id>\", \"The organization. Default: the active one\"]]\n },\n {\n action: \"members invite\",\n args: \"<email>\",\n section: \"Members\",\n description: \"Invite by email: a 7-day, single-use link they accept. Nobody joins until they do\",\n flags: [[\"--role <role>\", \"admin or member (default). Never owner: promote them with `members role` once they have joined\"]]\n },\n {\n action: \"members remove\",\n args: \"<email|uid>\",\n section: \"Members\",\n description: \"Remove a member. Asks first; --yes skips the prompt\"\n },\n {\n action: \"members role\",\n args: \"<email|uid> <role>\",\n section: \"Members\",\n description: \"Change a member's role: owner, admin or member\"\n },\n {\n action: \"invites\",\n args: \"[list]\",\n section: \"Invitations\",\n description: \"Pending invitations: email, role, who invited, expiry. Owners and admins only\"\n },\n {\n action: \"invites revoke\",\n args: \"<id|email>\",\n section: \"Invitations\",\n description: \"Revoke a pending invitation; its link stops working\"\n },\n {\n action: \"invites resend\",\n args: \"<id|email>\",\n section: \"Invitations\",\n description: \"A new link and seven more days; the old link stops working\"\n }\n ],\n notes: [\n \"The active one is what `rebase cloud use` selects, and what billing is scoped to.\",\n \"Inviting and invitations take a `rebase cloud login` session, not REBASE_TOKEN, and the owner or admin role.\",\n \"The invitation link is printed because the control plane may send no email; the output says whether it did. \"\n + \"Only an account that has verified the invited address can accept it.\"\n ]\n });\n}\n","/**\n * `rebase cloud domains` — the hostnames a project is served on.\n *\n * domains list Every host, its status, and the DNS records it needs\n * domains add <domain> Register a host (starts, does not finish, setup)\n * domains verify [domain] Check the host's published DNS now; live only if it passes\n * domains remove <domain> Stop serving a host\n *\n * A project's hosts are rows of the control plane's `project_domains` table,\n * managed through its `domains` function — the same one the console uses. The\n * Ingress is built from those rows, one verified host at a time, so every\n * action here addresses a row. The single `projects.customDomain` column is a\n * projection the control plane keeps in step with them; writing it directly\n * changes nothing that is served.\n *\n * Two cases still go through that column, because the control plane still\n * serves them from it: a project with no rows at all, whose one domain lives\n * only in the column, and a control plane that has no `domains` function.\n *\n * The DNS record set comes from the server, never composed here: whether to\n * publish an A or a CNAME depends on apex-vs-subdomain and on the ingress\n * address behind the tenant host, which the CLI cannot know. Adding a host only\n * registers it — it is unverified until the records are published and `verify`\n * passes.\n */\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n parseCloudArgs,\n emit,\n printGroupHelp,\n confirmDestructive,\n keyValues,\n success,\n fail,\n warn,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface DomainRecord {\n type: \"A\" | \"CNAME\" | \"TXT\";\n name: string;\n values: string[];\n}\n\ninterface DomainInstructions {\n pointing?: DomainRecord;\n ownership: DomainRecord;\n}\n\n/**\n * One host, as the `domains` function describes a row.\n *\n * `id` is null for the domain a project holds only in its single column: it\n * has no row, and is verified and removed through that column instead.\n */\ninterface DomainEntry {\n id: string | null;\n host: string;\n primary: boolean;\n status: \"pending\" | \"verified\";\n verifiedAt: string | null;\n isApex?: boolean;\n tenantHost?: string;\n instructions?: DomainInstructions;\n}\n\n/** What `verify-domain` answers about the single column. */\ninterface ColumnSetup {\n domain: string | null;\n status: \"none\" | \"pending\" | \"verified\";\n isApex?: boolean;\n tenantHost?: string;\n verifiedAt?: string | null;\n instructions?: DomainInstructions;\n}\n\n/** A row as the `domains` function sends it. */\ninterface DomainRow {\n id?: string;\n host?: string;\n primary?: boolean;\n status?: string;\n verifiedAt?: string | null;\n isApex?: boolean;\n tenantHost?: string;\n instructions?: DomainInstructions;\n}\n\ninterface DomainCheck {\n ok: boolean;\n expected: string[];\n observed: string[];\n error?: string;\n}\n\ninterface DomainChecks {\n ownership: DomainCheck;\n pointing: DomainCheck;\n}\n\n/** What either door answers a verification with: the host as it is now, and the checks. */\ninterface VerifyAnswer {\n verified?: boolean;\n checks?: DomainChecks;\n status?: string;\n verifiedAt?: string | null;\n instructions?: DomainInstructions;\n}\n\n/** A project's hosts, and which door changes them. */\ninterface DomainSet {\n /**\n * `rows` — the `domains` function answers, and each host with an id is a row.\n * `column` — the control plane has no `domains` function; everything goes\n * through the single column.\n */\n model: \"rows\" | \"column\";\n tenantHost?: string;\n domains: DomainEntry[];\n}\n\n/** The column's one domain as an entry, or none. */\nfunction columnEntry(setup: ColumnSetup): DomainEntry[] {\n if (!setup.domain) return [];\n return [{\n id: null,\n host: setup.domain,\n primary: true,\n status: setup.status === \"verified\" ? \"verified\" : \"pending\",\n verifiedAt: setup.verifiedAt ?? null,\n isApex: setup.isApex,\n tenantHost: setup.tenantHost,\n instructions: setup.instructions\n }];\n}\n\n/**\n * A row, or null for one with no id or host — it cannot be verified or removed,\n * so it is not offered as a domain. Anything but `verified` is pending: an\n * unreadable status must not read as live.\n */\nfunction rowEntry(row: DomainRow | null | undefined): DomainEntry | null {\n if (typeof row?.id !== \"string\" || typeof row.host !== \"string\") return null;\n return {\n id: row.id,\n host: row.host,\n primary: row.primary === true,\n status: row.status === \"verified\" ? \"verified\" : \"pending\",\n verifiedAt: row.verifiedAt ?? null,\n isApex: row.isApex,\n tenantHost: row.tenantHost,\n instructions: row.instructions\n };\n}\n\n/**\n * Whether a failed `domains` call means the control plane has no such function\n * — as opposed to refusing this project, which the function answers `not_found`.\n */\nfunction noDomainsFunction(e: unknown): boolean {\n if (typeof e !== \"object\" || e === null) return false;\n const status = \"status\" in e ? e.status : undefined;\n const code = \"code\" in e ? e.code : undefined;\n return status === 404 && code !== \"not_found\";\n}\n\nasync function fetchColumnSetup(client: CloudClient, projectId: string): Promise<ColumnSetup> {\n return client.functions.invoke<ColumnSetup>(\"verify-domain\", undefined, { method: \"GET\",\npath: projectId });\n}\n\n/** Every host this project is served on, or may be once verified. */\nasync function loadDomains(client: CloudClient, projectId: string): Promise<DomainSet> {\n let listed: { tenantHost?: string; domains?: DomainRow[] };\n try {\n listed = await client.functions.invoke<{ tenantHost?: string; domains?: DomainRow[] }>(\n \"domains\",\n undefined,\n { method: \"GET\",\npath: projectId }\n );\n } catch (e) {\n if (!noDomainsFunction(e)) throw e;\n const setup = await fetchColumnSetup(client, projectId);\n return { model: \"column\",\ntenantHost: setup.tenantHost,\ndomains: columnEntry(setup) };\n }\n\n const domains = (listed.domains ?? []).map(rowEntry).filter((d): d is DomainEntry => d !== null);\n if (domains.length > 0) return { model: \"rows\",\ntenantHost: listed.tenantHost,\ndomains };\n\n // No rows: the control plane serves the column's domain, if it holds one.\n const setup = await fetchColumnSetup(client, projectId);\n return { model: \"rows\",\ntenantHost: listed.tenantHost ?? setup.tenantHost,\ndomains: columnEntry(setup) };\n}\n\n/**\n * The host an action names, or the only one there is to name.\n *\n * Refuses to guess among several: removing or verifying the wrong host of a\n * live site is not a mistake worth saving a word over.\n */\nfunction pickDomain(set: DomainSet, named: string | undefined, action: string): DomainEntry {\n if (named) {\n const wanted = named.trim().toLowerCase().replace(/\\.$/, \"\");\n const found = set.domains.find(d => d.host.toLowerCase() === wanted);\n if (!found) {\n fail(\n `This project has no domain ${named}.`,\n set.domains.length\n ? `Its domains: ${set.domains.map(d => d.host).join(\", \")}.`\n : \"It has no custom domains. Add one with `rebase cloud domains add <domain>`.\",\n \"not_found\"\n );\n }\n return found;\n }\n if (set.domains.length === 1) return set.domains[0];\n if (set.domains.length === 0) {\n fail(\"This project has no custom domains.\", \"Add one with `rebase cloud domains add <domain>`.\", \"not_found\");\n }\n // `verify` with no host means the one waiting to be verified, when only one is.\n const pending = set.domains.filter(d => d.status !== \"verified\");\n if (action === \"verify\" && pending.length === 1) return pending[0];\n fail(\n `This project has ${set.domains.length} domains; name the one to ${action}.`,\n `Run \\`rebase cloud domains ${action} <domain>\\` with one of: ${set.domains.map(d => d.host).join(\", \")}.`,\n \"usage\"\n );\n}\n\nfunction printRecords(instructions: DomainInstructions | undefined): void {\n const recs = [instructions?.pointing, instructions?.ownership].filter(Boolean) as DomainRecord[];\n if (!recs.length) return;\n console.log(chalk.bold(\" DNS records to publish:\"));\n for (const r of recs) {\n console.log(` ${chalk.cyan(r.type)} ${r.name} → ${r.values.join(\", \")}`);\n }\n console.log(\"\");\n}\n\nexport async function domainsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case \"status\":\n case undefined:\n await listDomains(rawArgs);\n break;\n case \"add\":\n case \"set\":\n await addDomain(rawArgs);\n break;\n case \"verify\":\n await verifyDomain(rawArgs);\n break;\n case \"remove\":\n case \"rm\":\n case \"delete\":\n await removeDomain(rawArgs);\n break;\n case \"--help\":\n printDomainsHelp();\n break;\n default:\n fail(`Unknown domains command: ${action}`, \"Run `rebase cloud domains --help`.\", \"unknown_command\");\n }\n}\n\nasync function listDomains(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud domains\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const set = await loadDomains(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🌐 Custom domains — project ${projectRef}`));\n console.log(\"\");\n if (!set.domains.length) {\n console.log(chalk.gray(\" No custom domains. Add one with `rebase cloud domains add <domain>`.\"));\n console.log(\"\");\n return;\n }\n if (set.tenantHost) {\n keyValues([[\"Tenant host\", set.tenantHost]]);\n console.log(\"\");\n }\n for (const d of set.domains) {\n const status = d.status === \"verified\" ? chalk.green(d.status) : chalk.yellow(d.status);\n console.log(` ${chalk.bold(d.host)} ${status}${d.primary && set.domains.length > 1 ? chalk.gray(\" primary\") : \"\"}`);\n if (d.verifiedAt) console.log(chalk.gray(` verified ${d.verifiedAt}`));\n if (d.status !== \"verified\") printRecords(d.instructions);\n }\n console.log(\"\");\n },\n { projectId,\ntenantHost: set.tenantHost ?? null,\ndomains: set.domains }\n );\n } catch (e) {\n reportError(e, \"Failed to load custom domains\");\n }\n}\n\n/**\n * The domain an action was given, or undefined.\n *\n * Exported so its tests drive the real parser. Under the old operand filter\n * `rebase cloud domains add -p acme` registered a domain called \"acme\" — the\n * project slug, read out of `--project`'s own value — and a registered domain\n * is a project-record write, not a no-op.\n */\nexport function resolveDomainArg(rawArgs: string[], action = \"add\"): string | undefined {\n return parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud domains <action>\n command: `cloud domains ${action}`,\n maxPositionals: 1\n }).positionals[0];\n}\n\nasync function addDomain(rawArgs: string[]): Promise<void> {\n const domain = resolveDomainArg(rawArgs);\n if (!domain) fail(\"Usage: rebase cloud domains add <domain>\", undefined, \"usage\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let added: DomainEntry | undefined;\n try {\n const set = await loadDomains(client, projectId);\n if (set.model === \"column\") {\n // No `domains` function: the column is the project's one domain.\n await client.data.collection(\"projects\").update(projectId, { customDomain: domain });\n added = columnEntry(await fetchColumnSetup(client, projectId))[0];\n } else {\n const legacy = set.domains.find(d => d.id === null);\n if (legacy && legacy.host.toLowerCase() !== domain.trim().toLowerCase()) {\n // The column's domain is served only while the project has no\n // host rows; this adds the first, and once a row is verified\n // the Ingress carries the rows alone.\n warn(\n `${legacy.host} is held outside this project's host list, and stops being served once another host is verified.`,\n `Keep it by adding it too: \\`rebase cloud domains add ${legacy.host}\\`, then \\`rebase cloud domains verify ${legacy.host}\\`.`\n );\n }\n added = rowEntry(await client.functions.invoke<DomainRow>(\"domains\", { host: domain }, { path: projectId })) ?? undefined;\n }\n } catch (e) {\n reportError(e, \"Failed to register domain\");\n }\n if (!added) fail(`The control plane did not return ${domain}, so whether it was registered is unknown.`, \"Run `rebase cloud domains list`.\");\n const registered = added;\n emit(\n () => {\n success(`Registered ${chalk.bold(registered.host)} — not yet verified`);\n printRecords(registered.instructions);\n console.log(chalk.gray(` Publish the records above, then run \\`rebase cloud domains verify ${registered.host}\\`.`));\n console.log(\"\");\n },\n { success: true,\nprojectId,\n...registered }\n );\n}\n\nasync function verifyDomain(rawArgs: string[]): Promise<void> {\n const named = resolveDomainArg(rawArgs, \"verify\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n let set: DomainSet;\n try {\n set = await loadDomains(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to load custom domains\");\n }\n const target = pickDomain(set, named, \"verify\");\n try {\n const res = verifyOutcome(\n target.id === null\n ? await client.functions.invoke<VerifyAnswer>(\"verify-domain\", {}, { path: projectId })\n : await client.functions.invoke<VerifyAnswer>(\"domains\", {}, { path: `${projectId}/${target.id}/verify` }),\n target\n );\n emit(\n () => {\n console.log(\"\");\n if (res.verified) success(`${target.host} is verified and live`);\n else {\n console.log(chalk.yellow(` ⚠ ${target.host} is not verified yet`));\n console.log(\"\");\n const rows: Array<[string, DomainCheck]> = [\n [\"Ownership\", res.checks.ownership],\n [\"Pointing\", res.checks.pointing]\n ];\n for (const [label, check] of rows) {\n const mark = check.ok ? chalk.green(\"ok\") : chalk.red(\"missing\");\n console.log(` ${label}: ${mark}`);\n console.log(chalk.gray(` expected: ${check.expected.join(\", \") || \"—\"}`));\n console.log(chalk.gray(` observed: ${check.observed.join(\", \") || \"—\"}`));\n if (check.error) console.log(chalk.gray(` error: ${check.error}`));\n }\n console.log(\"\");\n printRecords(res.entry.instructions);\n }\n },\n { projectId,\nid: res.entry.id,\nhost: res.entry.host,\nverified: res.verified,\nstatus: res.entry.status,\nchecks: res.checks,\ninstructions: res.entry.instructions ?? null }\n );\n if (!res.verified) process.exit(1);\n } catch (e) {\n reportError(e, \"Failed to verify domain\");\n }\n}\n\n/** A verify answer from either door, as one shape. */\nfunction verifyOutcome(\n res: VerifyAnswer,\n target: DomainEntry\n): { verified: boolean; checks: DomainChecks; entry: DomainEntry } {\n const verified = res.verified === true;\n const unchecked: DomainCheck = { ok: false, expected: [], observed: [] };\n return {\n verified,\n checks: res.checks ?? { ownership: unchecked, pointing: unchecked },\n entry: {\n ...target,\n status: verified || res.status === \"verified\" ? \"verified\" : \"pending\",\n verifiedAt: res.verifiedAt ?? target.verifiedAt,\n instructions: res.instructions ?? target.instructions\n }\n };\n}\n\nasync function removeDomain(rawArgs: string[]): Promise<void> {\n // Strict: detaching a host is destructive, and the permissive parse\n // accepted `domains remove --dry-run` by ignoring the flag and detaching\n // anyway.\n const { flags: args, positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud domains remove\n command: \"cloud domains remove\",\n maxPositionals: 1\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n let set: DomainSet;\n try {\n set = await loadDomains(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to load custom domains\");\n }\n const target = pickDomain(set, positionals[0], \"remove\");\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Stop serving ${target.host} on project ${projectRef}?`\n });\n\n try {\n let removed = true;\n if (target.id === null) {\n await client.data.collection(\"projects\").update(projectId, { customDomain: \"\" });\n } else {\n const res = await client.functions.invoke<{ removed?: boolean }>(\n \"domains\",\n undefined,\n { method: \"DELETE\",\npath: `${projectId}/${target.id}` }\n );\n // `removed: false` is the server saying it was already gone — the\n // outcome asked for, and reported as it is.\n removed = res?.removed !== false;\n }\n emit(\n () => success(removed\n ? `${target.host} is no longer served by project ${projectRef}`\n : `${target.host} was already gone from project ${projectRef}`),\n { success: true,\nprojectId,\nhost: target.host,\nremoved }\n );\n } catch (e) {\n reportError(e, \"Failed to remove domain\");\n }\n}\n\nexport function printDomainsHelp(): void {\n printGroupHelp({\n command: \"cloud domains\",\n title: \"Custom domains\",\n actions: [\n { action: \"list\",\ndescription: \"Every host, its status, and the DNS records it needs\" },\n { action: \"add\",\nargs: \"<domain>\",\ndescription: \"Register a host\" },\n { action: \"verify\",\nargs: \"[domain]\",\ndescription: \"Check a host's DNS and put it live\" },\n { action: \"remove\",\nargs: \"<domain>\",\ndescription: \"Stop serving a host\" }\n ],\n notes: [\n \"A project can be served on several hosts; each is verified on its own.\",\n \"A CNAME is invalid at a zone apex: use an A record there and a CNAME below it.\",\n \"`list` prints the exact records to add — copy them rather than deriving them.\"\n ]\n });\n}\n","/**\n * `rebase cloud extensions` — allowlisted Postgres extensions.\n *\n * extensions list Every allowlisted extension + its real state\n * extensions enable <name> [-y] Install one (may restart the DB ⇒ needs -y)\n * extensions disable <name> Drop one (and remove any preload library)\n *\n * `manageable === false` is the anti-brick guard reaching the CLI: the server\n * has already said it will refuse, so enable/disable is never offered for such an\n * extension — its `manageableReason` is surfaced instead. Enabling one that\n * restarts the customer's database requires `--yes` in non-interactive use. The\n * `pgvector` alias resolves to `vector`, and a 202 (`pending`) means the database\n * is restarting and the extension is not installed yet — re-drive later.\n */\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n parseCloudArgs,\n emit,\n printGroupHelp,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface ExtensionStatus {\n name: string;\n displayName: string;\n description: string;\n requiresRestart: boolean;\n enabled: boolean;\n version: string | null;\n enabledAt: string | null;\n available: boolean;\n pendingRestart: boolean;\n manageable: boolean;\n manageableReason: string | null;\n}\n\ninterface ExtensionListResponse {\n databaseType: \"managed\" | \"byodb\" | \"none\";\n reason: string;\n source: \"database\" | \"record\";\n extensions: ExtensionStatus[];\n}\n\ninterface EnableResult {\n success: boolean;\n extension: string;\n pending?: boolean;\n restarted?: boolean;\n requiresRestart?: boolean;\n alreadyEnabled?: boolean;\n version?: string | null;\n recordWritten?: boolean;\n message: string;\n}\n\ninterface DisableResult {\n success: boolean;\n extension: string;\n dropped: boolean;\n preloadRemoved: boolean;\n restarted?: boolean;\n message: string;\n}\n\n/** The identifier CREATE EXTENSION takes. `pgvector` is a common alias. */\nexport function resolveExtensionAlias(name: string): string {\n return name.toLowerCase() === \"pgvector\" ? \"vector\" : name;\n}\n\nasync function fetchExtensions(client: CloudClient, projectId: string): Promise<ExtensionListResponse> {\n return client.functions.invoke<ExtensionListResponse>(\"extensions\", undefined, {\n method: \"GET\",\n path: `list/${projectId}`\n });\n}\n\nexport async function extensionsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listExtensions(rawArgs);\n break;\n case \"enable\":\n await enableExtension(rawArgs);\n break;\n case \"disable\":\n await disableExtension(rawArgs);\n break;\n case \"--help\":\n printExtensionsHelp();\n break;\n default:\n fail(`Unknown extensions command: ${action}`, \"Run `rebase cloud extensions --help`.\", \"unknown_command\");\n }\n}\n\nasync function listExtensions(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud extensions\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await fetchExtensions(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🧩 Extensions — project ${projectRef}`) + chalk.gray(` (${res.databaseType}, source: ${res.source})`));\n console.log(\"\");\n if (res.source === \"record\") {\n console.log(chalk.yellow(\" ⚠ Database unreachable — showing cached state, not live catalog.\"));\n console.log(\"\");\n }\n for (const e of res.extensions) {\n const state = e.enabled ? chalk.green(\"enabled\") : chalk.gray(\"disabled\");\n const restart = e.requiresRestart ? chalk.yellow(\" ⟳ restarts DB\") : \"\";\n const locked = !e.manageable ? chalk.gray(\" [not manageable]\") : \"\";\n console.log(` ${chalk.bold(e.name)} ${state}${e.version ? chalk.gray(` v${e.version}`) : \"\"}${restart}${locked}`);\n if (!e.manageable && e.manageableReason) console.log(chalk.gray(` ${e.manageableReason}`));\n }\n console.log(\"\");\n },\n { projectId,\ndatabaseType: res.databaseType,\nreason: res.reason,\nsource: res.source,\nextensions: res.extensions }\n );\n } catch (e) {\n reportError(e, \"Failed to list extensions\");\n }\n}\n\n/**\n * The extension `enable`/`disable` names, plus the flags that gate it.\n *\n * Under the old operand filter `rebase cloud extensions enable -p acme` read\n * `--project`'s value as the extension name and asked the server to install one\n * called \"acme\"; `extensions disable -p acme vector` dropped \"acme\" rather than\n * vector. Strict parsing consumes the flag with its value.\n */\nexport function resolveExtensionArgs(rawArgs: string[], action: \"enable\" | \"disable\") {\n const { flags, positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud extensions <action>\n command: `cloud extensions ${action}`,\n maxPositionals: 1\n });\n return { flags,\nname: positionals[0] };\n}\n\nasync function enableExtension(rawArgs: string[]): Promise<void> {\n const { flags: args, name: raw } = resolveExtensionArgs(rawArgs, \"enable\");\n if (!raw) fail(\"Usage: rebase cloud extensions enable <name>\", undefined, \"usage\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const name = resolveExtensionAlias(raw!);\n\n try {\n // Consult the catalog first: never offer enable where the server says it\n // is not manageable, and gate a DB-restarting enable behind --yes.\n const list = await fetchExtensions(client, projectId);\n const ext = list.extensions.find((e) => e.name === name);\n if (ext && !ext.manageable) {\n fail(\n `Extension ${name} cannot be managed on this project.`,\n ext.manageableReason ?? undefined,\n \"not_manageable\"\n );\n }\n if (ext?.requiresRestart && !ext.enabled) {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Enabling ${name} restarts the project's database. Continue?`\n });\n }\n\n const res = await client.functions.invoke<EnableResult>(\"extensions\", { projectId,\nextensionName: name }, { path: \"enable\" });\n emit(\n () => {\n if (res.pending) {\n console.log(\"\");\n console.log(chalk.yellow(` ⏳ ${res.message}`));\n console.log(chalk.gray(\" The database is restarting; re-run this once it is back to finish installing.\"));\n console.log(\"\");\n } else {\n success(res.message || `Enabled ${name}`);\n keyValues([[\"Version\", res.version ?? undefined]]);\n }\n },\n {\n success: res.success,\n extension: res.extension,\n pending: res.pending ?? false,\n restarted: res.restarted ?? false,\n alreadyEnabled: res.alreadyEnabled ?? false,\n version: res.version ?? null,\n message: res.message\n }\n );\n } catch (e) {\n reportError(e, \"Failed to enable extension\");\n }\n}\n\nasync function disableExtension(rawArgs: string[]): Promise<void> {\n const { flags: args, name: raw } = resolveExtensionArgs(rawArgs, \"disable\");\n if (!raw) fail(\"Usage: rebase cloud extensions disable <name>\", undefined, \"usage\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const name = resolveExtensionAlias(raw!);\n\n try {\n const list = await fetchExtensions(client, projectId);\n const ext = list.extensions.find((e) => e.name === name);\n if (ext && !ext.manageable) {\n fail(\n `Extension ${name} cannot be managed on this project.`,\n ext.manageableReason ?? undefined,\n \"not_manageable\"\n );\n }\n if (ext?.requiresRestart && ext.enabled) {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Disabling ${name} restarts the project's database. Continue?`\n });\n }\n\n const res = await client.functions.invoke<DisableResult>(\"extensions\", { projectId,\nextensionName: name }, { path: \"disable\" });\n emit(\n () => success(res.message || `Disabled ${name}`),\n {\n success: res.success,\n extension: res.extension,\n dropped: res.dropped,\n preloadRemoved: res.preloadRemoved,\n restarted: res.restarted ?? false,\n message: res.message\n }\n );\n } catch (e) {\n reportError(e, \"Failed to disable extension\");\n }\n}\n\nexport function printExtensionsHelp(): void {\n printGroupHelp({\n command: \"cloud extensions\",\n title: \"Postgres extensions\",\n actions: [\n { action: \"list\",\ndescription: \"List extensions and their state\" },\n { action: \"enable\",\nargs: \"<name>\",\ndescription: \"Enable one — `pgvector` is accepted for `vector`\" },\n { action: \"disable\",\nargs: \"<name>\",\ndescription: \"Disable one\" }\n ],\n notes: [\"Enabling or disabling one restarts the database, so it needs --yes when nothing can prompt.\"]\n });\n}\n","/**\n * `rebase cloud settings` — a project's editable configuration.\n *\n * settings Show the current settings\n * settings set [flags] Update name / branch / repo / subdomain / platform rebuilds\n *\n * These are plain `projects` updates. A subdomain change is validated against\n * `check-subdomain` up front so the CLI fails with the real reason rather than a\n * generic collection error.\n */\nimport chalk from \"chalk\";\nimport { requireClient, requireProject, displayProjectRef, parseCloudArgs, emit, printGroupHelp, keyValues, success, fail, reportError } from \"./context\";\n\ninterface ProjectSettings {\n id: string | number;\n name?: string;\n subdomain?: string;\n gitRepoUrl?: string;\n gitBranch?: string;\n customDomain?: string;\n provider?: string;\n region?: string;\n platformRebuilds?: boolean | null;\n}\n\nexport async function settingsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"set\":\n await setSettings(rawArgs);\n break;\n case undefined:\n case \"show\":\n case \"list\":\n await showSettings(rawArgs);\n break;\n case \"--help\":\n printSettingsHelp();\n break;\n default:\n fail(`Unknown settings command: ${action}`, \"Run `rebase cloud settings --help`.\", \"unknown_command\");\n }\n}\n\nasync function showSettings(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud settings\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const p = (await client.data.collection(\"projects\").findById(projectId)) as ProjectSettings | undefined;\n if (!p) fail(`Project ${projectRef} not found.`, undefined, \"not_found\");\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⚙️ Settings — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Name\", p!.name],\n [\"Subdomain\", p!.subdomain],\n [\"Repository\", p!.gitRepoUrl],\n [\"Branch\", p!.gitBranch],\n [\"Custom domain\", p!.customDomain],\n [\"Provider\", p!.provider],\n [\"Region\", p!.region],\n [\"Platform rebuilds\", p!.platformRebuilds === false ? \"off\" : \"on\"]\n ]);\n console.log(\"\");\n },\n {\n projectId: String(p!.id),\n name: p!.name ?? null,\n subdomain: p!.subdomain ?? null,\n gitRepoUrl: p!.gitRepoUrl ?? null,\n gitBranch: p!.gitBranch ?? null,\n customDomain: p!.customDomain ?? null,\n provider: p!.provider ?? null,\n region: p!.region ?? null,\n platformRebuilds: p!.platformRebuilds !== false\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load settings\");\n }\n}\n\n/** `on`/`off` (or `true`/`false`) as a boolean, or null for anything else. */\nexport function parseOnOff(value: string): boolean | null {\n const v = value.trim().toLowerCase();\n if (v === \"on\" || v === \"true\") return true;\n if (v === \"off\" || v === \"false\") return false;\n return null;\n}\n\n/** Build the update patch from the flags actually supplied (pure/testable). */\nexport function buildSettingsPatch(args: {\n name?: string;\n subdomain?: string;\n repo?: string;\n branch?: string;\n /** Already parsed with {@link parseOnOff}. */\n platformRebuilds?: boolean;\n}): Record<string, string | boolean> {\n const patch: Record<string, string | boolean> = {};\n if (args.name !== undefined) patch.name = args.name;\n if (args.subdomain !== undefined) patch.subdomain = args.subdomain.toLowerCase();\n if (args.repo !== undefined) patch.gitRepoUrl = args.repo;\n if (args.branch !== undefined) patch.gitBranch = args.branch;\n if (args.platformRebuilds !== undefined) patch.platformRebuilds = args.platformRebuilds;\n return patch;\n}\n\n/** What `rebase cloud settings set` parses. Its page is the group's own. */\nexport const SET_SETTINGS_FLAGS = {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n /* Whether fleet upgrades rebuild this app from its source on each new\n framework release (on by default). Off keeps every deploy as built,\n and the platform deletes the copy of the source it holds. */\n \"--platform-rebuilds\": String\n} as const;\n\nasync function setSettings(rawArgs: string[]): Promise<void> {\n // `--project`/`-p` are globals and are not redeclared here; the rest is this\n // command's own. Strict rather than permissive: `--brnach main` used to be\n // dropped, and the command then reported \"nothing to change\".\n const { flags: args } = parseCloudArgs({\n spec: SET_SETTINGS_FLAGS,\n rawArgs,\n commandWords: 3, // cloud settings set\n command: \"cloud settings\",\n maxPositionals: 0\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n let platformRebuilds: boolean | undefined;\n if (args[\"--platform-rebuilds\"] !== undefined) {\n const parsed = parseOnOff(args[\"--platform-rebuilds\"]);\n if (parsed === null) {\n fail(`--platform-rebuilds takes on or off (got \"${args[\"--platform-rebuilds\"]}\").`, undefined, \"usage\");\n }\n platformRebuilds = parsed;\n }\n\n const patch = buildSettingsPatch({\n name: args[\"--name\"],\n subdomain: args[\"--subdomain\"],\n repo: args[\"--repo\"],\n branch: args[\"--branch\"],\n platformRebuilds\n });\n if (Object.keys(patch).length === 0) {\n fail(\"Nothing to update.\", \"Pass --name, --subdomain, --repo, --branch, or --platform-rebuilds.\", \"usage\");\n }\n\n try {\n if (typeof patch.subdomain === \"string\" && patch.subdomain) {\n const check = await client.functions\n .invoke<{ available: boolean; reason?: string }>(\"check-subdomain\", { subdomain: patch.subdomain })\n .catch(() => undefined);\n if (check && !check.available) {\n fail(`Subdomain \"${patch.subdomain}\" is not available${check.reason ? ` (${check.reason})` : \"\"}.`, undefined, \"subdomain_taken\");\n }\n }\n\n await client.data.collection(\"projects\").update(projectId, patch);\n emit(\n () => success(`Updated ${Object.keys(patch).join(\", \")} for project ${projectRef}`),\n { success: true,\nprojectId,\nupdated: patch }\n );\n } catch (e) {\n reportError(e, \"Failed to update settings\");\n }\n}\n\nexport function printSettingsHelp(): void {\n printGroupHelp({\n command: \"cloud settings\",\n title: \"Project configuration\",\n actions: [\n { action: \"show\",\ndescription: \"Name, subdomain, repository, branch and platform rebuilds as recorded\" },\n {\n action: \"set\",\n description: \"Change one or more of them\",\n flags: [\n [\"--name <name>\", \"Display name\"],\n [\"--subdomain <sub>\", \"The <slug>.rebase.website host\"],\n [\"--repo <git url>\", \"Repository to build from\"],\n [\"--branch <branch>\", \"Branch to build\"],\n [\"--platform-rebuilds <on|off>\", \"Rebuild this app on new framework releases (default on)\"]\n ]\n }\n ]\n });\n}\n","/**\n * Deployment lifecycle: `rebase cloud deployments list`, `rollback`, `cancel`.\n *\n * The rollback rule is the load-bearing part. A rollback is only honoured for a\n * SUCCESSFUL deploy that recorded an artefact — an `imageUrl` from a custom\n * build, or a `bundleId` from a managed deploy; anything else 409s\n * `deploy_not_rollbackable` server-side. So this module never offers — and\n * refuses to invoke — a rollback the server would reject, exactly mirroring the\n * console's `isRollbackable`.\n */\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n parseCloudArgs,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient,\n cloudRows,\n cloudRow\n} from \"./context\";\n\n/** A deployment row, as the data API hands it back (camel or snake columns). */\nexport interface DeploymentRow {\n id: string | number;\n status?: string;\n createdAt?: string | Date;\n created_at?: string | Date;\n finishedAt?: string | Date;\n finished_at?: string | Date;\n imageUrl?: string;\n image_url?: string;\n bundleId?: string;\n bundle_id?: string;\n rollbackOf?: string;\n rollback_of?: string;\n triggeredBy?: string;\n triggered_by?: string;\n triggerSource?: string;\n trigger_source?: string;\n triggeredByUserId?: string;\n triggered_by_user_id?: string;\n gitCommitHash?: string;\n gitCommitMessage?: string;\n deployMessage?: string;\n deploy_message?: string;\n frameworkVersion?: string;\n framework_version?: string;\n}\n\nfunction str(dep: DeploymentRow, camel: keyof DeploymentRow, snake: keyof DeploymentRow): string | null {\n const raw = (dep[camel] ?? dep[snake]) as unknown;\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : null;\n}\n\nfunction isoOf(dep: DeploymentRow, camel: keyof DeploymentRow, snake: keyof DeploymentRow): string | null {\n const raw = (dep[camel] ?? dep[snake]) as unknown;\n if (raw instanceof Date) return Number.isNaN(raw.getTime()) ? null : raw.toISOString();\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : null;\n}\n\nfunction deploymentImage(dep: DeploymentRow): string | null {\n return str(dep, \"imageUrl\", \"image_url\");\n}\n\n/**\n * The bundle a managed deploy shipped, or null.\n *\n * A managed deploy publishes no image — the platform image is the platform's\n * half of the runtime — so this is the artefact a rollback restores there.\n */\nfunction deploymentBundle(dep: DeploymentRow): string | null {\n return str(dep, \"bundleId\", \"bundle_id\");\n}\n\n/**\n * The backend's rule EXACTLY (`rollbackTargetOf`): a rollback is honoured only\n * for a successful deploy that recorded an image or a bundle. Any other row\n * 409s `deploy_not_rollbackable`.\n *\n * The bundle half was missing, and it took the whole managed tier with it: a\n * managed deploy records no image, so `rebase cloud rollback` refused every\n * managed project before it even asked the server.\n */\nexport function isRollbackable(dep: DeploymentRow): boolean {\n return dep.status === \"success\" && (deploymentImage(dep) !== null || deploymentBundle(dep) !== null);\n}\n\n/** The image or bundle a deploy shipped, as one comparable value. */\nfunction artefactOf(dep: DeploymentRow): string {\n const image = deploymentImage(dep);\n return image !== null ? `image:${image}` : `bundle:${deploymentBundle(dep) ?? \"\"}`;\n}\n\n/** What a rollback needs, said the way a refusal should say it. */\nconst ROLLBACKABLE_RULE = \"needs a successful deploy that recorded an image or a bundle\";\n\n/** finishedAt − createdAt in ms, or null (still running / missing / skewed). */\nexport function deploymentDurationMs(dep: DeploymentRow): number | null {\n const created = isoOf(dep, \"createdAt\", \"created_at\");\n const finished = isoOf(dep, \"finishedAt\", \"finished_at\");\n if (!created || !finished) return null;\n const a = new Date(created).getTime();\n const b = new Date(finished).getTime();\n if (Number.isNaN(a) || Number.isNaN(b)) return null;\n const ms = b - a;\n return ms >= 0 ? ms : null;\n}\n\nfunction formatDuration(ms: number): string {\n const totalSec = Math.max(0, Math.round(ms / 1000));\n if (totalSec < 60) return `${totalSec}s`;\n const m = Math.floor(totalSec / 60);\n const s = totalSec % 60;\n if (m < 60) return s ? `${m}m ${s}s` : `${m}m`;\n const h = Math.floor(m / 60);\n const mm = m % 60;\n return mm ? `${h}h ${mm}m` : `${h}h`;\n}\n\nconst TRIGGERED_BY = [\"user\", \"automation\", \"unknown\"] as const;\nconst TRIGGER_SOURCES = [\"console\", \"cli\", \"webhook\", \"unknown\"] as const;\n\nexport function triggerInfo(dep: DeploymentRow): { by: string; source: string; userId: string } {\n const byRaw = (dep.triggeredBy ?? dep.triggered_by) as unknown;\n const srcRaw = (dep.triggerSource ?? dep.trigger_source) as unknown;\n const by = typeof byRaw === \"string\" && (TRIGGERED_BY as readonly string[]).includes(byRaw) ? byRaw : \"unknown\";\n const source =\n typeof srcRaw === \"string\" && (TRIGGER_SOURCES as readonly string[]).includes(srcRaw) ? srcRaw : \"unknown\";\n return { by,\nsource,\nuserId: str(dep, \"triggeredByUserId\", \"triggered_by_user_id\") ?? \"\" };\n}\n\n/** Shape one deployment row into the stable JSON view the CLI publishes. */\nexport function deploymentView(dep: DeploymentRow): Record<string, unknown> {\n const durationMs = deploymentDurationMs(dep);\n return {\n id: String(dep.id),\n status: dep.status ?? null,\n createdAt: isoOf(dep, \"createdAt\", \"created_at\"),\n finishedAt: isoOf(dep, \"finishedAt\", \"finished_at\"),\n durationMs,\n image: deploymentImage(dep),\n // Published beside `image` rather than folded into it: they are\n // different artefacts from different halves of the platform, and a\n // script that pinned one would silently match the other.\n bundle: deploymentBundle(dep),\n rollbackOf: str(dep, \"rollbackOf\", \"rollback_of\"),\n isRollback: str(dep, \"rollbackOf\", \"rollback_of\") !== null,\n rollbackable: isRollbackable(dep),\n trigger: triggerInfo(dep),\n // The caller's own label for this deploy, and the framework THIS BUNDLE\n // installed. Without them a `--source` project's history is N rows\n // carrying an identical placeholder commit message, distinguishable only\n // by timestamp — which is not enough to answer \"did mine go out?\".\n //\n // Published as `builtAgainst` — the manifest field it comes from\n // (`runtime.builtAgainst`, read off the installed `@rebasepro/server`) —\n // and NOT as `frameworkVersion`, which is what `cloud status` calls the\n // framework the runtime IMAGE ships. The two are routinely different:\n // the image supplies the server, the bundle supplies the driver. Under\n // one name they read as the control plane disagreeing with itself, and\n // that is how this was reported as a bug.\n message: str(dep, \"deployMessage\", \"deploy_message\"),\n builtAgainst: str(dep, \"frameworkVersion\", \"framework_version\"),\n commit: {\n hash: str(dep, \"gitCommitHash\", \"gitCommitHash\"),\n message: str(dep, \"gitCommitMessage\", \"gitCommitMessage\")\n }\n };\n}\n\n/** What `POST /api/functions/deploy/cancel` answers. */\nexport interface CancelResponse {\n success: boolean;\n /**\n * The deployment that was cancelled — `null` when there was none.\n *\n * Nullable because \"nothing was in flight\" is a real, successful outcome\n * and not an error: a project's `status` column can claim `deploying` while\n * no deployment row backs the claim, and cancelling is what clears it.\n */\n deploymentId: string | null;\n buildJobDeleted: boolean;\n /** The request cleared a stuck `deploying` claim rather than stopping a build. */\n unstranded?: boolean;\n /** The status the project settled on when it did. */\n projectStatus?: string | null;\n}\n\n/**\n * What `rebase cloud cancel` says it did.\n *\n * Split out of the command because there are now two outcomes behind one\n * `success: true`, and only one of them is \"a build was stopped\". The control\n * plane learned to clear a project stranded at `deploying` with no deployment\n * row behind it — the state `prospector` was wedged in for five days — and it\n * reports that through this same endpoint. An unbranched caller printed\n * \"Cancelled deployment null\" for it, which reads as a bug in the thing that\n * had just fixed the bug.\n *\n * The ABSENT ID is what decides, not the `unstranded` flag: the flag is the\n * server being explicit, and it is the newer half of the contract. Branching on\n * the id means a client that meets a control plane which grew the behaviour\n * without the flag still says something true.\n */\nexport function cancelView(res: CancelResponse): {\n /** The headline, for `success()`. */\n headline: string;\n /** Dimmed follow-ups, printed under it. */\n notes: string[];\n /** The stable JSON view, which is what a piped run gets. */\n json: Record<string, unknown>;\n} {\n const deploymentId = res.deploymentId ? String(res.deploymentId) : null;\n const projectStatus =\n typeof res.projectStatus === \"string\" && res.projectStatus.length > 0 ? res.projectStatus : null;\n\n if (!deploymentId) {\n return {\n headline:\n \"No deploy was in flight — cleared this project's stuck 'deploying' status\" +\n (projectStatus ? ` (now ${chalk.bold(projectStatus)})` : \"\"),\n notes: [\"Its status claimed a deploy that no deployment backed. Redeploy is available again.\"],\n json: { success: true,\ndeploymentId: null,\nbuildJobDeleted: false,\nunstranded: true,\nprojectStatus }\n };\n }\n\n return {\n headline: `Cancelled deployment ${chalk.bold(deploymentId)}`,\n notes: res.buildJobDeleted ? [\"The build job was deleted.\"] : [],\n json: { success: true,\ndeploymentId,\nbuildJobDeleted: Boolean(res.buildJobDeleted),\nunstranded: Boolean(res.unstranded),\nprojectStatus }\n };\n}\n\nasync function fetchDeployments(client: CloudClient, projectId: string, limit = 100): Promise<DeploymentRow[]> {\n const res = await client.data.collection(\"deployments\").find({\n where: { project: [\"==\", projectId] },\n orderBy: [\"createdAt\", \"desc\"],\n limit\n });\n return cloudRows<DeploymentRow>(res.data);\n}\n\n/**\n * Rows shown when `--limit` is not given.\n *\n * History is unbounded and grows one row per deploy, so \"all of it\" is the\n * wrong default in both directions: a wall of near-identical lines in a\n * terminal, and — since JSON mode is entered automatically for any non-TTY\n * stdout — a project's entire history dumped at anything that pipes the\n * command. Recent deploys are what the question is almost always about.\n */\nexport const DEFAULT_DEPLOYMENTS_LIMIT = 20;\n\n/** Hard ceiling on `--limit`, matching the backend's own page size. */\nconst MAX_DEPLOYMENTS_LIMIT = 100;\n\n/** `--limit N`, bounded. A garbage value is a refusal, never a silent default. */\nexport function parseDeploymentsLimit(raw: number | undefined): number {\n if (raw === undefined) return DEFAULT_DEPLOYMENTS_LIMIT;\n if (!Number.isInteger(raw) || raw < 1 || raw > MAX_DEPLOYMENTS_LIMIT) {\n fail(`--limit must be a whole number between 1 and ${MAX_DEPLOYMENTS_LIMIT}.`, undefined, \"usage\");\n }\n return raw;\n}\n\nexport async function deploymentsListCommand(rawArgs: string[]): Promise<void> {\n // `--limit` is validated below and a typo of it must not silently fall back\n // to the default page — the refusal is the whole point of the bound.\n const { flags: args } = parseCloudArgs({\n spec: { \"--limit\": Number,\n\"--all\": Boolean },\n rawArgs,\n commandWords: 2, // cloud deployments\n command: \"cloud deployments list\",\n maxPositionals: 1 // the `list` action word, when written out\n });\n const limit = args[\"--all\"] ? MAX_DEPLOYMENTS_LIMIT : parseDeploymentsLimit(args[\"--limit\"]);\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const rows = await fetchDeployments(client, projectId, limit);\n const views = rows.map(deploymentView);\n // Never let a truncated list read as a complete one. `truncated` is in\n // the JSON for the same reason the note is in the human output.\n const truncated = views.length === limit;\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🚀 Deployments — project ${projectRef}`));\n console.log(\"\");\n if (!views.length) {\n console.log(chalk.gray(\" No deployments yet. Deploy with `rebase cloud deploy`.\"));\n console.log(\"\");\n return;\n }\n for (const v of views) {\n const dur = v.durationMs !== null ? formatDuration(v.durationMs as number) : chalk.gray(\"running\");\n const trig = (v.trigger as { source: string }).source;\n const roll = v.rollbackable ? chalk.green(\" ↺ rollbackable\") : \"\";\n console.log(\n ` ${chalk.gray(`[${v.id}]`)} ${colorStatus(v.status as string)} ${chalk.gray(String(v.createdAt ?? \"—\"))} ${dur} ${chalk.gray(trig)}${roll}`\n );\n // The label and the framework this bundle was built against\n // are what make one row distinguishable from the next;\n // indented under it so the status line stays scannable when\n // they are absent. Spelled \"built against\" so it cannot be\n // read as the framework `cloud status` reports, which is the\n // image's.\n const label = [v.message, v.builtAgainst ? `built against @rebasepro/* ${v.builtAgainst}` : null]\n .filter(Boolean)\n .join(\" · \");\n if (label) console.log(` ${chalk.gray(label)}`);\n }\n if (truncated) {\n console.log(\"\");\n console.log(chalk.gray(` Showing the ${limit} most recent. Use \\`--limit N\\` or \\`--all\\` for more.`));\n }\n console.log(\"\");\n },\n { projectId,\nlimit,\ntruncated,\ndeployments: views }\n );\n } catch (e) {\n reportError(e, \"Failed to list deployments\");\n }\n}\n\n/**\n * The deployment id `rollback`/`cancel` was given, if any.\n *\n * Both take an optional id, which is what made the old operand filter so easy\n * to trip: `rebase cloud rollback -p acme` — the documented way to act on an\n * unlinked project — read `--project`'s value as the id and refused with\n * \"Deployment acme not found\", and `cancel -p acme` sent \"acme\" to the server\n * as the deployment to cancel. Strict parsing consumes the flag with its value,\n * so an id given as a flag value is never mistaken for an argument.\n */\nexport function resolveDeploymentIdArg(rawArgs: string[], command: string) {\n const { flags, positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 2, // cloud <rollback|cancel>\n command,\n maxPositionals: 1\n });\n return { flags,\nid: positionals[0] };\n}\n\n/**\n * One deployment by id, when it belongs to `projectId`; undefined otherwise.\n *\n * A read that fails is \"not found\" too: the caller's refusal says so, and the\n * control plane checks the same ownership again before rolling back.\n */\nasync function deploymentOfProject(\n client: CloudClient,\n deploymentId: string,\n projectId: string\n): Promise<DeploymentRow | undefined> {\n let row: Record<string, unknown> | undefined;\n try {\n row = (await client.data.collection(\"deployments\").findById(deploymentId)) as Record<string, unknown> | undefined;\n } catch {\n return undefined;\n }\n if (!row) return undefined;\n const owner = row.project ?? row.projectId ?? row.project_id;\n const ownerId = typeof owner === \"object\" && owner !== null && \"id\" in owner ? owner.id : owner;\n if (ownerId !== undefined && ownerId !== null && String(ownerId) !== projectId) return undefined;\n return cloudRow<DeploymentRow>(row);\n}\n\nexport async function rollbackCommand(rawArgs: string[]): Promise<void> {\n // `rollback [deploymentId]` — the id, when given, is the only argument.\n const { flags: args, id: explicitId } = resolveDeploymentIdArg(rawArgs, \"cloud rollback\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // Fetch history — the only step here that can fail with a server error.\n let rows: DeploymentRow[];\n try {\n rows = await fetchDeployments(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to read deployment history\");\n }\n if (!rows!.length) fail(\"No deployments to roll back to.\", undefined, \"no_deployments\");\n\n // Select + validate the target OUTSIDE any catch — a refusal here is a\n // deliberate exit, never a server error to re-wrap.\n let target: DeploymentRow | undefined;\n if (explicitId) {\n // The page is the newest 100. An id named outright may be older, so it\n // is read on its own before it is called missing.\n target = rows!.find((d) => String(d.id) === explicitId) ?? await deploymentOfProject(client, explicitId, projectId);\n if (!target) fail(`Deployment ${explicitId} not found for project ${projectRef}.`, undefined, \"not_found\");\n // Refuse locally rather than let the server 409 — this is the safety\n // contract, mirrored from the backend's rollback rule.\n if (!isRollbackable(target!)) {\n fail(\n `Deployment ${explicitId} is not rollbackable (${ROLLBACKABLE_RULE}).`,\n \"List candidates with `rebase cloud deployments list`.\",\n \"deploy_not_rollbackable\"\n );\n }\n } else {\n const rollbackable = rows!.filter(isRollbackable);\n if (!rollbackable.length) {\n fail(\n `No rollbackable deployment found (${ROLLBACKABLE_RULE}).`,\n \"List history with `rebase cloud deployments list`.\",\n \"deploy_not_rollbackable\"\n );\n }\n const newest = rows![0];\n // A static app deployed on its own succeeded and recorded no bundle:\n // the backend serving now is the newest rollbackable deploy, and\n // re-deploying it changes nothing. What changed cannot be rolled back.\n if (newest.status === \"success\" && !isRollbackable(newest)) {\n fail(\n `The newest deployment, ${newest.id}, published a static app on its own, which cannot be rolled back yet; ` +\n `the backend deployment ${rollbackable[0].id} is the one serving now.`,\n \"Deploy the last good version of the app again, or name the deployment to roll back to: `rebase cloud rollback <id>`.\",\n \"deploy_not_rollbackable\"\n );\n }\n // Prefer the previous good artefact when the newest deploy is itself\n // good — rolling back to what is live, or to an earlier deploy of the\n // same image or bundle, is a no-op; otherwise (the newest failed) the\n // most recent good one.\n if (String(rollbackable[0].id) === String(newest.id)) {\n const live = artefactOf(newest);\n target = rollbackable.find((d) => artefactOf(d) !== live);\n if (!target) {\n fail(\n `Deployment ${newest.id} is live, and no earlier deployment shipped something else to roll back to.`,\n \"A rollback needs a project that has deployed successfully at least twice. List history with `rebase cloud deployments list`.\",\n \"deploy_not_rollbackable\"\n );\n }\n } else {\n target = rollbackable[0];\n }\n }\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Roll project ${projectRef} back to deployment ${target!.id}? This starts a new deployment.`\n });\n\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string };\n rolledBackTo: string;\n // Exactly one is non-null, and which one says whether a custom\n // build's image or a managed deploy's bundle is being restored.\n imageUrl: string | null;\n bundleId: string | null;\n }>(\"deploy\", { projectId,\ndeploymentId: String(target!.id),\nclient: \"cli\" }, { path: \"rollback\" });\n\n emit(\n () => {\n success(`Rolling back to deployment ${chalk.bold(String(target!.id))}`);\n keyValues([\n [\"New deployment\", res.deployment?.id ? String(res.deployment.id) : undefined],\n [\"Rolled back to\", res.rolledBackTo],\n // Only the one that applies. Printing \"Image: —\" at somebody\n // who has never had an image is the same wrong answer the\n // refusal used to give.\n [\"Image\", res.imageUrl ?? undefined],\n [\"Bundle\", res.bundleId ?? undefined]\n ]);\n console.log(chalk.gray(\" Follow it with `rebase cloud logs -f`.\"));\n console.log(\"\");\n },\n {\n success: true,\n deploymentId: res.deployment?.id ?? null,\n rolledBackTo: res.rolledBackTo,\n imageUrl: res.imageUrl ?? null,\n bundleId: res.bundleId ?? null\n }\n );\n } catch (e) {\n reportError(e, \"Failed to roll back\");\n }\n}\n\nexport async function cancelCommand(rawArgs: string[]): Promise<void> {\n const { flags: args, id: explicitId } = resolveDeploymentIdArg(rawArgs, \"cloud cancel\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Cancel the in-flight build for project ${projectRef}?`\n });\n\n try {\n const res = await client.functions.invoke<CancelResponse>(\n \"deploy\",\n explicitId ? { projectId,\ndeploymentId: explicitId } : { projectId },\n { path: \"cancel\" }\n );\n const view = cancelView(res);\n emit(\n () => {\n success(view.headline);\n for (const note of view.notes) console.log(chalk.gray(` ${note}`));\n console.log(\"\");\n },\n view.json\n );\n } catch (e) {\n const err = e as { status?: number };\n if (err?.status === 404) {\n fail(\"No deployment in progress to cancel.\", undefined, \"not_found\");\n }\n reportError(e, \"Failed to cancel deployment\");\n }\n}\n","/**\n * `rebase cloud start | stop | restart` — power operations.\n *\n * These flip the project's `status`, exactly as the console's `handleServerAction`\n * does: stop → `stopped`, start → `active`, restart → stop then start with a\n * brief pause in between (a real stop→start with genuine downtime). Stop and\n * restart cause downtime, so they require `--yes` in non-interactive use.\n */\nimport { requireClient, requireProject, displayProjectRef, parseCloudArgs, emit, confirmDestructive, success, reportError, type CloudClient } from \"./context\";\n\ntype PowerAction = \"start\" | \"stop\" | \"restart\";\n\nasync function setStatus(client: CloudClient, projectId: string, status: \"active\" | \"stopped\"): Promise<void> {\n await client.data.collection(\"projects\").update(projectId, { status });\n}\n\nexport async function powerCommand(action: PowerAction, rawArgs: string[]): Promise<void> {\n // Every key here is a global, so the spec is empty — declaring one would\n // replace the global in the merge while the global's other readers went on\n // reading the raw line. Strict rather than permissive: `stop --yse` used to\n // drop the flag and then refuse off a terminal for want of it.\n const { flags: args } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 2, // cloud start|stop|restart\n command: `cloud ${action}`,\n maxPositionals: 0\n });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // start is benign; stop and restart cause downtime and are gated.\n if (action !== \"start\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `${action === \"stop\" ? \"Stop\" : \"Restart\"} project ${projectRef}? This causes downtime.`\n });\n }\n\n try {\n if (action === \"stop\") {\n await setStatus(client, projectId, \"stopped\");\n emit(() => success(`Stopped project ${projectRef}`), { success: true,\nprojectId,\nstatus: \"stopped\" });\n } else if (action === \"start\") {\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Started project ${projectRef}`), { success: true,\nprojectId,\nstatus: \"active\" });\n } else {\n await setStatus(client, projectId, \"stopped\");\n await new Promise((r) => setTimeout(r, 1500));\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Restarted project ${projectRef}`), { success: true,\nprojectId,\nstatus: \"active\" });\n }\n } catch (e) {\n reportError(e, `Failed to ${action} project`);\n }\n}\n","/**\n * `rebase cloud usage [org] [--month YYYY-MM]`: what a project — or every\n * project of the selected organization — has used this month against its\n * included allowance, the overage so far, and where the month is heading.\n *\n * Reads `GET /usage/:projectId` and `GET /usage/org/:org` on the control plane,\n * the same reads as the console's usage panel. Their overage figures are the\n * overage report's own calculation, so they are what the invoice will carry;\n * the projection to the month's end is the one estimate, and says so. The\n * caveats the control plane sends (object storage not measured, multi-pod\n * projects undercounting requests, partial days) are printed with the numbers,\n * and are in `--json` unchanged. Read-only; any member of the organization.\n */\nimport chalk from \"chalk\";\nimport {\n displayProjectRef,\n emit,\n fail,\n getContextOrg,\n parseCloudArgs,\n reportError,\n requireClient,\n requireKnownAction,\n requireProject,\n type CloudClient\n} from \"./context\";\n\nexport const USAGE_FLAGS = { \"--month\": String } as const;\nexport const USAGE_ACTIONS = [\"org\"] as const;\n\n/** A caveat on the figures, as the control plane sends it. */\nexport interface CliUsageCaveat {\n code: string;\n message: string;\n count?: number;\n}\n\n/** One project's month, as `GET /usage/:projectId` answers it. */\nexport interface CliProjectUsage {\n projectId: string;\n month: string;\n complete: boolean;\n days: { day: string; requests: number; errors: number; missedSamples: number }[];\n totals: { requests: number; errors: number; daysRecorded: number; daysWithGaps: number };\n quotas: { requestsPerMonth: number | null };\n fraction: number;\n warn: boolean;\n overageEur: number;\n billed: boolean;\n projection: { requests: number; fraction: number; overageEur: number } | null;\n enforcement: { kind: string; message: string };\n caveats: CliUsageCaveat[];\n}\n\nexport interface CliOrgUsage {\n organizationId: string;\n month: string;\n complete: boolean;\n projects: (CliProjectUsage & { name: string | null })[];\n totals: { requests: number; errors: number; overageEur: number; projectedOverageEur: number | null };\n truncated: boolean;\n}\n\nconst MONTH_RE = /^\\d{4}-(0[1-9]|1[0-2])$/;\n\nconst count = (n: number) => new Intl.NumberFormat(\"en\").format(Math.round(n));\nconst eur = (n: number) => new Intl.NumberFormat(\"en\", { style: \"currency\", currency: \"EUR\" }).format(n);\nconst pct = (fraction: number) => {\n if (!(fraction > 0)) return \"0%\";\n const p = fraction * 100;\n return p < 1 ? \"<1%\" : `${Math.floor(p)}%`;\n};\n\n/** The allowance as a bar of 20 cells, coloured like the console: amber from 80%, red past it. */\nexport function usageBar(fraction: number): string {\n const cells = 20;\n const filled = Math.max(0, Math.min(cells, Math.round(Math.min(fraction, 1) * cells)));\n const bar = \"█\".repeat(filled) + \"░\".repeat(cells - filled);\n if (fraction > 1) return chalk.red(bar);\n if (fraction >= 0.8) return chalk.yellow(bar);\n return chalk.cyan(bar);\n}\n\nfunction printCaveats(caveats: CliUsageCaveat[]): void {\n if (caveats.length === 0) return;\n console.log(\"\");\n for (const c of caveats) console.log(chalk.gray(` · ${c.message}`));\n}\n\nfunction printProject(u: CliProjectUsage, label: string): void {\n console.log(\"\");\n console.log(chalk.bold(` 📈 Usage — ${label} — ${u.month} (UTC)${u.complete ? \"\" : \", so far\"}`));\n console.log(\"\");\n const included = u.quotas.requestsPerMonth;\n console.log(` Requests ${count(u.totals.requests)}${included !== null ? ` of ${count(included)} included` : \"\"}`);\n if (included !== null) console.log(` ${usageBar(u.fraction)} ${pct(u.fraction)}`);\n console.log(` 5xx errors ${count(u.totals.errors)}`);\n console.log(` Overage ${u.billed ? eur(u.overageEur) : chalk.gray(\"not charged\")}`);\n if (u.projection) {\n console.log(chalk.gray(` At this pace by month end: ${count(u.projection.requests)} requests, ${eur(u.projection.overageEur)} overage (an estimate)`));\n }\n if (u.days.length === 0) {\n console.log(\"\");\n console.log(chalk.gray(\" No usage recorded for this month.\"));\n }\n printCaveats(u.caveats);\n console.log(\"\");\n}\n\nfunction printOrg(u: CliOrgUsage): void {\n console.log(\"\");\n console.log(chalk.bold(` 📈 Usage — org ${u.organizationId} — ${u.month} (UTC)${u.complete ? \"\" : \", so far\"}`));\n console.log(\"\");\n if (u.projects.length === 0) {\n console.log(chalk.gray(\" This organization has no projects.\"));\n console.log(\"\");\n return;\n }\n const nameWidth = Math.max(7, ...u.projects.map((p) => (p.name ?? p.projectId).length));\n console.log(chalk.gray(` ${\"Project\".padEnd(nameWidth)} ${\"Requests\".padStart(12)} ${\"Allowance\".padStart(9)} ${\"Overage\".padStart(10)}`));\n for (const p of u.projects) {\n console.log(\n ` ${(p.name ?? p.projectId).padEnd(nameWidth)} ${count(p.totals.requests).padStart(12)} `\n + `${(p.quotas.requestsPerMonth !== null ? pct(p.fraction) : \"—\").padStart(9)} `\n + `${(p.billed ? eur(p.overageEur) : \"not charged\").padStart(10)}`\n );\n }\n console.log(\n chalk.bold(` ${\"Total\".padEnd(nameWidth)} ${count(u.totals.requests).padStart(12)} ${\"\".padStart(9)} ${eur(u.totals.overageEur).padStart(10)}`)\n );\n if (u.totals.projectedOverageEur !== null) {\n console.log(chalk.gray(` At this pace by month end: ${eur(u.totals.projectedOverageEur)} overage (an estimate)`));\n }\n if (u.truncated) console.log(chalk.gray(\" Only the first 200 projects are shown.\"));\n // Each caveat once, as the first project carrying it phrased it.\n const seen = new Set<string>();\n const caveats: CliUsageCaveat[] = [];\n for (const p of u.projects) {\n for (const c of p.caveats) {\n if (c.code === \"partial_days\" || c.code === \"multi_pod_undercount\" || c.code === \"not_billed\") {\n caveats.push({ ...c, message: `${p.name ?? p.projectId}: ${c.message}` });\n } else if (!seen.has(c.code)) {\n seen.add(c.code);\n caveats.push(c);\n }\n }\n }\n printCaveats(caveats);\n console.log(\"\");\n}\n\nasync function readProjectUsage(client: CloudClient, projectId: string, month?: string): Promise<CliProjectUsage> {\n return client.functions.invoke<CliProjectUsage>(\"usage\", undefined, {\n method: \"GET\",\n path: `${encodeURIComponent(projectId)}${month ? `?month=${encodeURIComponent(month)}` : \"\"}`\n });\n}\n\nasync function readOrgUsage(client: CloudClient, org: string, month?: string): Promise<CliOrgUsage> {\n return client.functions.invoke<CliOrgUsage>(\"usage\", undefined, {\n method: \"GET\",\n path: `org/${encodeURIComponent(org)}${month ? `?month=${encodeURIComponent(month)}` : \"\"}`\n });\n}\n\nexport async function usageCommand(rawArgs: string[]): Promise<void> {\n // Refused before the client is built: an unusable line costs no login round-trip.\n const parsed = parseCloudArgs({\n spec: USAGE_FLAGS,\n rawArgs,\n commandWords: 2, // cloud usage\n command: \"cloud usage\",\n maxPositionals: 1\n });\n const action = parsed.positionals[0];\n requireKnownAction(\"usage\", action, USAGE_ACTIONS);\n const month = parsed.flags[\"--month\"];\n if (month !== undefined && !MONTH_RE.test(month)) {\n fail(`\"${month}\" is not a month.`, \"Pass --month as YYYY-MM, e.g. --month 2026-09.\", \"usage\");\n }\n\n const { client, url } = await requireClient(rawArgs);\n\n if (action === \"org\") {\n const org = getContextOrg(url);\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\", \"no_org\");\n let usage: CliOrgUsage;\n try {\n usage = await readOrgUsage(client, org, month);\n } catch (e) {\n reportError(e, \"Failed to load usage\");\n }\n emit(() => printOrg(usage), usage);\n return;\n }\n\n const projectId = await requireProject(rawArgs, client);\n let usage: CliProjectUsage;\n try {\n usage = await readProjectUsage(client, projectId, month);\n } catch (e) {\n reportError(e, \"Failed to load usage\");\n }\n emit(() => printProject(usage, `project ${displayProjectRef(rawArgs) || projectId}`), usage);\n}\n","/**\n * `rebase cloud app-key [rotate]`: the key `rebase cloud init --claim` minted\n * on the project's app and wrote into `.env` as `REBASE_API_TOKEN`, and the\n * way its owner replaces it.\n *\n * A claim hands that key over to the person who claimed the project: it stops\n * expiring, because the app's `.env` runs on it. The agent that ran `init`\n * still holds a copy, so `rotate` mints a new key on the app, revokes every\n * earlier agent key, and answers the new one once. In a directory whose `.env`\n * sets `REBASE_API_TOKEN`, it is written there; anywhere else (CI, a hosted\n * frontend) the old key is refused until it is given the new one.\n *\n * Reads `GET /credentials/:projectId/app-key` and `POST\n * /credentials/:projectId/app-key/rotate` on the control plane, the same calls\n * as the console's Settings. Owners and admins, signed in: the routes require\n * `project:configure`, which no access-token capability grants.\n *\n * @module\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport {\n confirmDestructive,\n displayProjectRef,\n emit,\n note,\n parseCloudArgs,\n reportError,\n requireKnownAction,\n requireProject,\n requireSessionClient,\n success,\n warn,\n type CloudClient\n} from \"./context\";\nimport { API_TOKEN_ENV, dotenvSets, upsertDotenv } from \"./init\";\nimport { findProjectRoot } from \"../../utils/project\";\n\nexport const APP_KEY_FLAGS = {} as const;\nexport const APP_KEY_ACTIONS = [\"rotate\"] as const;\n\n/** An agent key on the app, as the control plane lists it. Never the key itself. */\nexport interface CliAgentKey {\n id: string;\n prefix: string | null;\n createdAt: string | null;\n expiresAt: string | null;\n}\n\n/** What a rotation answers: the new key, once. */\nexport interface CliRotatedAppKey {\n apiKey: string;\n keyId: string;\n scopes: string[];\n expiresAt: string | null;\n revoked: string[];\n}\n\nfunction isRotated(value: unknown): value is CliRotatedAppKey {\n return typeof value === \"object\" && value !== null\n && \"apiKey\" in value && typeof value.apiKey === \"string\" && value.apiKey.startsWith(\"rk_\")\n && \"keyId\" in value && typeof value.keyId === \"string\"\n && \"revoked\" in value && Array.isArray(value.revoked);\n}\n\nasync function listKeys(client: CloudClient, projectId: string): Promise<{ keys: CliAgentKey[] }> {\n return client.functions.invoke<{ keys: CliAgentKey[] }>(\"credentials\", undefined, {\n method: \"GET\",\n path: `${encodeURIComponent(projectId)}/app-key`\n });\n}\n\nasync function rotateKey(client: CloudClient, projectId: string): Promise<unknown> {\n return client.functions.invoke<unknown>(\"credentials\", {}, {\n path: `${encodeURIComponent(projectId)}/app-key/rotate`\n });\n}\n\nfunction printKeys(keys: CliAgentKey[], label: string): void {\n console.log(\"\");\n console.log(chalk.bold(` 🔑 App key — ${label}`));\n console.log(\"\");\n if (keys.length === 0) {\n console.log(chalk.gray(\" This app holds no agent key. Keys made in the project's admin panel are managed there.\"));\n console.log(\"\");\n return;\n }\n for (const key of keys) {\n const when = key.createdAt ? `created ${new Date(key.createdAt).toLocaleString()}, ` : \"\";\n const expiry = key.expiresAt ? `expires ${new Date(key.expiresAt).toLocaleString()}` : \"does not expire\";\n console.log(` ${key.prefix ? `${key.prefix}…` : key.id} ${chalk.gray(`${when}${expiry}`)}`);\n }\n console.log(\"\");\n console.log(chalk.gray(` Replace it with ${chalk.bold(\"rebase cloud app-key rotate\")}: the old key stops working at once.`));\n console.log(\"\");\n}\n\nexport async function appKeyCommand(rawArgs: string[]): Promise<void> {\n const parsed = parseCloudArgs({\n spec: APP_KEY_FLAGS,\n rawArgs,\n commandWords: 2, // cloud app-key\n command: \"cloud app-key\",\n maxPositionals: 1\n });\n const action = parsed.positionals[0];\n requireKnownAction(\"app-key\", action, APP_KEY_ACTIONS);\n\n const { client } = await requireSessionClient(rawArgs, \"replace a project's app key\");\n const projectId = await requireProject(rawArgs, client);\n const label = `project ${displayProjectRef(rawArgs) || projectId}`;\n\n if (action !== \"rotate\") {\n let listed: { keys: CliAgentKey[] };\n try {\n listed = await listKeys(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to read the app's keys\");\n }\n emit(() => printKeys(listed.keys, label), listed);\n return;\n }\n\n await confirmDestructive({\n yes: Boolean(parsed.flags[\"--yes\"]),\n prompt: `Rotate the app key of ${label}? Every earlier agent key stops working at once.`\n });\n\n let answer: unknown;\n try {\n answer = await rotateKey(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to rotate the app key\");\n }\n if (!isRotated(answer)) {\n reportError(new Error(\"The control plane's answer did not carry a key.\"), \"Failed to rotate the app key\");\n }\n const rotated = answer;\n\n // Where the old key was written, the new one goes: a directory whose `.env`\n // sets it is the one `init` wrote. Nowhere else — a `.env` that does not\n // set it is somebody else's.\n const root = findProjectRoot() ?? process.cwd();\n const dotenv = path.join(root, \".env\");\n const wroteDotenv = dotenvSets(dotenv, API_TOKEN_ENV);\n if (wroteDotenv) upsertDotenv(dotenv, API_TOKEN_ENV, rotated.apiKey);\n\n emit(() => {\n success(`Rotated the app key of ${label}.`);\n if (wroteDotenv) note(`Wrote the new key to ${dotenv} as ${API_TOKEN_ENV}.`);\n else {\n console.log(\"\");\n console.log(` ${chalk.bold(rotated.apiKey)}`);\n console.log(\"\");\n note(`Shown once. Set it as ${API_TOKEN_ENV} wherever the old key was used.`);\n }\n if (rotated.revoked.length > 0) note(`Revoked ${rotated.revoked.length} earlier agent key${rotated.revoked.length === 1 ? \"\" : \"s\"}.`);\n else warn(\"No earlier agent key was revoked: there was none, or the app did not answer the clean-up.\");\n }, wroteDotenv\n // Not repeated where it was written: this output can reach an agent's\n // transcript, and the point of rotating is a key the agent never saw.\n ? { keyId: rotated.keyId, scopes: rotated.scopes, expiresAt: rotated.expiresAt, revoked: rotated.revoked, dotenv }\n : { ...rotated, dotenv: null });\n}\n","/**\n * `rebase cloud service-key [rotate]`: the project's `REBASE_SERVICE_KEY`,\n * admin on the app's own API, and replacing it.\n *\n * The control plane derives the key from the project and a generation, and\n * injects it into the app. `rotate` issues the next generation and restarts\n * the app onto it in the background; the old key keeps working until that\n * restart has come up, and nothing after. Anything that copied the old key —\n * a script, a CI job, an agent's deployed code that printed it — is refused\n * from then on. A claim rotates it too.\n *\n * Without an action, prints the generation, when it was last rotated and\n * whether a rotation is still restarting the app. The key itself is\n * `rebase cloud env reveal REBASE_SERVICE_KEY`. Calls `GET` and `POST\n * /credentials/:projectId/service-key[/rotate]`, owners and admins, signed in.\n *\n * @module\n */\nimport chalk from \"chalk\";\nimport {\n confirmDestructive,\n displayProjectRef,\n emit,\n note,\n parseCloudArgs,\n reportError,\n requireKnownAction,\n requireProject,\n requireSessionClient,\n success,\n type CloudClient\n} from \"./context\";\n\nexport const SERVICE_KEY_FLAGS = {} as const;\nexport const SERVICE_KEY_ACTIONS = [\"rotate\"] as const;\n\n/** What `GET /credentials/:projectId/service-key` answers. Never the key. */\nexport interface CliServiceKeyStatus {\n generation: number;\n liveGeneration: number;\n rotatedAt: string | null;\n pending: boolean;\n}\n\n/** What a rotation answers. */\nexport interface CliServiceKeyRotation {\n generation: number;\n state: \"restarting\" | \"pending\";\n}\n\nasync function readStatus(client: CloudClient, projectId: string): Promise<CliServiceKeyStatus> {\n return client.functions.invoke<CliServiceKeyStatus>(\"credentials\", undefined, {\n method: \"GET\",\n path: `${encodeURIComponent(projectId)}/service-key`\n });\n}\n\nfunction printStatus(status: CliServiceKeyStatus, label: string): void {\n console.log(\"\");\n console.log(chalk.bold(` 🛡 Service key — ${label}`));\n console.log(\"\");\n console.log(` Generation ${status.generation}`);\n console.log(` Rotated ${status.rotatedAt ? new Date(status.rotatedAt).toLocaleString() : chalk.gray(\"never\")}`);\n if (status.pending) {\n console.log(\"\");\n console.log(chalk.yellow(\" The app has not restarted onto the newest key yet; the previous one still works until it has.\"));\n }\n console.log(\"\");\n console.log(chalk.gray(` Read it with ${chalk.bold(\"rebase cloud env reveal REBASE_SERVICE_KEY\")}; replace it with ${chalk.bold(\"rebase cloud service-key rotate\")}.`));\n console.log(\"\");\n}\n\nexport async function serviceKeyCommand(rawArgs: string[]): Promise<void> {\n const parsed = parseCloudArgs({\n spec: SERVICE_KEY_FLAGS,\n rawArgs,\n commandWords: 2, // cloud service-key\n command: \"cloud service-key\",\n maxPositionals: 1\n });\n const action = parsed.positionals[0];\n requireKnownAction(\"service-key\", action, SERVICE_KEY_ACTIONS);\n\n const { client } = await requireSessionClient(rawArgs, \"rotate a project's service key\");\n const projectId = await requireProject(rawArgs, client);\n const label = `project ${displayProjectRef(rawArgs) || projectId}`;\n\n if (action !== \"rotate\") {\n let status: CliServiceKeyStatus;\n try {\n status = await readStatus(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to read the service key's state\");\n }\n emit(() => printStatus(status, label), status);\n return;\n }\n\n await confirmDestructive({\n yes: Boolean(parsed.flags[\"--yes\"]),\n prompt: `Rotate the service key of ${label}? The app restarts onto a new key, and anything using the old one is refused once it has.`\n });\n\n let rotation: CliServiceKeyRotation;\n try {\n rotation = await client.functions.invoke<CliServiceKeyRotation>(\"credentials\", {}, {\n path: `${encodeURIComponent(projectId)}/service-key/rotate`\n });\n } catch (e) {\n reportError(e, \"Failed to rotate the service key\");\n }\n emit(() => {\n success(`Issued service key generation ${rotation.generation} for ${label}.`);\n note(rotation.state === \"pending\"\n ? \"A deploy is running: the next deploy carries the new key. The old one works until then.\"\n : \"The app is restarting onto it; the old key works until the restart has finished. Follow it with `rebase cloud service-key`.\");\n note(\"Read the new key with `rebase cloud env reveal REBASE_SERVICE_KEY` once the restart is done.\");\n }, rotation);\n}\n","/**\n * `rebase cloud activity`: the selected organization's audit log — who\n * deployed, set or deleted an env var (by name, never by value), added or\n * removed a domain, restored a backup, changed a member's role, minted a\n * token, deleted a project.\n *\n * Reads `GET /audit/org/:org` on the control plane, the same read as the\n * console's Activity page, behind the same gate: an owner or admin of the\n * organization. Read-only. Newest first; `--limit` sizes a page and the next\n * page is `--before <cursor>`, which the output prints when there is one.\n * `--json` is one value: `{ org, events, nextCursor }`, each event exactly as\n * the control plane sends it.\n */\nimport chalk from \"chalk\";\nimport {\n emit,\n fail,\n getContextOrg,\n note,\n noteBlank,\n parseCloudArgs,\n reportError,\n requireClient,\n requireProject\n} from \"./context\";\n\nexport const ACTIVITY_FLAGS = {\n \"--org\": String,\n \"--action\": String,\n \"--actor\": String,\n \"--limit\": String,\n \"--before\": String\n} as const;\n\n/** One event, as the control plane sends it. */\nexport interface CliAuditEvent {\n id: string;\n createdAt: string;\n action: string;\n target: string | null;\n projectId: string | null;\n projectLabel: string | null;\n actorKind: string;\n actorLabel: string | null;\n actorUserId: string | null;\n metadata: Record<string, unknown>;\n}\n\nconst MAX_LIMIT = 100;\n/** A project id (a UUID), as opposed to a slug to resolve. */\nconst PROJECT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** `2026-10-25 10:00 UTC`: one clock for everyone reading the same log. */\nfunction when(iso: string): string {\n return iso.length >= 16 ? `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC` : iso;\n}\n\n/** Who, in a few words: an email, a token's name and owner, a hook, the platform. */\nexport function actorText(event: CliAuditEvent): string {\n const label = event.actorLabel ?? event.actorUserId ?? \"unknown\";\n if (event.actorKind === \"token\") return `${label} [token]`;\n return label;\n}\n\nfunction show(value: unknown): string {\n if (value === null || value === undefined || value === \"\") return \"—\";\n return typeof value === \"object\" ? JSON.stringify(value) : String(value);\n}\n\n/** The line under an event, when its metadata says more than its action does. */\nexport function detailText(event: CliAuditEvent): string {\n const m = event.metadata ?? {};\n const changes = m.changes;\n if (changes && typeof changes === \"object\" && !Array.isArray(changes)) {\n return Object.entries(changes as Record<string, { from?: unknown; to?: unknown }>)\n .map(([field, c]) => `${field}: ${show(c?.from)} → ${show(c?.to)}`)\n .join(\", \");\n }\n if (event.action === \"member.role\") return `${show(m.from)} → ${show(m.to)}`;\n if (event.action === \"backup.restore\" && m.succeeded === false) return \"failed part way: the data may have changed\";\n if (event.action === \"domain.verify\") return m.verified === true ? \"verified\" : \"not verified yet\";\n if ((event.action === \"env.set\" || event.action === \"env.delete\") && m.previews === true) return \"preview override\";\n return \"\";\n}\n\nfunction print(org: string, events: CliAuditEvent[], nextCursor: string | null, filtered: boolean): void {\n console.log(\"\");\n console.log(chalk.bold(` 🧾 Activity — org ${org}`));\n console.log(\"\");\n if (events.length === 0) {\n console.log(chalk.gray(filtered ? \" No activity matches these filters.\" : \" Nothing has been recorded yet.\"));\n console.log(\"\");\n return;\n }\n const actionWidth = Math.max(6, ...events.map((e) => e.action.length));\n for (const e of events) {\n const project = e.projectLabel ?? (e.projectId ? \"(deleted project)\" : \"\");\n const target = e.target ? ` ${chalk.cyan(e.target)}` : \"\";\n console.log(\n ` ${chalk.gray(when(e.createdAt))} ${e.action.padEnd(actionWidth)}${target}`\n + `${project ? chalk.gray(` · ${project}`) : \"\"}`\n );\n const detail = detailText(e);\n console.log(chalk.gray(` ${\"\".padEnd(20)} by ${actorText(e)}${detail ? ` — ${detail}` : \"\"}`));\n }\n console.log(\"\");\n if (nextCursor) {\n noteBlank();\n note(chalk.gray(`More: rebase cloud activity --before ${nextCursor}` + \" (with the same filters)\"));\n }\n}\n\nexport async function activityCommand(rawArgs: string[]): Promise<void> {\n // Refused before the client is built: an unusable line costs no login round-trip.\n const parsed = parseCloudArgs({\n spec: ACTIVITY_FLAGS,\n rawArgs,\n commandWords: 2, // cloud activity\n command: \"cloud activity\",\n maxPositionals: 0\n });\n const flags = parsed.flags;\n let limit: number | undefined;\n if (flags[\"--limit\"] !== undefined) {\n const n = Number(flags[\"--limit\"]);\n if (!Number.isInteger(n) || n < 1 || n > MAX_LIMIT) {\n fail(`\"${flags[\"--limit\"]}\" is not a page size.`, `Pass --limit as a whole number from 1 to ${MAX_LIMIT}.`, \"usage\");\n }\n limit = n;\n }\n\n const { client, url } = await requireClient(rawArgs);\n const org = flags[\"--org\"] || getContextOrg(url);\n if (!org) {\n fail(\"No organization selected.\", `Pass ${chalk.bold(\"--org <id>\")} or run ${chalk.bold(\"rebase cloud use\")}.`, \"no_org\");\n }\n // `--project` narrows to one project; without it, the whole organization.\n // Resolved only when given — a linked directory does not narrow the log —\n // and a project id is passed as it is: a deleted project no longer\n // resolves, and \"who deleted it\" is a question this log answers.\n const projectFlag = flags[\"--project\"];\n const projectId = !projectFlag ? undefined\n : PROJECT_ID.test(projectFlag) ? projectFlag\n : await requireProject(rawArgs, client);\n\n const params = new URLSearchParams();\n if (projectId) params.set(\"project\", projectId);\n if (flags[\"--action\"]) params.set(\"action\", flags[\"--action\"]);\n if (flags[\"--actor\"]) params.set(\"actor\", flags[\"--actor\"]);\n if (limit !== undefined) params.set(\"limit\", String(limit));\n if (flags[\"--before\"]) params.set(\"before\", flags[\"--before\"]);\n const query = params.toString();\n\n let res: { events?: CliAuditEvent[]; nextCursor?: string | null };\n try {\n res = await client.functions.invoke<{ events?: CliAuditEvent[]; nextCursor?: string | null }>(\n \"audit\",\n undefined,\n { method: \"GET\", path: `org/${encodeURIComponent(org)}${query ? `?${query}` : \"\"}` }\n );\n } catch (e) {\n reportError(e, \"Failed to load the activity log\");\n }\n const events = res.events ?? [];\n const nextCursor = res.nextCursor ?? null;\n const filtered = Boolean(projectId || flags[\"--action\"] || flags[\"--actor\"]);\n emit(() => print(org, events, nextCursor, filtered), { org, events, nextCursor });\n}\n","/**\n * `rebase cloud notifications`: where the linked project's events are POSTed —\n * a Slack or Discord incoming webhook, a chat-ops bot, any https URL.\n *\n * rebase cloud notifications [list]\n * rebase cloud notifications add <url> [--events a,b] [--format json|slack] [--name <name>]\n * rebase cloud notifications test <id>\n * rebase cloud notifications remove <id> [--yes]\n *\n * The control plane's `/api/functions/notifications/webhooks` routes, the same\n * as the console's Settings → Notifications card. Any member of the\n * organization may list (URLs masked: a Slack webhook URL is a credential);\n * adding, testing and removing take the organization's owner or admin role.\n * The control plane refuses a URL that is not https or that resolves to a\n * private, loopback, link-local or metadata address, at add time and again at\n * every delivery. Each POST is signed: `X-Webhook-Signature: sha256=<hex HMAC\n * of the body>` with the secret `add` prints once.\n */\nimport chalk from \"chalk\";\nimport {\n confirmDestructive,\n displayProjectRef,\n emit,\n fail,\n note,\n parseCloudArgs,\n reportError,\n requireClient,\n requireKnownAction,\n requireProject,\n success,\n type CloudClient\n} from \"./context\";\n\n/** The events the control plane notifies about. */\nexport const NOTIFICATION_EVENTS = [\n \"deploy.failed\",\n \"deploy.succeeded\",\n \"deploy.rolled_back\",\n \"backup.unhealthy\",\n \"billing.payment_failed\",\n \"usage.threshold\",\n \"preview.paused\"\n] as const;\n\nexport const NOTIFICATIONS_ACTIONS = [\"list\", \"add\", \"test\", \"remove\"] as const;\nexport const NOTIFICATIONS_ADD_FLAGS = { \"--events\": String, \"--format\": String, \"--name\": String } as const;\n\n/** A destination, as the control plane lists it. */\nexport interface CliNotificationWebhook {\n id: string;\n name: string;\n url: string;\n events: string[];\n format: \"json\" | \"slack\";\n enabled: boolean;\n lastStatus: number | null;\n lastError: string;\n lastDeliveredAt: string | null;\n failureCount: number;\n createdAt: string | null;\n}\n\n/**\n * `--events deploy.failed,backup.unhealthy` as a list, refused when it names an\n * event that does not exist. Exported so its test drives the real parser.\n */\nexport function parseNotificationEvents(raw: string | undefined): string[] {\n if (raw === undefined) return [\"deploy.failed\"];\n const events = raw.split(\",\").map((e) => e.trim()).filter(Boolean);\n if (events.length === 0) fail(\"--events is empty.\", `Pick from: ${NOTIFICATION_EVENTS.join(\", \")}.`, \"usage\");\n for (const event of events) {\n if (!(NOTIFICATION_EVENTS as readonly string[]).includes(event)) {\n fail(`\"${event}\" is not a notification event.`, `Pick from: ${NOTIFICATION_EVENTS.join(\", \")}.`, \"usage\");\n }\n }\n return [...new Set(events)];\n}\n\nfunction lastDelivery(h: CliNotificationWebhook): string {\n if (!h.enabled) return chalk.gray(\"switched off\");\n if (!h.lastDeliveredAt || h.lastStatus === null) return chalk.gray(\"nothing sent yet\");\n const when = h.lastDeliveredAt.replace(\"T\", \" \").slice(0, 16) + \" UTC\";\n if (h.failureCount > 0 || h.lastStatus < 200 || h.lastStatus >= 300) {\n const status = h.lastStatus ? `HTTP ${h.lastStatus}` : \"no response\";\n return chalk.red(`failing: ${status} at ${when}, ${h.failureCount} in a row${h.lastError ? ` — ${h.lastError}` : \"\"}`);\n }\n return chalk.green(`delivered (HTTP ${h.lastStatus}) at ${when}`);\n}\n\nasync function listWebhooks(client: CloudClient, projectId: string): Promise<CliNotificationWebhook[]> {\n const res = await client.functions.invoke<{ webhooks?: CliNotificationWebhook[] }>(\"notifications\", undefined, {\n method: \"GET\",\n path: `webhooks?projectId=${encodeURIComponent(projectId)}`\n });\n return res.webhooks ?? [];\n}\n\nexport async function notificationsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n requireKnownAction(\"notifications\", action, NOTIFICATIONS_ACTIONS);\n\n // Every line is parsed before the client is built: a line the parser will\n // refuse costs no login round-trip.\n if (action === \"add\") {\n const { flags, positionals } = parseCloudArgs({\n spec: NOTIFICATIONS_ADD_FLAGS,\n rawArgs,\n commandWords: 3, // cloud notifications add\n command: \"cloud notifications add\",\n maxPositionals: 1\n });\n const url = positionals[0];\n if (!url) {\n fail(\n \"Usage: rebase cloud notifications add <url> [--events a,b] [--format json|slack]\",\n \"The URL is a positional argument: `--url` names the control plane in every cloud command.\",\n \"usage\"\n );\n }\n const events = parseNotificationEvents(flags[\"--events\"]);\n const format = flags[\"--format\"] ?? \"json\";\n if (format !== \"json\" && format !== \"slack\") fail(`--format must be json or slack, not \"${format}\".`, undefined, \"usage\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n let created: { webhook: CliNotificationWebhook; secret: string };\n try {\n created = await client.functions.invoke<{ webhook: CliNotificationWebhook; secret: string }>(\n \"notifications\",\n { projectId, url, events, format, ...(flags[\"--name\"] ? { name: flags[\"--name\"] } : {}) },\n { path: \"webhooks\" }\n );\n } catch (e) {\n reportError(e, \"Failed to add the notification webhook\");\n }\n emit(() => {\n success(`Notifications for ${events.join(\", \")} now go to ${chalk.bold(created.webhook.url)} [${created.webhook.id}]`);\n note(`Signing secret (shown once): ${chalk.bold(created.secret)}`);\n note(chalk.gray(\"Each POST carries X-Webhook-Signature: sha256=<hex HMAC-SHA256 of the body with this secret>.\"));\n note(chalk.gray(`Check it now: rebase cloud notifications test ${created.webhook.id}`));\n console.log(\"\");\n }, { projectId, webhook: created.webhook, secret: created.secret });\n return;\n }\n\n if (action === \"test\" || action === \"remove\") {\n const { flags, positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3,\n command: `cloud notifications ${action}`,\n maxPositionals: 1\n });\n const id = positionals[0];\n if (!id) {\n fail(`Usage: rebase cloud notifications ${action} <id>`, \"`rebase cloud notifications list` shows the ids.\", \"usage\");\n }\n const { client } = await requireClient(rawArgs);\n\n if (action === \"remove\") {\n await confirmDestructive({\n yes: Boolean(flags[\"--yes\"]),\n prompt: `Remove notification webhook ${id}? Events stop going to it at once.`\n });\n try {\n await client.functions.invoke(\"notifications\", undefined, { method: \"DELETE\", path: `webhooks/${encodeURIComponent(id)}` });\n } catch (e) {\n reportError(e, \"Failed to remove the notification webhook\");\n }\n success(`Notification webhook ${chalk.bold(id)} removed`);\n emit(() => {}, { success: true, id });\n return;\n }\n\n let result: { success: boolean; statusCode: number; error: string; attempts: number };\n try {\n result = await client.functions.invoke<{ success: boolean; statusCode: number; error: string; attempts: number }>(\n \"notifications\",\n {},\n { path: `webhooks/${encodeURIComponent(id)}/test` }\n );\n } catch (e) {\n reportError(e, \"Failed to send the test event\");\n }\n if (!result.success) {\n // A delivery the receiver refused is the answer, and a failure: exit 1.\n fail(\n `The test event was not delivered: ${result.statusCode ? `HTTP ${result.statusCode}` : \"no response\"}.`,\n result.error || undefined,\n \"delivery_failed\"\n );\n }\n success(`Test event delivered (HTTP ${result.statusCode})`);\n emit(() => {}, { id, ...result });\n return;\n }\n\n // list\n parseCloudArgs({ spec: {}, rawArgs, commandWords: action ? 3 : 2, command: \"cloud notifications\", maxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n let webhooks: CliNotificationWebhook[];\n try {\n webhooks = await listWebhooks(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to list notification webhooks\");\n }\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔔 Notifications — project ${displayProjectRef(rawArgs) || projectId}`));\n console.log(\"\");\n if (webhooks.length === 0) {\n console.log(chalk.gray(\" No notification webhooks. Add one with `rebase cloud notifications add <url>`.\"));\n console.log(chalk.gray(\" Which emails you get: the console's Account → Notifications.\"));\n console.log(\"\");\n return;\n }\n for (const h of webhooks) {\n console.log(` ${chalk.bold(h.name || h.url)} ${chalk.gray(`[${h.id}]`)}${h.format === \"slack\" ? chalk.gray(\" (Slack message)\") : \"\"}`);\n if (h.name) console.log(` ${chalk.gray(h.url)}`);\n console.log(` ${chalk.gray(h.events.join(\", \"))}`);\n console.log(` ${lastDelivery(h)}`);\n }\n console.log(\"\");\n },\n { projectId, webhooks }\n );\n}\n","/**\n * `rebase cloud resources` — what a project declares against what the platform\n * holds for it, and the one removal a deploy is not allowed to make.\n *\n * `rebase resources` reads the code. This reads the platform: each database\n * and bucket the project's deploys recorded, whether the last deploy's code\n * still declares it, and whether the platform made it. The two disagree in\n * exactly two ways worth a line — declared and not configured, which is a 501\n * waiting to happen, and provisioned and no longer declared, which is a\n * database the platform keeps, binds and bills until somebody prunes it.\n *\n * Pruning is here rather than in the deploy on purpose. A deploy that deleted\n * a database because a line went missing from a commit would be data deleted\n * by a push; this asks, names the key, and needs the project's admin role.\n */\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n parseCloudArgs,\n emit,\n confirmDestructive,\n requireKnownAction,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface ResourceRow {\n kind: \"database\" | \"bucket\";\n key: string;\n engine?: string;\n declared: boolean;\n provisioned: boolean;\n note?: string;\n}\n\n/** The action words `rebase cloud resources` dispatches. No word lists. */\nexport const DECLARED_RESOURCES_ACTIONS = [\"list\", \"prune\"] as const;\n\nexport async function declaredResourcesCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n // Through `requireKnownAction`, like every other group: a mistyped word\n // used to reach `fail`'s default code, so `resources lst` and a control\n // plane that fell over answered with the same `\"error\"`.\n requireKnownAction(\"resources\", action, DECLARED_RESOURCES_ACTIONS);\n if (action === \"prune\") {\n await pruneResource(rawArgs);\n return;\n }\n await listResources(rawArgs);\n}\n\nasync function listResources(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud resources\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await client.functions.invoke<{ resources: ResourceRow[] }>(\"resources\", undefined, {\n method: \"GET\",\n path: projectId\n });\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` Resources — project ${projectRef}`));\n if (res.resources.length === 0) {\n console.log(chalk.gray(\" Nothing recorded beyond the default database. Deploy once and this fills in.\"));\n console.log(\"\");\n return;\n }\n for (const kind of [\"database\", \"bucket\"] as const) {\n const rows = res.resources.filter(r => r.kind === kind);\n if (rows.length === 0) continue;\n console.log(\"\");\n console.log(` ${chalk.bold.underline(`${kind}s`)}`);\n for (const row of rows) {\n const mark = row.declared && (row.provisioned || row.kind === \"bucket\")\n ? chalk.green(\"✓\")\n : row.note ? chalk.yellow(\"○\") : chalk.gray(\"·\");\n const tags = [\n row.engine ? chalk.gray(row.engine) : \"\",\n row.declared ? chalk.gray(\"declared\") : chalk.yellow(\"not declared\"),\n row.provisioned ? chalk.gray(\"platform-provisioned\") : chalk.gray(\"your own\")\n ].filter(Boolean);\n console.log(` ${mark} ${chalk.bold(row.key)} ${tags.join(\" · \")}`);\n if (row.note) console.log(chalk.yellow(` └ ${row.note}`));\n }\n }\n console.log(\"\");\n },\n { projectId, resources: res.resources }\n );\n } catch (e) {\n reportError(e, \"Failed to list resources\");\n }\n}\n\nasync function pruneResource(rawArgs: string[]): Promise<void> {\n const { flags: args, positionals } = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud resources prune\n command: \"cloud resources prune\",\n maxPositionals: 2 // <kind> <key>\n });\n const [kind, key] = positionals;\n if (kind !== \"database\" || !key) {\n fail(\n \"Say what to prune: `rebase cloud resources prune database <key>`.\",\n \"Only a database can be pruned here; a bucket and its files are removed in the project's storage settings.\",\n \"invalid_argument\"\n );\n }\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Drop database \"${key}\" from project ${projectRef}? Its rows are gone for good; the platform keeps no copy.`\n });\n\n try {\n const res = await client.functions.invoke<{ removed: boolean; pendingRedeploy?: boolean }>(\n \"resources\",\n { projectId, kind, key },\n { path: \"prune\" }\n );\n success(`Removed database ${chalk.bold(key)} from project ${projectRef}.`);\n if (res.pendingRedeploy) {\n console.log(chalk.gray(\" Its connection string leaves the running backend at the next deploy.\"));\n }\n emit(() => {}, { projectId, kind, key, removed: res.removed });\n } catch (e) {\n reportError(e, `Failed to prune database \"${key}\"`);\n }\n}\n","/**\n * Per-action help for `rebase cloud`.\n *\n * `--help` was already answered centrally, but only per *group*: `rebase cloud\n * projects create --help` and `rebase cloud deploy --help` both fell through to\n * the index page, which lists groups and no flags at all. So the flags that\n * decide what those commands do — `--name`, `--subdomain`, `--type`, `--bundle`\n * — had no discoverable spelling anywhere. The way they were found on a real\n * first deploy was by reading `dist/index.es.js.map`. An agent cannot do that,\n * and neither should a person.\n *\n * Two rules hold this file honest:\n *\n * 1. **The spec is the source of truth, not this page.** `action-help.test.ts`\n * pairs every entry with the `arg` spec its command actually parses and\n * asserts they agree in both directions. A flag added to a command without\n * a line here is a failing test, not a page that is quietly a year old.\n * The pairing lives in the test rather than here on purpose: importing the\n * command modules to describe them would make `--help` depend on the code\n * it is meant to be readable without.\n * 2. **It answers in the reader's language.** Like every other page in this\n * family it goes through `emitHelp`, so a piped `--help` is a structured\n * description of the command rather than sixty lines of ANSI to scrape.\n */\nimport chalk from \"chalk\";\nimport { emitHelp, GLOBAL_HELP_FLAGS } from \"./context\";\nimport { ORG_CAPABILITIES, ORG_CAPABILITY_NAMES, TOKEN_CAPABILITIES, TOKEN_CAPABILITY_NAMES } from \"./token-capabilities\";\n\nexport interface ActionHelp {\n /** `cloud projects create` — no leading `rebase`. */\n command: string;\n /** The usage line, minus the `rebase ` prefix. */\n usage: string;\n /** One paragraph: what the command does, and what it does not. */\n summary: string;\n /** `[flag, description]`, in the order a reader needs them. */\n flags: Array<[string, string]>;\n examples: string[];\n /** Anything a caller gets wrong more than once. */\n notes?: string[];\n}\n\n/*\n * `GLOBAL_HELP_FLAGS` and `GLOBAL_SPEC_KEYS` moved to `context.ts`, next to the\n * `GLOBAL_CLOUD_FLAGS` they describe — the group pages print them too, and\n * `context` cannot import this module (this one imports it). `GLOBAL_SPEC_KEYS`\n * is derived from the spec now rather than listed a second time.\n */\n\nexport const ACTION_HELP: Record<string, ActionHelp> = {\n init: {\n command: \"cloud init\",\n usage: \"cloud init --claim [--name <name>] [--no-deploy]\",\n summary:\n \"Provision a project on Rebase Cloud with no account, push this project's collections to it, and print \"\n + \"its live URL and a claim link. Whoever opens the link and signs in owns the project; unclaimed, it is \"\n + \"deleted after 72 hours. Sets REBASE_BASE_URL in .env and links this directory to the project; after \"\n + \"the deploy, also REBASE_API_TOKEN, a key the app accepts for reading and writing data.\",\n flags: [\n [\"--claim\", \"Required: provision an unclaimed project and print the link that claims it\"],\n [\"--name, -n <name>\", \"What to call the app. Default: a generated name\"],\n [\"--no-deploy\", \"Provision and link only; push the collections later with `rebase cloud deploy`\"]\n ],\n examples: [\n \"rebase cloud init --claim\",\n \"rebase cloud init --claim --name \\\"Todo app\\\" --json\"\n ],\n notes: [\n \"The project's token is kept in ~/.rebase/credentials.json, never in the repository, and `rebase cloud` \"\n + \"commands in this directory use it until the project is claimed or expires.\",\n \"Claiming takes a signed-in browser session and a payment method on the claiming organization.\",\n \"With an account already: `rebase cloud projects create --link`.\"\n ]\n },\n\n claim: {\n command: \"cloud claim\",\n usage: \"cloud claim [--open]\",\n summary:\n \"Print the claim link of the project `rebase cloud init --claim` provisioned in this directory, and how long \"\n + \"is left before it is deleted unclaimed. Asks the control plane first, and refuses once the project has \"\n + \"been claimed.\",\n flags: [[\"--open\", \"Also open the link in a browser\"]],\n examples: [\"rebase cloud claim\", \"rebase cloud claim --open\", \"rebase cloud claim --json\"],\n notes: [\n \"The link exists only on the machine that ran `init --claim` (in ~/.rebase/credentials.json); the control \"\n + \"plane keeps a hash of it and cannot print it again.\",\n \"`rebase cloud status` and `rebase cloud whoami` show the same link while the project is unclaimed.\"\n ]\n },\n\n projects: {\n command: \"cloud projects\",\n usage: \"cloud projects <list|create|info|delete> [options]\",\n summary: \"List, create, inspect and delete projects in the selected organization.\",\n flags: [],\n examples: [\n \"rebase cloud projects list\",\n \"rebase cloud projects create --help\",\n \"rebase cloud projects info shop\",\n \"rebase cloud projects delete shop --yes\"\n ]\n },\n\n clusters: {\n command: \"cloud clusters\",\n usage: \"cloud clusters [list|add|verify|registry] [options]\",\n summary: \"The compute clusters tenants run on. Platform-admin only.\",\n flags: [],\n examples: [\n \"rebase cloud clusters\",\n \"rebase cloud clusters verify <cluster-id> --baseline\",\n \"rebase cloud clusters add --name gke-eu --provider gcp --region europe-west1 --kubeconfig ./kubeconfig\",\n \"rebase cloud clusters registry <cluster-id> --repository europe-west1-docker.pkg.dev/p/rlc-acme --push-service-account rlc-acme-push@p.iam.gserviceaccount.com --pull-key-file ./rlc-acme-pull.json\"\n ]\n },\n\n \"projects create\": {\n command: \"cloud projects create\",\n usage: \"cloud projects create --name <name> --subdomain <slug> [options]\",\n summary:\n \"Create a project. Unless --db says otherwise a managed database is attached in the \"\n + \"same call, because a project without one can never deploy — it sits at \"\n + \"status \\\"provisioning\\\" indefinitely, and that word does not mean work is underway.\",\n flags: [\n [\"--name, -n <name>\", \"Display name. Required (prompted only on a terminal)\"],\n [\"--subdomain <slug>\", \"The <slug>.rebase.website host. Required, and not editable afterwards\"],\n [\"--db <managed|byodb|none>\", \"Which database to attach. Default: managed\"],\n [\"--connection-string <url>\", \"The PostgreSQL URL, for --db byodb\"],\n [\"--org <id>\", \"Organization to create it in (default: the selected one)\"],\n [\"--link\", \"Link this directory to the new project\"],\n [\"--repo <url>\", \"Git repository to build from\"],\n [\"--branch <name>\", \"Git branch. Default: main\"],\n // Not a region picker. See the note below — the flags record where\n // the project is placed, and the beta has one place to put it.\n [\"--provider <gcp|hetzner|…>\", \"Which deploy target to record. Default: the one this control plane would use\"],\n [\"--region <region>\", \"Region recorded on the project. Default: that target's own region\"],\n [\"--cpu <n>\", \"vCPU per instance\"],\n [\"--memory <size>\", \"Memory per instance, e.g. 512Mi\"],\n [\"--replicas <n>\", \"Instance count\"],\n [\"--spot <true|false>\", \"Run on preemptible capacity\"],\n // Still parsed so an old script is told what happened. Documented\n // here because the parse is: a page silent about a flag the\n // command accepts is how the two drift.\n [\"--scale-to-zero <false>\", \"Retired: every backend is always on. `false` is ignored with a warning, `true` refused\"],\n [\"--db-instances <n>\", \"Database instance count\"],\n [\"--db-cpu <n>\", \"vCPU per database instance\"],\n [\"--db-memory <size>\", \"Memory per database instance\"],\n [\"--storage <mode>\", \"Object storage: shared-prefix or dedicated-bucket\"]\n ],\n examples: [\n \"rebase cloud projects create --name \\\"Shop\\\" --subdomain shop --link\",\n \"rebase cloud projects create --name Shop --subdomain shop --db none\",\n \"rebase cloud projects create --name Shop --subdomain shop --db byodb --connection-string \\\"$DATABASE_URL\\\"\"\n ],\n notes: [\n \"The subdomain cannot be changed in passing later — a typo here is a new project.\",\n \"A managed database is created at the project's FIRST DEPLOY, not here.\",\n \"--provider and --region are not a region picker. They record which of the control plane's \"\n + \"registered deploy targets this project belongs to; the private beta has one, so both \"\n + \"default to it and neither moves a project anywhere else.\"\n ]\n },\n\n \"db create\": {\n command: \"cloud db create\",\n usage: \"cloud db create --type <managed|byodb> [options]\",\n summary:\n \"Attach a database to the project. Required before the first deploy: a project with no \"\n + \"database stays at status \\\"provisioning\\\" forever, waiting for this command. \"\n + \"`rebase cloud projects create` now does it for you unless you passed --db none.\",\n flags: [\n [\"--type <managed|byodb>\", \"Platform-provisioned Postgres, or your own\"],\n [\"--connection-string <url>\", \"The PostgreSQL URL, for --type byodb\"],\n [\"--wait\", \"Wait for the database to answer (byodb only — see below)\"],\n [\"--timeout <seconds>\", \"Ceiling on --wait. Default: 300\"]\n ],\n examples: [\n \"rebase cloud db create --type managed\",\n \"rebase cloud db create --type byodb --connection-string \\\"$DATABASE_URL\\\" --wait\"\n ],\n notes: [\n \"A managed database is a CloudNativePG cluster of the project's own, in the project's \"\n + \"own namespace and backed up on its own schedule. It is created at the project's first \"\n + \"deploy: there is nothing to poll before then, so --wait says so and returns rather \"\n + \"than looping.\",\n \"`rebase cloud db test` legitimately fails before the first deploy.\",\n \"A project has exactly one database — attaching a second is refused, because the \"\n + \"platform reads one row and it becomes undefined which it deploys against.\"\n ]\n },\n\n \"db connect\": {\n command: \"cloud db connect\",\n usage: \"cloud db connect [--port <n>] [--reveal]\",\n summary:\n \"Open a local port that is the project's managed database, and hold it open until Ctrl-C. \"\n + \"A managed database lives inside the platform's cluster, so the host `db info` reports is \"\n + \"your backend's address for it and resolves to nothing on your machine; this is what makes \"\n + \"it reachable from here. Point psql, TablePlus, Drizzle Studio or pg_dump at the URL it \"\n + \"prints. The database still asks for its password — the tunnel is a network path, not a \"\n + \"credential.\",\n flags: [\n [\"--port <n>\", \"Local port to listen on. Default: 5432\"],\n [\"--reveal\", \"Print the password inside the connection URL\"]\n ],\n examples: [\n \"rebase cloud db connect\",\n \"rebase cloud db connect --port 6543\",\n \"rebase cloud db connect --reveal --project shop\"\n ],\n notes: [\n \"Requires the organization's owner or admin role — the same gate as the console's SQL \"\n + \"console, because it is the same capability.\",\n \"Piped or with --json it prints one object — host, port, database, username, \"\n + \"connectionString — and keeps serving, so a script can read the URL and connect.\",\n \"Connections go through the control plane, so they count against the project's own \"\n + \"database connection limit like any other client.\",\n \"Bring-your-own databases are refused: that host is already yours to reach, and there is \"\n + \"nothing for the platform to tunnel.\"\n ]\n },\n\n deploy: {\n command: \"cloud deploy\",\n usage: \"cloud deploy [app] [options]\",\n summary:\n \"Deploy an app of the linked project and follow the build to a terminal state, exiting \"\n + \"non-zero if it failed. With no app named, the repository's backend is deployed. It ends \"\n + \"on a summary: each app shipped and its URL, the deployment id, how long it took, and whether \"\n + \"the new version answers on those URLs.\",\n flags: [\n [\"--wait\", \"Follow to a terminal state. Already the default; here to be explicit\"],\n [\"--timeout <seconds>\", \"Ceiling on the follow. Default: 900\"],\n [\"--live-timeout <seconds>\", \"How long to wait for the new version to answer on its URLs. 0 skips the check. Default: 60\"],\n [\"--no-follow\", \"Return as soon as the build is triggered\"],\n [\"--message, -m <text>\", \"Label the release\"],\n [\"--bundle\", \"Force a managed-bundle deploy (the default for runtime: managed)\"],\n [\"--bundle-dir <path>\", \"Deploy a bundle that is already built\"],\n [\"--source <path>\", \"Upload this directory and build a container image from it\"],\n [\"--skip-type-check\", \"Compile without type checking, as `rebase build` does\"],\n [\"--skip-schema\", \"Keep the committed database schema instead of regenerating it\"],\n [\"--no-static\", \"Deploy the backend without folding the static apps into its bundle\"],\n [\"--no-source\", \"Do not upload the project's source beside a backend bundle\"],\n [\"--no-verify\", \"Skip the syntax check of the static apps' JavaScript\"],\n [\"--allow-downgrade\", \"Deploy a bundle built on an older framework release than the project runs\"],\n [\"--preview\", \"Serve this build on an address of its own and leave production untouched\"],\n [\"--preview-name <name>\", \"Name the preview, so deploying the same name again updates the same address. Implies --preview\"],\n [\"--eject\", \"Leave the managed runtime on purpose (ejects to a container image)\"]\n ],\n examples: [\n \"rebase cloud deploy\",\n \"rebase cloud deploy web --message \\\"add search\\\"\",\n \"rebase cloud deploy --preview\",\n \"rebase cloud deploy --preview-name new-quiz\",\n \"rebase cloud deploy --timeout 300 --json\"\n ],\n notes: [\n \"The summary is printed even when stdout is piped. Pass --json (or set REBASE_JSON=1) for one \"\n + \"JSON object instead: apps, hosts, live, liveChecks, durationMs and the deployment id.\",\n \"A failed deploy ends on one line naming the app and the reason, and exits non-zero. A deploy \"\n + \"that succeeded but could not be confirmed live within --live-timeout exits zero and says so.\",\n \"A project whose rebase.json declares runtime: managed deploys a bundle without --bundle.\",\n \"--source on a managed project is refused: it would swap the project onto a container image.\",\n \"A backend bundle deploy also uploads the project's source (what git tracks, never a .env), so a \"\n + \"platform upgrade can rebuild it on a newer release. If it is over 100 MB or the upload fails, \"\n + \"the deploy goes on without it and says so.\",\n \"A bundle older than the release the project runs is refused as FRAMEWORK_DOWNGRADE. Run \"\n + \"`rebase upgrade` and deploy again, or pass --allow-downgrade.\",\n \"Before uploading, every .js/.mjs/.cjs file and inline <script> in each static app's output is \"\n + \"parsed. A syntax error stops the deploy with its file:line:column (code syntax_error); \"\n + \"--no-verify skips the check.\",\n \"Undo a bad deploy with `rebase cloud rollback`: it restores the previous successful backend \"\n + \"deployment, static apps folded into it included. A static app deployed on its own \"\n + \"(`cloud deploy <app>`) cannot be rolled back yet; deploy its last good version again.\",\n \"--preview prints the preview's own address, https://<project>--<name>.rebase.website. A preview of the \"\n + \"backend runs its own, on an empty database of its own, with its static apps folded in. It uploads \"\n + \"no source and registers no apps or hostnames. `rebase cloud previews` lists and deletes previews.\",\n \"A backend preview is billed while it exists; the deploy prints what it costs per month, as the control \"\n + \"plane quotes it (`cost` under --json).\",\n \"A static app previewed on its own (`cloud deploy <app> --preview`) needs a control plane that serves \"\n + \"static sites by themselves. Rebase Cloud does not yet, and refuses it with PREVIEW_STATIC_UNSERVED; \"\n + \"nothing is published.\",\n \"A control plane without previews refuses --preview with previews_unavailable, and nothing is deployed.\"\n ]\n },\n\n previews: {\n command: \"cloud previews\",\n usage: \"cloud previews [list|delete] [options]\",\n summary:\n \"The project's preview deployments: builds made with `rebase cloud deploy --preview`, each served on \"\n + \"its own address while production keeps serving what it served before. `list` is the default.\",\n flags: [],\n examples: [\n \"rebase cloud previews\",\n \"rebase cloud previews delete new-quiz --yes\"\n ],\n notes: [\n \"A preview expires on its own when it has not been deployed to for a while; `list` says when.\",\n \"Deleting a preview stops its address answering and, for a backend preview, drops its database. \"\n + \"Production is never touched.\"\n ]\n },\n\n \"previews list\": {\n command: \"cloud previews list\",\n usage: \"cloud previews list\",\n summary: \"Every preview of the project: its name, its address, the app it serves, which backend it calls, and when it expires.\",\n flags: [],\n examples: [\"rebase cloud previews list\", \"rebase cloud previews list --json\"]\n },\n\n \"previews delete\": {\n command: \"cloud previews delete\",\n usage: \"cloud previews delete <name> [--yes]\",\n summary: \"Delete one preview: its address stops answering, and a backend preview's database is dropped. Alias: `rm`.\",\n flags: [],\n examples: [\"rebase cloud previews delete new-quiz --yes\"]\n },\n\n logs: {\n command: \"cloud logs\",\n usage: \"cloud logs [--runtime] [--follow] [--preview [<name>]] [--since <t>] [--tail <n>] [--grep <text>] [--level <l>] [--previous]\",\n summary: \"The latest build log, or what the running app prints with --runtime — from every pod, followed live with -f.\",\n flags: [\n [\"--runtime\", \"The running app's log instead of the build log\"],\n [\"--follow, -f\", \"Keep printing new lines until Ctrl-C (exits 0); with no --runtime, tail a build still running\"],\n [\"--preview [<name>]\", \"A preview's log instead of production's: its name, or the deployment id a preview deploy printed; alone, the project's only preview\"],\n [\"--since <t>\", \"With --runtime: start from 30s / 5m / 1h ago, or from an RFC3339 time\"],\n [\"--tail <n>\", \"With --runtime: at most this many lines per pod to start with (the control plane caps it at 2000)\"],\n [\"--grep <text>\", \"With --runtime: only lines containing the text (any case); `/re/flags` for a regular expression\"],\n [\"--level <l>\", \"With --runtime: only lines at this severity or worse — error, warn, info or debug\"],\n [\"--previous\", \"With --runtime: the last instance of a container that restarted, where a crash's reason usually is\"]\n ],\n examples: [\n \"rebase cloud logs\",\n \"rebase cloud logs -f\",\n \"rebase cloud logs --runtime -f\",\n \"rebase cloud logs --runtime -f --level error\",\n \"rebase cloud logs --runtime --since 15m --grep timeout\",\n \"rebase cloud logs --runtime --previous\",\n \"rebase cloud logs --preview new-quiz -f\",\n \"rebase cloud logs --runtime --json -f | jq -r 'select(.type == \\\"line\\\") | .text'\"\n ],\n notes: [\n \"Under --json a followed runtime log is NDJSON: one `{\\\"type\\\":\\\"line\\\",\\\"ts\\\",\\\"pod\\\",\\\"text\\\"}` per log line, \"\n + \"and `{\\\"type\\\":\\\"event\\\",\\\"event\\\":…}` when a pod starts, restarts or goes, or the connection drops and comes back.\",\n \"A container that restarts while you follow has its previous instance's last lines printed — usually the crash's reason.\"\n ]\n },\n\n status: {\n command: \"cloud status\",\n usage: \"cloud status\",\n summary:\n \"One-glance project status: URL, last deploy, runtime, database, storage — and \"\n + \"blockedOn/nextAction, which say whether the platform is working or waiting for you.\",\n flags: [],\n examples: [\"rebase cloud status\", \"rebase cloud status --project shop --json\"],\n notes: [\n \"Poll `status` only while blockedOn is null. Any other value names a command, and the \"\n + \"state will not change until you run it.\"\n ]\n },\n\n \"clusters add\": {\n command: \"cloud clusters add\",\n usage: \"cloud clusters add --name <n> --provider <gcp|aws|hetzner> --region <r> --kubeconfig <path> [options]\",\n summary:\n \"Register a cluster. Everything the row needs to serve tenants is set here, at insert, \"\n + \"because the control plane installs the cluster baseline on insert and reads the row to do it: \"\n + \"the name is what a Hetzner load balancer is adopted by, the address is what the ingress is pinned to.\",\n flags: [\n [\"--name <n>\", \"The cluster's name. On Hetzner, its load balancer is `<name>-ingress`\"],\n [\"--provider <gcp|aws|hetzner>\", \"Where it runs\"],\n [\"--region <r>\", \"Its region id (europe-west1, fsn1, hel1). Projects placed here deploy to it\"],\n [\"--kubeconfig <path>\", \"A kubeconfig for the control plane's identity on it\"],\n [\"--base-domain <d>\", \"Tenants on it are served at <subdomain>.<d>. Convention: <region>.rebase.website\"],\n [\"--ingress-address <ip>\", \"Its pinned ingress address — what the wildcard DNS record points at\"],\n [\"--platform-capacity\", \"This is capacity Rebase operates: projects placed in its region deploy here. Leave off for a customer's own cluster\"],\n [\"--backup-bucket <b>\", \"Its own object-storage bucket for database backups (with the three below)\"],\n [\"--backup-endpoint <url>\", \"S3 endpoint of that bucket, e.g. https://fsn1.your-objectstorage.com\"],\n [\"--backup-access-key-id <k>\", \"Key for the bucket\"],\n [\"--backup-secret-access-key <s>\", \"Secret for the bucket. Encrypted at rest\"]\n ],\n examples: [\n \"rebase cloud clusters add --name gke-eu --provider gcp --region europe-west1 --kubeconfig ./kubeconfig\",\n \"rebase cloud clusters add --name rebase-fsn1 --provider hetzner --region fsn1 --kubeconfig ./control-plane.kubeconfig \"\n + \"--base-domain fsn1.rebase.website --ingress-address 49.13.1.1 --platform-capacity \"\n + \"--backup-bucket rebase-fsn1-db-backups --backup-endpoint https://fsn1.your-objectstorage.com \"\n + \"--backup-access-key-id … --backup-secret-access-key …\"\n ],\n notes: [\n \"The backup flags go together; a bucket without a key is a cluster with no backup store.\",\n \"A Hetzner cluster registered with --platform-capacity must bring its own backup store.\"\n ]\n },\n\n \"clusters registry\": {\n command: \"cloud clusters registry\",\n usage: \"cloud clusters registry <cluster-id> --repository <host/project/repo> --push-service-account <email> --pull-key-file <key.json>\",\n summary:\n \"Give a customer's own cluster an image registry of its own. Its admin can read every Secret there, so \"\n + \"without one it is handed the platform's shared registry credentials, and every deploy to it says so. \"\n + \"With one, its builds push to this repository as this account, and its pods pull with this key only.\",\n flags: [\n [\"--repository <host/project/repo>\", \"The cluster's own Artifact Registry repository (Terraform output tenant_registry)\"],\n [\"--push-service-account <email>\", \"Writer on that repository only; the control plane impersonates it (push_service_account)\"],\n [\"--pull-key-file <key.json>\", \"The JSON key of the cluster's read-only account (pull_service_account). Sealed at write, never shown again\"],\n [\"--clear\", \"Forget the cluster's registry and go back to the shared one\"]\n ],\n examples: [\n \"rebase cloud clusters registry <cluster-id> --repository europe-west1-docker.pkg.dev/p/rlc-acme --push-service-account rlc-acme-push@p.iam.gserviceaccount.com --pull-key-file ./rlc-acme-pull.json\",\n \"rebase cloud clusters registry <cluster-id> --clear\"\n ],\n notes: [\n \"All three values go together: the control plane ignores a partial set and keeps the shared credentials.\",\n \"The repository and both accounts come from saas/infra/gcp/registry-linked-clusters.tf. Takes effect on each project's next deploy.\"\n ]\n },\n\n \"clusters verify\": {\n command: \"cloud clusters verify\",\n usage: \"cloud clusters verify <cluster-id> [--baseline]\",\n summary:\n \"Ask a registered cluster whether it can host tenants. Reports permissions.allowed and \"\n + \"permissions.denied, which is what names a missing RBAC grant.\",\n flags: [[\"--baseline\", \"Also check ingress-nginx, cert-manager and CloudNativePG\"]],\n examples: [\"rebase cloud clusters verify gke-europe-west1 --baseline\"],\n notes: [\"Exits non-zero when the verdict is `unusable`, so it works as a gate.\"]\n },\n\n /* ── The leaves that were undiscoverable ───────────────────────────\n *\n * Every entry below existed as a command with its own flag spec and no page\n * of its own, so `--help` fell through to its group's index — a list of\n * sibling actions and not one flag. `storage attach`'s six flags were read\n * out of `dist/index.es.js` by somebody deploying a real project, and the\n * only way to learn that `storage create` takes no flags at all was the\n * same one. The completeness check in `action-help.test.ts` now requires a\n * page for every command that names itself to `parseCloudArgs`.\n */\n\n \"resources prune\": {\n command: \"cloud resources prune\",\n usage: \"cloud resources prune database <key> [--yes]\",\n summary:\n \"Drop a platform-provisioned database that this project's code no longer declares. \"\n + \"A deploy never removes one — it keeps, binds and bills it — so this is where it goes. \"\n + \"Only a database: a bucket and its files are removed in the project's storage settings.\",\n flags: [],\n examples: [\"rebase cloud resources prune database analytics --yes\"],\n notes: [\n \"`--yes` is the global flag, listed below. Off a terminal this command refuses rather than assuming it.\",\n \"Refused while the code still declares the database, and for one the platform never made.\",\n \"Its connection string leaves the running backend at the next deploy.\"\n ]\n },\n\n \"projects delete\": {\n command: \"cloud projects delete\",\n usage: \"cloud projects delete <slug|id> [--yes]\",\n summary:\n \"Delete a project: its deployments, its database and its subdomain. The subdomain is \"\n + \"not reusable afterwards. Takes no options of its own — `--yes` is the global one.\",\n flags: [],\n examples: [\"rebase cloud projects delete shop --yes\"],\n notes: [\"Irreversible. Without --yes it prompts, and off a terminal it refuses rather than assuming.\"]\n },\n\n \"db backup\": {\n command: \"cloud db backup\",\n usage: \"cloud db backup <list|create|restore|status|download> [filename] [--yes]\",\n summary:\n \"Take, list, inspect, download and restore this project's database backups. \"\n + \"`list` is the default when no action is given.\",\n flags: [],\n examples: [\n \"rebase cloud db backup\",\n \"rebase cloud db backup create\",\n \"rebase cloud db backup status\",\n \"rebase cloud db backup restore base-20260831 --yes\",\n \"rebase cloud db backup download base-20260831\"\n ],\n notes: [\n \"`restore` replaces the live database. Nothing about it is undoable from here — `--yes`, the global flag listed below, is what skips that confirmation.\",\n \"Backups are the project's own: a base backup on a schedule, plus continuous WAL archiving for point-in-time recovery.\"\n ]\n },\n\n \"db pitr\": {\n command: \"cloud db pitr\",\n usage: \"cloud db pitr <status|restore|cutover|discard> [--target <timestamp>] [--yes]\",\n summary:\n \"Point-in-time recovery. `status` reports the recoverable window; `restore` stages a \"\n + \"recovered copy beside the live database; `cutover` repoints the app at that copy; \"\n + \"`discard` throws it away. `status` is the default.\",\n flags: [\n [\"--target <timestamp>\", \"The instant to recover to, ISO-8601. Defaults to the latest recoverable point\"]\n ],\n examples: [\n \"rebase cloud db pitr\",\n \"rebase cloud db pitr restore --target 2026-08-30T14:00:00Z\",\n \"rebase cloud db pitr cutover --yes\",\n \"rebase cloud db pitr discard\"\n ],\n notes: [\n \"`restore` does not touch the live database — `cutover` is the step that does. `--yes`, the global flag listed below, skips the confirmation on both.\",\n \"Recovery is only possible inside the window `status` reports. Check it first.\"\n ]\n },\n\n \"deployments list\": {\n command: \"cloud deployments list\",\n usage: \"cloud deployments [list] [--limit <n>] [--all]\",\n summary: \"The project's deployment history, newest first, with the status and image of each.\",\n flags: [\n [\"--limit <n>\", \"How many to return. Bounded; a value over the maximum is refused, not clamped\"],\n [\"--all\", \"Return the maximum instead of naming a limit\"]\n ],\n examples: [\n \"rebase cloud deployments\",\n \"rebase cloud deployments list --limit 5\",\n \"rebase cloud deployments --all --json\"\n ]\n },\n\n \"domains add\": {\n command: \"cloud domains add\",\n usage: \"cloud domains add <domain>\",\n summary:\n \"Register a custom domain on this project, beside any it already has, and print the DNS records to publish. \"\n + \"Registering is not verifying — run `domains verify <domain>` once the records are live.\",\n flags: [],\n examples: [\"rebase cloud domains add app.example.com\"],\n notes: [\n \"At a zone apex use the A record this prints, not a CNAME: a CNAME is invalid at an apex.\",\n \"Verification is a separate command because DNS propagation is not instant.\"\n ]\n },\n\n \"domains remove\": {\n command: \"cloud domains remove\",\n usage: \"cloud domains remove <domain>\",\n summary:\n \"Stop serving one custom domain. The project keeps its other domains and its <slug>.rebase.website host. \"\n + \"The domain may be left out when the project has only one. Aliases: `rm`, `delete`.\",\n flags: [],\n examples: [\"rebase cloud domains remove app.example.com\"]\n },\n\n \"env set\": {\n command: \"cloud env set\",\n usage: \"cloud env set KEY=VALUE | KEY VALUE | KEY --stdin [--secret] [--force] [--preview]\",\n summary:\n \"Set one environment variable on the project. Takes effect on the next deploy — \"\n + \"a running instance does not pick it up.\",\n flags: [\n [\"--secret\", \"Store it encrypted and never return it in a listing\"],\n [\"--force\", \"Set a build-time key (VITE_*, NEXT_PUBLIC_*, …) anyway, for a build that reads it at run time\"],\n [\"--stdin\", \"Read the value from standard input, so it never appears in `ps` or your shell history. Give only KEY\"],\n [\"--preview\", \"Set it for the project's previews only; production keeps its value\"]\n ],\n examples: [\n \"rebase cloud env set STRIPE_KEY=sk_live_… --secret\",\n \"rebase cloud env set STRIPE_KEY=sk_test_… --secret --preview\",\n \"rebase cloud env set LOG_LEVEL debug\",\n \"rebase cloud env set FEATURE_X= \"\n ],\n notes: [\n \"A value starting with `-` must use the KEY=VALUE form; the KEY VALUE form refuses it.\",\n \"`printf %s \\\"$STRIPE_KEY\\\" | rebase cloud env set STRIPE_KEY --stdin --secret` sets a value without putting it on the command line.\",\n \"Variables the platform sets for every project cannot be overridden — `env reveal` reads them.\"\n ]\n },\n\n \"env pull\": {\n command: \"cloud env pull\",\n usage: \"cloud env pull [--output <path>]\",\n summary:\n \"Write the project's variables to a local .env file. Secrets come through, so the file \"\n + \"this produces is a credential.\",\n flags: [[\"--output, --out <path>\", \"Where to write. Default: .env\"]],\n examples: [\n \"rebase cloud env pull\",\n \"rebase cloud env pull --output .env.production\"\n ],\n notes: [\"Add the file it writes to .gitignore before running it, not after.\"]\n },\n\n \"storage create\": {\n command: \"cloud storage create\",\n usage: \"cloud storage create\",\n summary:\n \"Provision platform-managed storage: a bucket and its credentials, written onto the \"\n + \"project and injected into the tenant at deploy time. Takes no options of its own — \"\n + \"region and naming come from the platform.\",\n flags: [],\n examples: [\"rebase cloud storage create\"],\n notes: [\n \"Creates billable infrastructure, and requires org admin rather than membership.\",\n \"The secret key is never displayed: it goes to the project record and to the tenant's environment.\",\n \"Redeploy afterwards — a running instance has no credentials for a bucket created after it started.\"\n ]\n },\n\n \"storage attach\": {\n command: \"cloud storage attach\",\n usage:\n \"cloud storage attach --bucket <name> --access-key-id <id> --secret-access-key <secret> \"\n + \"[--endpoint <url>] [--region <region>] [--force-path-style] [--source <key>]\",\n summary:\n \"Point the project at storage you already own — S3, R2, MinIO, any S3-compatible bucket. \"\n + \"The alternative to `storage create`, for a bucket the platform does not manage.\",\n flags: [\n [\"--bucket <name>\", \"The bucket name. Required\"],\n [\"--access-key-id <id>\", \"Required\"],\n [\"--secret-access-key <secret>\", \"Required. Stored encrypted and never returned\"],\n [\"--endpoint <url>\", \"For anything that is not AWS S3 — R2, MinIO, Backblaze\"],\n [\"--region <region>\", \"Bucket region. Default: the provider's own default\"],\n [\"--force-path-style\", \"Address as endpoint/bucket rather than bucket.endpoint. Needed by MinIO\"],\n [\"--source <key>\", \"Which declared bucket to configure. Default: the project's default bucket\"]\n ],\n examples: [\n \"rebase cloud storage attach --bucket assets --access-key-id … --secret-access-key …\",\n \"rebase cloud storage attach --source media --bucket media-eu --access-key-id … --secret-access-key …\",\n \"rebase cloud storage attach --bucket assets --access-key-id … --secret-access-key … \\\\\\n\"\n + \" --endpoint https://<account>.r2.cloudflarestorage.com --region auto\"\n ],\n notes: [\n \"All three of --bucket, --access-key-id and --secret-access-key, or none: a bucket with no \"\n + \"credentials reads as configured and fails on the first upload.\",\n \"Redeploy for the tenant to pick the credentials up.\"\n ]\n },\n\n deployments: {\n command: \"cloud deployments\",\n usage: \"cloud deployments [list] [options]\",\n summary: \"The project's deployment history. `list` is the only action, and the default.\",\n flags: [],\n examples: [\"rebase cloud deployments\", \"rebase cloud deployments list --limit 5\"]\n },\n\n webhooks: {\n command: \"cloud webhooks\",\n usage: \"cloud webhooks\",\n summary:\n \"Retired: it never delivered anything, and every action now exits 1 with code `command_retired`. \"\n + \"A project's events (deploy failed, backups, billing, usage) go to Slack, Discord or any URL with \"\n + \"`rebase cloud notifications`; a POST when rows of your app's own tables change is a WebhookDispatcher \"\n + \"in your app's code.\",\n flags: [],\n examples: [\"rebase cloud notifications add https://hooks.slack.com/services/…\"]\n },\n\n notifications: {\n command: \"cloud notifications\",\n usage: \"cloud notifications [list|add|test|remove] [options]\",\n summary:\n \"Where the linked project's events are POSTed: a Slack or Discord incoming webhook, or any https URL. \"\n + \"`list` (the default) shows each destination, masked, with the outcome of its last delivery; any \"\n + \"member of the organization may read it. `add`, `test` and `remove` take the owner or admin role. \"\n + \"Which emails you get is set in the console, under Account → Notifications. A token manages them with \"\n + \"the `notifications` capability on the organization (`rebase cloud tokens create --can notifications`).\",\n flags: [],\n examples: [\n \"rebase cloud notifications\",\n \"rebase cloud notifications add https://hooks.slack.com/services/T000/B000/XXXX\",\n \"rebase cloud notifications test 6f1c…\",\n \"rebase cloud notifications remove 6f1c… --yes\"\n ]\n },\n\n \"notifications add\": {\n command: \"cloud notifications add\",\n usage: \"cloud notifications add <url> [--events <list>] [--format json|slack] [--name <name>]\",\n summary:\n \"Send the project's events to a URL. The control plane refuses a URL that is not https, or that \"\n + \"resolves to a private, loopback, link-local or metadata address, now and at every delivery. \"\n + \"Prints the signing secret once.\",\n flags: [\n [\"--events <list>\", \"Comma-separated: deploy.failed, deploy.succeeded, deploy.rolled_back, backup.unhealthy, billing.payment_failed, usage.threshold, preview.paused. Default: deploy.failed\"],\n [\"--format <json|slack>\", \"json (default): the event's facts plus a `text` line Slack reads as-is. slack: `{ text }` only\"],\n [\"--name <name>\", \"What it is called in listings\"]\n ],\n examples: [\n \"rebase cloud notifications add https://hooks.slack.com/services/T000/B000/XXXX\",\n \"rebase cloud notifications add https://discord.com/api/webhooks/1/abc/slack --events deploy.failed,backup.unhealthy\",\n \"rebase cloud notifications add https://ops.example.com/rebase --events deploy.failed,deploy.succeeded --name pager\"\n ],\n notes: [\n \"The URL is a positional argument: `--url` names the control plane in every cloud command.\",\n \"Each POST carries `X-Webhook-Signature: sha256=<hex HMAC-SHA256 of the raw body>` with the secret, \"\n + \"`X-Webhook-Event`, and an `X-Webhook-Delivery` id that is the same on every retry of one delivery.\",\n \"Discord takes Slack's format at its webhook URL with `/slack` appended.\"\n ]\n },\n\n \"notifications test\": {\n command: \"cloud notifications test\",\n usage: \"cloud notifications test <id>\",\n summary:\n \"POST a `notification.test` event now and report what the receiver answered. Exits 1, code \"\n + \"`delivery_failed`, when it was not delivered.\",\n flags: [],\n examples: [\"rebase cloud notifications test 6f1c…\"]\n },\n\n \"notifications remove\": {\n command: \"cloud notifications remove\",\n usage: \"cloud notifications remove <id> [--yes]\",\n summary: \"Stop sending events to a destination. Adding it again mints a new signing secret.\",\n flags: [],\n examples: [\"rebase cloud notifications remove 6f1c… --yes\"]\n },\n\n billing: {\n command: \"cloud billing\",\n usage: \"cloud billing [setup|checkout|invoices|upcoming]\",\n summary:\n \"The selected organization's billing. Bare, it prints the billing account, the card on \"\n + \"file and what the linked project costs per month; `setup` attaches a card (one-time, \"\n + \"opens a browser); `checkout` opens a Stripe session for one project; `invoices` lists \"\n + \"the issued invoices with Stripe's hosted page for each; `upcoming` previews the next \"\n + \"invoice of every subscription. Organization-scoped, not project-scoped.\",\n flags: [\n [\"--limit <n>\", \"`invoices` only: how many to list, newest first. Default 24, at most 100\"]\n ],\n examples: [\n \"rebase cloud billing\",\n \"rebase cloud billing setup\",\n \"rebase cloud billing checkout --project shop\",\n \"rebase cloud billing invoices --json\",\n \"rebase cloud billing upcoming\"\n ],\n notes: [\n \"`setup` comes before the first deploy: without a card the control plane answers 402, and `deploy` refuses before it builds.\",\n \"A token reaches billing with the `billing` capability on the organization (`rebase cloud tokens create --can billing --org <id>`). \"\n + \"A token made before that capability existed still works for one release, and each answer warns that it will stop.\"\n ]\n },\n\n \"app-key\": {\n command: \"cloud app-key\",\n usage: \"cloud app-key [rotate]\",\n summary:\n \"The key `rebase cloud init --claim` minted on the project's app and wrote into .env as REBASE_API_TOKEN. \"\n + \"Claiming the project hands it over: it stops expiring. Without an action, lists the app's agent keys \"\n + \"(never their value). `rotate` mints a new key, revokes every earlier agent key at once, and writes the \"\n + \"new one into a .env that already sets REBASE_API_TOKEN, or prints it once. Owners and admins, signed in.\",\n flags: [],\n examples: [\n \"rebase cloud app-key\",\n \"rebase cloud app-key rotate\",\n \"rebase cloud app-key rotate --yes --json\"\n ],\n notes: [\n \"Anything still using the old key (a hosted frontend, CI) is refused until it is given the new one.\",\n \"Keys made in the app's own admin panel are not touched.\",\n \"It runs with your login: no access-token capability grants it, so REBASE_TOKEN is refused.\"\n ]\n },\n \"service-key\": {\n command: \"cloud service-key\",\n usage: \"cloud service-key [rotate]\",\n summary:\n \"The project's REBASE_SERVICE_KEY, admin on the app's own API. Without an action, prints its generation, \"\n + \"when it was last rotated and whether the app is still restarting onto the newest one (never the key: \"\n + \"that is `rebase cloud env reveal REBASE_SERVICE_KEY`). `rotate` issues a new key and restarts the app \"\n + \"onto it; the old key works until the restart has finished and nothing after. Refused while a deploy is \"\n + \"running. Owners and admins, signed in.\",\n flags: [],\n examples: [\n \"rebase cloud service-key\",\n \"rebase cloud service-key rotate\",\n \"rebase cloud service-key rotate --yes --json\"\n ],\n notes: [\n \"Anything that copied the old key (a script, a CI job) is refused once the restart has finished.\",\n \"Claiming a project rotates its service key too.\",\n \"It runs with your login: no access-token capability grants it, so REBASE_TOKEN is refused.\"\n ]\n },\n usage: {\n command: \"cloud usage\",\n usage: \"cloud usage [org] [--month YYYY-MM]\",\n summary:\n \"Requests the linked project has used this month (UTC) against its included allowance, the 5xx errors, \"\n + \"the overage so far and where the month is heading at this pace. `org` lists every project of the \"\n + \"selected organization with the organization's total. The overage is counted exactly as the invoice \"\n + \"counts it; the month-end figure is an estimate. Read-only; any member of the organization.\",\n flags: [\n [\"--month <YYYY-MM>\", \"A past month instead of the current one\"]\n ],\n examples: [\n \"rebase cloud usage\",\n \"rebase cloud usage --month 2026-09 --json\",\n \"rebase cloud usage org\"\n ],\n notes: [\n \"The figures carry their limits as `caveats`: object storage is not measured yet, a project that can run \"\n + \"two or more app pods undercounts requests, and days with missed samples are partial.\",\n \"A month's overage is billed on the following month's invoice.\",\n \"A token reads it with the `logs` capability on the project (`rebase cloud tokens create --can logs`); \"\n + \"`usage org` lists the projects the token holds it on.\"\n ]\n },\n\n activity: {\n command: \"cloud activity\",\n usage: \"cloud activity [--project <id|slug>] [--action <area|action>] [--actor <email>] [--limit <n>]\",\n summary:\n \"The selected organization's audit log, newest first: who deployed, rolled back, set or deleted an \"\n + \"environment variable (by name, never by value), added or removed a domain, created, restored or \"\n + \"downloaded a backup, changed compute, stopped or deleted a project, added a member or changed a role, \"\n + \"and created or revoked an access token. Owners and admins of the organization.\",\n flags: [\n [\"--action <area|action>\", \"An area (deploy, deploy_hook, env, domain, backup, pitr, database, extension, storage, project, org, member, token) or a full action such as env.set\"],\n [\"--actor <email>\", \"Only what this person did, their tokens included\"],\n [\"--limit <n>\", \"Events per page, 1 to 100 (default 50)\"],\n [\"--before <cursor>\", \"The next page: the cursor the previous page printed\"],\n [\"--org <id>\", \"Another organization than the selected one\"]\n ],\n examples: [\n \"rebase cloud activity\",\n \"rebase cloud activity --action env --json\",\n \"rebase cloud activity --project shop --actor ana@example.com\"\n ],\n notes: [\n \"--project narrows to one project's events; a deleted project's id still works.\",\n \"Times are UTC. A project that was deleted still shows by the name it had.\",\n \"A token reads it only with the `audit` capability on the organization \"\n + \"(`rebase cloud tokens create --can audit --org <id>`), and only while you are its owner or admin.\",\n \"The same log is the Activity page in the console.\"\n ]\n },\n\n /* ── The graph, and the dials ───────────────────────────────────────\n *\n * `resources` is what the project declares against what the platform\n * holds; `compute` is CPU, memory, replicas and what they cost. They were\n * one word once, which is how `rebase cloud resources` came to mean the\n * dials and `rebase resources` the graph — the same word for two things,\n * one letter of context apart.\n *\n * `compute` is two pages rather than one, because they answer different\n * questions: bare is \"what does this project have, and what does it cost\",\n * `set` is \"what may I change it to\". The prices are not repeated here —\n * the control plane quotes them and both pages say so, which is the only\n * version of this that cannot go stale. */\n\n resources: {\n command: \"cloud resources\",\n usage: \"cloud resources [list|prune] [options]\",\n summary:\n \"Each database and bucket this project's deploys recorded: whether the last deploy's \"\n + \"code still declares it, and whether the platform made it. A deploy never removes a \"\n + \"provisioned database when its declaration goes — that would be data deleted by a \"\n + \"push — so it keeps, binds and bills it until `prune` names it.\",\n flags: [],\n examples: [\n \"rebase cloud resources\",\n \"rebase cloud resources --json\",\n \"rebase cloud resources prune database analytics\"\n ],\n notes: [\n \"`rebase resources` reads the code; this reads the platform. The two disagreeing is the point of the page.\",\n \"For CPU, memory, replicas and cost, that is `rebase cloud compute`.\"\n ]\n },\n\n compute: {\n command: \"cloud compute\",\n usage: \"cloud compute [set] [options]\",\n summary:\n \"What this project reserves, and what the control plane would invoice for it. Bare, it \"\n + \"prints every dial and an itemised €/month; `set` changes one. An empty dial means the \"\n + \"platform default, which moves when the default moves — a dial pinned to the same \"\n + \"number does not.\",\n flags: [],\n examples: [\n \"rebase cloud compute\",\n \"rebase cloud compute --json\",\n \"rebase cloud compute set --help\"\n ],\n notes: [\n \"The price is the control plane's own quote for these dials, itemised line by line — not a tier, and not a number this CLI computes.\"\n ]\n },\n\n \"compute set\": {\n command: \"cloud compute set\",\n usage: \"cloud compute set [--cpu <n>] [--memory <size>] [--replicas <n>] [...]\",\n summary:\n \"Change one or more of a project's dials. At least one is required: a patch with nothing \"\n + \"in it is a typo, and reporting success for a change nobody made is worse than refusing.\",\n flags: [\n [\"--cpu <n>\", \"App CPU request per instance, e.g. 500m or 2. Default: 100m, bursting to 2\"],\n [\"--memory <size>\", \"App memory request per instance, e.g. 512Mi or 2Gi. Default: 384Mi, bursting to 2Gi\"],\n [\"--replicas <n>\", \"Instances that always exist — the autoscaler's floor, and what is billed at rest\"],\n [\"--spot <true|false>\", \"Preemptible capacity: cheaper, and restarted without notice\"],\n [\"--db-instances <n>\", \"1–3. 1 is a single instance with no failover; 2 adds an automatic standby\"],\n [\"--db-cpu <n>\", \"Database CPU request per instance. Default: 160m\"],\n [\"--db-memory <size>\", \"Database memory request per instance. Default: 1Gi\"],\n [\"--storage <mode>\", \"Object storage: shared-prefix or dedicated-bucket\"],\n [\"--autoscale-max <n>\", \"1–16. The ceiling the app may reach, and the worst case it may be billed\"],\n [\"--autoscale-cpu-target <pct>\", \"10–95. CPU utilisation the autoscaler holds, against the request. Default: 70\"],\n [\"--no-autoscale\", \"Turn autoscaling off. The only way to: a ceiling at or below --replicas is refused\"]\n ],\n examples: [\n \"rebase cloud compute set --cpu 500m --memory 2Gi\",\n \"rebase cloud compute set --replicas 2 --autoscale-max 6\",\n \"rebase cloud compute set --db-instances 2 --db-memory 4Gi\"\n ],\n notes: [\n \"Run `rebase cloud compute` first — it prints the current dials and the €/month this project is quoted.\",\n \"Applied immediately: the app rolls its pods and the subscription is prorated from today. A change that restarts the database waits for a maintenance window.\",\n \"The valid ranges are the target cluster's, not this CLI's — GKE Autopilot bills a 250m/512Mi floor and rewrites a memory:CPU ratio outside 1:1–6.5:1, a Hetzner node has neither constraint. The control plane refuses what it cannot honour and names the field.\"\n ]\n },\n\n /* ── Session, link, and the operations with no flags of their own ────\n *\n * Every one of these fell through to the index page, which lists groups\n * and not one flag — so `login --password`, `link`'s positional URL and\n * the `-y` that `stop` requires had no discoverable spelling. They take\n * few options, and that is exactly what a reader needs told. */\n\n login: {\n command: \"cloud login\",\n usage: \"cloud login [--email <address>] [--password <password> | --code]\",\n summary:\n \"Sign in to the control plane and write the session to ~/.rebase/credentials.json. \"\n + \"Prompts for whatever is missing when attached to a terminal, and refuses rather than \"\n + \"hangs when it is not.\",\n flags: [\n [\"--email, -e <address>\", \"The account's email. Prompted when omitted, or REBASE_CLOUD_EMAIL\"],\n [\"--password <password>\", \"Discouraged: a password written here is recorded in your shell history and visible in the process table. Prefer the prompt, or REBASE_CLOUD_PASSWORD\"],\n [\"--code\", \"Sign in with a 6-digit code emailed to you instead of a password: the way in for accounts made with Google, GitHub or LinkedIn. Needs a terminal\"]\n ],\n examples: [\n \"rebase cloud login\",\n \"rebase cloud login --email me@example.com\",\n \"rebase cloud login --code --email me@example.com\",\n \"rebase cloud login --url https://cloud.example.com\"\n ],\n notes: [\n \"At a terminal with no password given, login asks whether to use your password or an emailed code, when the control plane sends codes.\",\n \"With two-factor authentication on, login then asks for the code from your authenticator app (or a recovery code), whichever way you signed in.\",\n \"Without a terminal, a code or a second factor cannot be typed: create an access token in the console (Settings → Access tokens) and set REBASE_TOKEN instead.\",\n \"--password warns, once, before the request: by the time a login succeeds the password is already in the history file.\",\n \"CI should not log in at all: `rebase cloud tokens create` mints a token for REBASE_TOKEN. Where a login is \"\n + \"still wanted, REBASE_CLOUD_EMAIL and REBASE_CLOUD_PASSWORD are how a secret store hands the \"\n + \"credentials over without them appearing on a command line.\",\n \"In a directory whose .rebase/cloud.json names a control plane you have not signed in to before, login \"\n + \"names it and asks first, and refuses without a terminal: a cloned repository does not choose where \"\n + \"your password goes. Pass --url <that host> to sign in there on purpose.\"\n ]\n },\n\n logout: {\n command: \"cloud logout\",\n usage: \"cloud logout [--url <origin>]\",\n summary:\n \"Forget the session for a control plane. Idempotent — logging out when you are not \"\n + \"logged in is a success, and `wasLoggedIn` in the JSON is how a script tells the two apart.\",\n flags: [],\n examples: [\"rebase cloud logout\"]\n },\n\n whoami: {\n command: \"cloud whoami\",\n usage: \"cloud whoami\",\n summary:\n \"Who this session is, which control plane it is against, and what this directory is linked to. \"\n + \"With REBASE_TOKEN set, what the token may do instead.\",\n flags: [],\n examples: [\"rebase cloud whoami\", \"rebase cloud whoami --json\"]\n },\n\n tokens: {\n command: \"cloud tokens\",\n usage: \"cloud tokens <list|create|revoke> [options]\",\n summary:\n \"API tokens for CI and agents. A token acts as your account, narrowed to what it was created \"\n + \"for on one project; with REBASE_TOKEN set, every `rebase cloud` command uses it instead of \"\n + \"your login. `list` is the default.\",\n flags: [],\n examples: [\n \"rebase cloud tokens\",\n \"rebase cloud tokens create --project shop --can deploy,logs\",\n \"rebase cloud tokens revoke 3f2a9c1e --yes\"\n ],\n notes: [\n \"Managing tokens takes your `rebase cloud login` session: a token cannot list, create or revoke tokens.\"\n ]\n },\n\n \"tokens list\": {\n command: \"cloud tokens list\",\n usage: \"cloud tokens list\",\n summary: \"Your tokens: what each may do and on which project, when it expires, and when it was last used.\",\n flags: [],\n examples: [\"rebase cloud tokens list\", \"rebase cloud tokens list --json\"]\n },\n\n \"tokens create\": {\n command: \"cloud tokens create\",\n usage: \"cloud tokens create --can <capabilities> [--project <slug>] [--org <id>] [--name <name>] [--expires-in <days>]\",\n summary:\n \"Create a token for one project — the linked one unless --project names another — holding only \"\n + \"the capabilities --can names. `billing`, `audit` and `notifications` act on an organization instead: \"\n + \"--org, else the project's own, else the selected one; a token may hold only those. The token is \"\n + \"printed once, as the `export REBASE_TOKEN=…` line to hand to CI.\",\n flags: [\n [\"--can <capabilities>\", `Comma-separated or repeated: ${[...TOKEN_CAPABILITY_NAMES, ...ORG_CAPABILITY_NAMES].join(\", \")}`],\n [\"--org <id>\", \"The organization billing, audit and notifications are for\"],\n [\"--name <name>\", \"What to call it. Defaults to the project and its capabilities\"],\n [\"--expires-in <days>\", \"Days until it stops working. Default: it does not expire\"]\n ],\n examples: [\n \"rebase cloud tokens create --can deploy\",\n \"rebase cloud tokens create --project shop --can deploy,logs --name \\\"GitHub Actions\\\" --expires-in 90\",\n \"rebase cloud tokens create --project shop --can env,database\",\n \"rebase cloud tokens create --can billing,audit --org 3f2a9c1e --name invoices\"\n ],\n notes: [\n ...TOKEN_CAPABILITY_NAMES.map(name => `${name}: ${TOKEN_CAPABILITIES[name].label}.`),\n ...ORG_CAPABILITY_NAMES.map(name => `${name}: ${ORG_CAPABILITIES[name].label}.`),\n \"A token never holds more than your account does when it is used, and cannot create tokens.\"\n ]\n },\n\n \"tokens revoke\": {\n command: \"cloud tokens revoke\",\n usage: \"cloud tokens revoke <id> [--yes]\",\n summary: \"Revoke a token. Anything still using it is refused from then on.\",\n flags: [],\n examples: [\"rebase cloud tokens revoke 3f2a9c1e\", \"rebase cloud tokens revoke 3f2a9c1e --yes\"]\n },\n\n link: {\n command: \"cloud link\",\n usage: \"cloud link [<url>] [--project <slug>]\",\n summary:\n \"Bind this directory to a backend, by writing .rebase/cloud.json. With a cloud project \"\n + \"(picked interactively, or named with --project) the rest of the family needs no flags. \"\n + \"With a positional URL it links straight at a running Rebase API — no control plane, no \"\n + \"login — which is what makes the multi-repo workflow available to self-hosters.\",\n flags: [],\n examples: [\n \"rebase cloud link\",\n \"rebase cloud link --project shop\",\n \"rebase cloud link https://api.example.com\"\n ],\n notes: [\n \"A positional URL is verified before it is written: an address that does not answer is still linked, but you are told.\",\n \"A direct link is one backend, not a control plane. The rest of the `cloud` family refuses in a directory linked that way — unlink first, or pass `--project` — so that `login` can never send your control-plane password to the linked host.\",\n \".rebase/cloud.json is not a secret and is not your credentials — those live in ~/.rebase/credentials.json.\"\n ]\n },\n\n unlink: {\n command: \"cloud unlink\",\n usage: \"cloud unlink\",\n summary:\n \"Remove this directory's link. Idempotent, like logout: `unlinked: false` says there was \"\n + \"nothing to remove.\",\n flags: [],\n examples: [\"rebase cloud unlink\"]\n },\n\n use: {\n command: \"cloud use\",\n usage: \"cloud use [<org>]\",\n summary:\n \"Select the active organization — the one `projects create`, `billing` and `orgs` act on. \"\n + \"Named, it is set; omitted, you pick from the ones this account belongs to.\",\n flags: [],\n examples: [\"rebase cloud use\", \"rebase cloud use acme\"]\n },\n\n open: {\n command: \"cloud open\",\n usage: \"cloud open\",\n summary:\n \"Open the console in a browser — the linked project's page when this directory is linked, \"\n + \"the dashboard otherwise. The URL is the result, so a piped run prints it instead.\",\n flags: [],\n examples: [\"rebase cloud open\"]\n },\n\n rollback: {\n command: \"cloud rollback\",\n usage: \"cloud rollback [<deploymentId>] [--yes]\",\n summary:\n \"Put a previous successful deployment back into service. Without an id, the most recent \"\n + \"rollbackable deployment that is not the live one. History is appended, never rewound: \"\n + \"a rollback is a new deployment row pointing back at the old one.\",\n flags: [],\n examples: [\n \"rebase cloud rollback\",\n \"rebase cloud deployments list\",\n \"rebase cloud rollback 214 --yes\"\n ],\n notes: [\n \"A static app deployed on its own (`rebase cloud deploy <app>`) records no bundle, so its \"\n + \"deployments are not rollbackable yet: deploy its last good version again. Static apps \"\n + \"folded into the backend's bundle (a plain `rebase cloud deploy`) roll back with it.\",\n \"`rebase cloud deployments list` marks which rows are rollbackable. One that is not is refused here rather than by a 409 from the control plane.\"\n ]\n },\n\n cancel: {\n command: \"cloud cancel\",\n usage: \"cloud cancel [<deploymentId>] [--yes]\",\n summary:\n \"Stop the build in flight for this project. Without an id, whichever one is deploying. \"\n + \"Also the way out of a project whose status claims a deploy that no deployment row backs.\",\n flags: [],\n examples: [\"rebase cloud cancel\", \"rebase cloud cancel 214 --yes\"]\n },\n\n start: {\n command: \"cloud start\",\n usage: \"cloud start\",\n summary: \"Bring a stopped project back into service.\",\n flags: [],\n examples: [\"rebase cloud start\"]\n },\n\n stop: {\n command: \"cloud stop\",\n usage: \"cloud stop [--yes]\",\n summary:\n \"Stop the project. This is downtime, so it is confirmed — pass --yes to skip the prompt, \"\n + \"which a non-interactive run must.\",\n flags: [],\n examples: [\"rebase cloud stop\", \"rebase cloud stop --yes\"]\n },\n\n restart: {\n command: \"cloud restart\",\n usage: \"cloud restart [--yes]\",\n summary:\n \"Stop the project and start it again. A real stop and start, with genuine downtime in \"\n + \"between, so it is confirmed like `stop`.\",\n flags: [],\n examples: [\"rebase cloud restart --yes\"]\n },\n\n cron: {\n command: \"cloud cron\",\n usage: \"cloud cron [list|logs] [options]\",\n summary:\n \"The deployed app's cron jobs and their recorded runs, read from the app itself with your \"\n + \"`rebase cloud` login. Read-only: the login is exchanged for a token that reads cron and \"\n + \"nothing else, is bound to this project and expires within minutes. `list` is the default.\",\n flags: [],\n examples: [\n \"rebase cloud cron\",\n \"rebase cloud cron logs nightly-digest\",\n \"rebase cloud cron logs nightly-digest --limit 5 --json\"\n ],\n notes: [\n \"To change, disable or trigger a job, use the app's own admin panel.\",\n \"`rebase cloud debug logs` shows what jobs printed to the pod's output; this shows every recorded run.\"\n ]\n },\n\n \"cron list\": {\n command: \"cloud cron list\",\n usage: \"cloud cron list [--host <hostname>]\",\n summary:\n \"Every job the app schedules: its schedule, its state, when it last ran and how long it took, \"\n + \"when it runs next, and the last error of a job that failed.\",\n flags: [[\"--host <hostname>\", \"Read this address instead of the project's own\"]],\n examples: [\"rebase cloud cron list\", \"rebase cloud cron list --json\"]\n },\n\n \"cron logs\": {\n command: \"cloud cron logs\",\n usage: \"cloud cron logs <job> [--limit <n>] [--host <hostname>]\",\n summary:\n \"One job's recorded runs, newest first: when each started, how long it took, whether it failed \"\n + \"and why, and every line it logged with `ctx.log`.\",\n flags: [\n [\"--limit <n>\", \"How many runs. Default: 50\"],\n [\"--host <hostname>\", \"Read this address instead of the project's own\"]\n ],\n examples: [\"rebase cloud cron logs nightly-digest\", \"rebase cloud cron logs nightly-digest --limit 5 --json\"]\n },\n\n metrics: {\n command: \"cloud metrics\",\n usage: \"cloud metrics\",\n summary: \"Live CPU, memory and disk for the project's running units, as the control plane reports them.\",\n flags: [],\n examples: [\"rebase cloud metrics\", \"rebase cloud metrics --json\"]\n }\n};\n\n/** Print one action's page — human, or its JSON description when piped. */\nexport function printActionHelp(entry: ActionHelp): void {\n emitHelp(\n entry.command,\n [],\n () => {\n console.log(\"\");\n console.log(`${chalk.bold(`rebase ${entry.command}`)}`);\n console.log(\"\");\n console.log(` ${entry.summary}`);\n console.log(\"\");\n console.log(chalk.green.bold(\"Usage\"));\n console.log(` rebase ${chalk.blue(entry.usage.replace(/^cloud /, \"cloud \"))}`);\n if (entry.flags.length > 0) {\n console.log(\"\");\n console.log(chalk.green.bold(\"Options\"));\n for (const [flag, description] of entry.flags) {\n console.log(` ${chalk.blue(flag.padEnd(30))} ${description}`);\n }\n }\n console.log(\"\");\n console.log(chalk.green.bold(\"Global options\"));\n for (const [flag, description] of GLOBAL_HELP_FLAGS) {\n console.log(` ${chalk.blue(flag.padEnd(30))} ${chalk.gray(description)}`);\n }\n if (entry.notes?.length) {\n console.log(\"\");\n console.log(chalk.green.bold(\"Notes\"));\n for (const note of entry.notes) console.log(` ${chalk.gray(`• ${note}`)}`);\n }\n console.log(\"\");\n console.log(chalk.green.bold(\"Examples\"));\n for (const example of entry.examples) console.log(` ${chalk.gray(example)}`);\n console.log(\"\");\n },\n {\n usage: `rebase ${entry.usage}`,\n summary: entry.summary,\n flags: [...entry.flags, ...GLOBAL_HELP_FLAGS].map(([flag, description]) => ({ flag,\ndescription })),\n notes: entry.notes ?? [],\n examples: entry.examples\n }\n );\n}\n","/**\n * CLI command: `rebase cloud <group> [action] [options]`\n *\n * A single entry point for everything you do against Rebase Cloud — the hosted\n * control plane. Auth, project link, deploys, databases, and the rest are all\n * dispatched from here. Individual groups live in sibling modules; this file\n * only routes and prints help.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { loginCommand, logoutCommand, whoamiCommand } from \"./auth\";\nimport { tokensCommand } from \"./tokens\";\nimport { linkCommand, unlinkCommand, selectOrgCommand, openCommand } from \"./link\";\nimport { listProjects, createProject, projectInfo, deleteProject, resolveProjectArg } from \"./projects\";\nimport { cloudInitCommand } from \"./init\";\nimport { claimCommand } from \"./claim\";\nimport { deployCommand, logsCommand } from \"./deploy\";\nimport { orgsCommand, printOrgsHelp } from \"./orgs\";\nimport { dbCommand, printDbHelp } from \"./databases\";\nimport { envCommand, printEnvHelp } from \"./env\";\nimport { domainsCommand, printDomainsHelp } from \"./domains\";\nimport { extensionsCommand, printExtensionsHelp } from \"./extensions\";\nimport { settingsCommand, printSettingsHelp } from \"./settings\";\nimport { deploymentsListCommand, rollbackCommand, cancelCommand } from \"./deployments\";\nimport { powerCommand } from \"./power\";\nimport { debugCommand, printDebugHelp } from \"./debug\";\nimport { cronCommand } from \"./cron\";\nimport { previewsCommand } from \"./previews\";\nimport { usageCommand } from \"./usage\";\nimport { appKeyCommand } from \"./app-key\";\nimport { serviceKeyCommand } from \"./service-key\";\nimport { activityCommand } from \"./activity\";\nimport { notificationsCommand } from \"./notifications\";\nimport {\n statusCommand,\n metricsCommand,\n webhooksCommand,\n storageCommand,\n computeCommand,\n clustersCommand,\n billingCommand,\n printStorageHelp\n} from \"./resources\";\nimport { declaredResourcesCommand } from \"./declared-resources\";\nimport {\n requireProjectRef,\n initOutputMode,\n printGroupHelp,\n fail,\n GLOBAL_CLOUD_FLAGS,\n type HelpAction\n} from \"./context\";\nimport { ACTION_HELP, printActionHelp } from \"./action-help\";\n\n/**\n * Every flag in the `rebase cloud` family that takes a value, and the short\n * spellings of them — the globals aside, which `GLOBAL_CLOUD_FLAGS` declares.\n *\n * {@link positionals} needs them for one reason: `arg` only consumes a flag's\n * value when the flag is declared, and an undeclared one leaves its value\n * behind as a bare word in the action's position. `rebase cloud deployments\n * --limit 5` dispatched to an action called \"5\", `rebase cloud debug --host\n * staging.example.com` to one called \"staging.example.com\", and `rebase cloud\n * projects --name shop create` to one called \"shop\" — each refused as an unknown\n * command, for a line the command's own help offers.\n *\n * Every value is `String` whatever the command reads it as: only consumption\n * matters here, and the command parses the value itself. One list for the whole\n * family works because no flag takes a value in one command and none in\n * another; `value-flags.test.ts` holds that, and holds this list to the specs\n * the commands declare in both directions, so a new value flag fails a test\n * until it is added here.\n */\nexport const CLOUD_VALUE_FLAGS = {\n \"--access-key-id\": String,\n \"--action\": String,\n \"--actor\": String,\n \"--autoscale-cpu-target\": String,\n \"--autoscale-max\": String,\n \"--backup-access-key-id\": String,\n \"--backup-bucket\": String,\n \"--backup-endpoint\": String,\n \"--backup-secret-access-key\": String,\n \"--base-domain\": String,\n \"--before\": String,\n \"--branch\": String,\n \"--bucket\": String,\n \"--bundle-dir\": String,\n \"--can\": String,\n \"--collection\": String,\n \"--connection-string\": String,\n \"--cpu\": String,\n \"--db\": String,\n \"--db-cpu\": String,\n \"--db-instances\": String,\n \"--db-memory\": String,\n \"--email\": String,\n \"--endpoint\": String,\n \"--events\": String,\n \"--expires-in\": String,\n \"--format\": String,\n \"--function\": String,\n \"--grep\": String,\n \"--host\": String,\n \"--ingress-address\": String,\n \"--kubeconfig\": String,\n \"--level\": String,\n \"--limit\": String,\n \"--live-timeout\": String,\n \"--memory\": String,\n \"--message\": String,\n \"--month\": String,\n \"--name\": String,\n \"--org\": String,\n \"--output\": String,\n \"--password\": String,\n \"--platform-rebuilds\": String,\n \"--port\": String,\n \"--preview-name\": String,\n \"--provider\": String,\n // `clusters registry` (b403f036d5): its three values, so a flag's value is\n // never read as the action.\n \"--pull-key-file\": String,\n \"--push-service-account\": String,\n \"--region\": String,\n \"--replicas\": String,\n \"--repo\": String,\n \"--repository\": String,\n \"--role\": String,\n \"--scale-to-zero\": String,\n \"--secret-access-key\": String,\n \"--since\": String,\n \"--slug\": String,\n \"--source\": String,\n \"--spot\": String,\n \"--storage\": String,\n \"--subdomain\": String,\n \"--tail\": String,\n \"--target\": String,\n \"--timeout\": String,\n \"--type\": String,\n \"--out\": \"--output\",\n \"-e\": \"--email\",\n \"-m\": \"--message\",\n \"-n\": \"--name\"\n} as const;\n\n/**\n * Positional tokens after `rebase cloud` (group, action, …).\n *\n * Two things stop a flag being mistaken for the group or the action.\n * `GLOBAL_CLOUD_FLAGS` and {@link CLOUD_VALUE_FLAGS} are declared so `arg`\n * *consumes* every flag of the family that takes a value — critically together\n * with its value, which is the half that filtering cannot do. The leading-`-`\n * skip then covers a flag nobody declared, so an unrecognised boolean shifts\n * nothing.\n *\n * A flag this family has never heard of, that takes a value, is the one shape\n * still unresolvable here — there is no way to know whether the token after it\n * is its value or the action. The command's own strict parse refuses that flag\n * anyway, so the only cost is which refusal the caller reads.\n *\n * Exported so its tests can drive the real thing. The dispatch test used to\n * re-implement it locally as `slice(3).filter(a => !a.startsWith(\"-\"))` — which\n * filtered flags, while this function did not — so the test asserted the\n * behaviour we wanted against a copy that had it, and stayed green for as long\n * as the real dispatcher was broken.\n */\nexport function positionals(rawArgs: string[]): string[] {\n let rest: string[];\n try {\n rest = arg({ ...CLOUD_VALUE_FLAGS, ...GLOBAL_CLOUD_FLAGS }, { argv: rawArgs.slice(3), permissive: true })._;\n } catch {\n // A value flag at the end of the line with no value. The command's own\n // parse names that problem in the family's refusal envelope; here it is\n // enough to find the words as the globals alone see them.\n rest = arg(GLOBAL_CLOUD_FLAGS, { argv: rawArgs.slice(3), permissive: true })._;\n }\n let i = 0;\n while (i < rest.length && rest[i].startsWith(\"-\")) i++;\n return rest.slice(i);\n}\n\n/**\n * The help page for each group, keyed by every alias the dispatch below accepts.\n *\n * Aliases are listed explicitly rather than normalised first, so a group that\n * gains one and forgets it here degrades to the index page — wrong, but a page.\n * `cloud-help.test.ts` asserts the two stay in step.\n *\n * A group absent from this map has no page of its own; the index lists it.\n */\n/**\n * The second spelling of a group, mapped to the one the pages are keyed on.\n *\n * The dispatch below accepts both (`case \"db\": case \"database\":`), so help has\n * to as well, or half the spellings of a command have no page.\n */\nexport const GROUP_ALIASES: Record<string, string> = {\n database: \"db\",\n domain: \"domains\",\n extension: \"extensions\",\n org: \"orgs\",\n preview: \"previews\",\n project: \"projects\"\n};\n\nexport const GROUP_HELP: Record<string, () => void> = {\n env: printEnvHelp,\n domains: printDomainsHelp,\n domain: printDomainsHelp,\n extensions: printExtensionsHelp,\n extension: printExtensionsHelp,\n settings: printSettingsHelp,\n orgs: printOrgsHelp,\n org: printOrgsHelp,\n db: printDbHelp,\n database: printDbHelp,\n debug: printDebugHelp,\n storage: printStorageHelp\n};\n\nexport async function cloudCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // Latch the output mode FIRST — before anything can print or `fail` — so the\n // whole command family agrees on human vs. machine-readable output.\n initOutputMode(rawArgs);\n\n const pos = positionals(rawArgs);\n // The positionals win over the `subcommand` the top-level parser handed us.\n // Both describe the same token, but only this one is resolved against a\n // flag spec: `cli.ts` is generic across every command and cannot know which\n // flags `cloud` takes, so with `cloud --json storage create` it reported the\n // subcommand as `\"--json\"`. Falling back to it keeps the parameter useful\n // when a caller passes a group that is not in `rawArgs` at all.\n const group = pos[0] ?? (subcommand !== \"--help\" ? subcommand : undefined);\n // A piped `cloud deploy` prints its summary, not JSON — see `initOutputMode`.\n // Re-latched here rather than decided above because the group is only known\n // now; nothing between the two calls prints.\n if (group === \"deploy\") initOutputMode(rawArgs, { whenPiped: \"human\" });\n\n // `--help` has to be recovered from `rawArgs` rather than read off `pos`.\n // `positionals()` resolves against `GLOBAL_CLOUD_FLAGS`, which declares\n // `--help`, so `arg` *consumes* it — correct for `--project` and `--json`,\n // which modify a command, but wrong for `--help`, which replaces it.\n const wantsHelp = rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\");\n // A flag is never an action. `rebase cloud env --frobnicate` used to read\n // the flag as the action and refuse it as an unknown *command* — a refusal,\n // but about the wrong half of the line; the group's own parser is what\n // knows the flag is undeclared, and it never got the chance to say so.\n // Skipped here rather than in `positionals()`, whose contract past the\n // action is deliberately \"these are somebody else's positionals\".\n const action = pos.slice(1).find(token => !token.startsWith(\"-\"));\n\n // The index help is for `rebase cloud` and `rebase cloud --help` — that is,\n // when no group was named. It used to also fire whenever `subcommand` was\n // the literal `\"--help\"`, which `cli.ts` set for *any* `--help` anywhere in\n // the line, so `rebase cloud env --help` printed this page instead of env's\n // and the per-group help in seven modules was unreachable. Keyed on the\n // group now, which is the thing that actually decides whose help this is.\n if (!group) {\n printCloudHelp();\n return;\n }\n\n // `--help` is answered here, before dispatch, and never by the command.\n //\n // Routing it as an action instead only worked for the groups that happened\n // to have a `case \"--help\"`. The others took `rawArgs` and ignored the\n // action entirely, so the flag did nothing and the command ran: `rebase\n // cloud env --help` tried to list variables and failed on \"No project\n // specified\", `rebase cloud deploy --help` started resolving a project, and\n // `rebase cloud link --help` opened an *interactive project picker* — a\n // prompt, from a flag whose entire job is to print text and exit.\n //\n // Answering centrally makes that structurally impossible: `--help` cannot\n // reach a handler, so it cannot prompt, call the API, or need a linked\n // project. A group without its own page falls back to the index rather than\n // to running something.\n //\n // Resolved most-specific-first. Group-level was all there was, so `rebase\n // cloud projects create --help` and `rebase cloud deploy --help` printed the\n // index — a list of groups, no flags — and `--name`, `--subdomain` and\n // `--type` had no discoverable spelling anywhere in the CLI. They were found\n // on a real first deploy by reading `dist/index.es.js.map`.\n if (wantsHelp) {\n // Through the alias, because the dispatch accepts both spellings and a\n // page keyed on one of them is not a page for the other: `rebase cloud\n // database create --help` reached the group index while\n // `rebase cloud db create --help` printed the flags.\n const canonical = GROUP_ALIASES[group] ?? group;\n const forAction = action ? ACTION_HELP[`${canonical} ${action}`] : undefined;\n const page = forAction ?? ACTION_HELP[canonical];\n if (page) {\n printActionHelp(page);\n return;\n }\n (GROUP_HELP[group] ?? printCloudHelp)();\n return;\n }\n\n switch (group) {\n /* auth */\n case \"login\":\n await loginCommand(rawArgs);\n break;\n case \"logout\":\n await logoutCommand(rawArgs);\n break;\n case \"whoami\":\n await whoamiCommand(rawArgs);\n break;\n case \"tokens\":\n await tokensCommand(action, rawArgs);\n break;\n\n /* context / link */\n case \"link\":\n await linkCommand(rawArgs);\n break;\n case \"unlink\":\n unlinkCommand(rawArgs);\n break;\n case \"use\":\n await selectOrgCommand(rawArgs);\n break;\n case \"open\":\n openCommand(rawArgs);\n break;\n\n /* projects */\n case \"init\":\n await cloudInitCommand(rawArgs);\n break;\n case \"claim\":\n await claimCommand(rawArgs);\n break;\n case \"projects\":\n case \"project\":\n await projectsGroup(action, rawArgs);\n break;\n\n /* deploy + logs (operate on linked/--project) */\n case \"deploy\":\n await deployCommand(rawArgs, requireProjectRef(rawArgs));\n break;\n case \"logs\":\n await logsCommand(rawArgs, requireProjectRef(rawArgs));\n break;\n case \"previews\":\n case \"preview\":\n await previewsCommand(action, rawArgs);\n break;\n case \"deployments\":\n case \"releases\":\n await deploymentsGroup(action, rawArgs);\n break;\n case \"rollback\":\n await rollbackCommand(rawArgs);\n break;\n case \"cancel\":\n await cancelCommand(rawArgs);\n break;\n case \"start\":\n case \"stop\":\n case \"restart\":\n await powerCommand(group, rawArgs);\n break;\n case \"status\":\n await statusCommand(rawArgs);\n break;\n case \"metrics\":\n await metricsCommand(rawArgs);\n break;\n case \"debug\":\n await debugCommand(action, rawArgs);\n break;\n case \"cron\":\n await cronCommand(action, rawArgs);\n break;\n\n /* env / domains / extensions / settings */\n case \"env\":\n await envCommand(action, rawArgs);\n break;\n case \"domains\":\n case \"domain\":\n await domainsCommand(action, rawArgs);\n break;\n case \"extensions\":\n case \"extension\":\n await extensionsCommand(action, rawArgs);\n break;\n case \"settings\":\n await settingsCommand(action, rawArgs);\n break;\n\n /* orgs */\n case \"orgs\":\n case \"org\":\n await orgsCommand(action, rawArgs);\n break;\n\n /* databases */\n case \"db\":\n case \"database\":\n await dbCommand(action, rawArgs);\n break;\n\n /* other resources */\n case \"webhooks\":\n await webhooksCommand(action, rawArgs);\n break;\n case \"notifications\":\n await notificationsCommand(action, rawArgs);\n break;\n case \"storage\":\n await storageCommand(action, rawArgs);\n break;\n case \"compute\":\n await computeCommand(action, rawArgs);\n break;\n case \"resources\":\n // The word means the graph now, on both sides of the wire: what the\n // code declares against what the platform holds. What it used to\n // show — CPU, memory, cost — is `compute`, and a dial flag arriving\n // here is the one thing worth a pointed refusal.\n if (action === \"set\") {\n fail(\n \"`rebase cloud resources set` is now `rebase cloud compute set` — CPU, memory, replicas and cost.\",\n \"`rebase cloud resources` lists what this project declares against what the platform provisioned.\",\n \"renamed\"\n );\n }\n await declaredResourcesCommand(action, rawArgs);\n break;\n case \"clusters\":\n await clustersCommand(action, rawArgs);\n break;\n case \"usage\":\n await usageCommand(rawArgs);\n break;\n case \"app-key\":\n await appKeyCommand(rawArgs);\n break;\n case \"service-key\":\n await serviceKeyCommand(rawArgs);\n break;\n case \"activity\":\n await activityCommand(rawArgs);\n break;\n case \"billing\":\n await billingCommand(rawArgs);\n break;\n\n default:\n // Through `fail`, like every other refusal in the family — and like\n // the two group dispatchers below, which now match.\n //\n // It used to print a red line to stderr and then the ENTIRE help\n // page to stdout before exiting 1. Two things wrong with that: a\n // piped `rebase cloud typo` handed its caller ~60 lines of\n // ANSI-coloured help where the contract promises one JSON value,\n // and even on a terminal it put the remedy on the RESULTS stream of\n // a command that produced no result. The hint names `--help`, which\n // is the one command whose result the page actually is.\n fail(`Unknown cloud command: ${group}`, \"Run `rebase cloud --help`.\", \"unknown_command\");\n }\n}\n\nasync function projectsGroup(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listProjects(rawArgs);\n break;\n case \"create\":\n await createProject(rawArgs);\n break;\n // The id is resolved by the handlers' own module, against their own flag\n // spec. `positionals()` cannot do it: it declares only the global cloud\n // flags and skips only LEADING `-` tokens, so any other flag written\n // after the action became the id — `projects delete --force` looked up\n // a project named \"--force\".\n case \"info\":\n await projectInfo(rawArgs, resolveProjectArg(rawArgs, \"info\"));\n break;\n case \"delete\":\n await deleteProject(rawArgs, resolveProjectArg(rawArgs, \"delete\"));\n break;\n case \"--help\":\n printCloudHelp();\n break;\n default:\n fail(`Unknown projects command: ${action}`, \"Run `rebase cloud --help`.\", \"unknown_command\");\n }\n}\n\nasync function deploymentsGroup(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await deploymentsListCommand(rawArgs);\n break;\n case \"--help\":\n printCloudHelp();\n break;\n default:\n fail(`Unknown deployments command: ${action}`, \"Run `rebase cloud --help`.\", \"unknown_command\");\n }\n}\n\n/**\n * Every group `cloudCommand` dispatches, canonical name first, with the line the\n * index page prints for it.\n *\n * One list, rendered twice. It used to be two: a bare array of words for the\n * JSON form and a hand-formatted template literal for the terminal — which is\n * how `clusters` came to be listed on the page twice, under two different\n * descriptions, in the same section. The page is generated from this now, so a\n * group appears exactly as often as it appears here, and `cloud-help.test.ts`\n * holds the list to the dispatch switch and to the pages.\n *\n * Sub-actions are deliberately not here. Every group answers `--help` with its\n * own page now, listing its actions, their arguments and their flags; repeating\n * a subset of that on the index is the duplication this replaced.\n */\nexport const CLOUD_GROUPS: HelpAction[] = [\n { action: \"login\", section: \"Auth\", description: \"Sign in to the control plane\" },\n { action: \"logout\", section: \"Auth\", description: \"Sign out\" },\n { action: \"whoami\", section: \"Auth\", description: \"Show the current session, or what REBASE_TOKEN may do\" },\n { action: \"tokens\", section: \"Auth\", description: \"Tokens for CI and agents, each narrowed to one project\" },\n\n { action: \"link\", section: \"Project link\", args: \"[url]\", description: \"Bind this directory to a cloud project, or straight to a backend URL\" },\n { action: \"unlink\", section: \"Project link\", description: \"Remove the link\" },\n { action: \"use\", section: \"Project link\", args: \"[org]\", description: \"Select the active organization\" },\n { action: \"open\", section: \"Project link\", description: \"Open the console in a browser\" },\n\n { action: \"init\", section: \"Projects\", description: \"With --claim: a live backend with no account, and a link to claim it within 72 hours\" },\n { action: \"claim\", section: \"Projects\", description: \"The claim link of the project `init --claim` made here, and the time left; --open opens it\" },\n { action: \"projects\", section: \"Projects\", description: \"Create, list, inspect and delete projects\" },\n\n { action: \"deploy\", section: \"Deploy & observe\", args: \"[app]\", description: \"Build, upload and ship an app, following it to a terminal state\" },\n { action: \"logs\", section: \"Deploy & observe\", description: \"Build logs, or the runtime's with --runtime\" },\n { action: \"deployments\", section: \"Deploy & observe\", description: \"Deployment history: status, duration, trigger\" },\n { action: \"previews\", section: \"Deploy & observe\", description: \"Builds served on their own address by `deploy --preview`\" },\n { action: \"rollback\", section: \"Deploy & observe\", args: \"[id]\", description: \"Put a previous successful deployment back into service\" },\n { action: \"cancel\", section: \"Deploy & observe\", description: \"Stop the build in flight\" },\n { action: \"start\", section: \"Deploy & observe\", description: \"Bring a stopped project back\" },\n { action: \"stop\", section: \"Deploy & observe\", description: \"Stop the project. Downtime, so it confirms\" },\n { action: \"restart\", section: \"Deploy & observe\", description: \"Stop and start it again\" },\n { action: \"status\", section: \"Deploy & observe\", description: \"One glance: URL, last deploy, and what it is waiting on\" },\n { action: \"metrics\", section: \"Deploy & observe\", description: \"Live CPU, memory and disk\" },\n { action: \"debug\", section: \"Deploy & observe\", description: \"Diagnose a misbehaving deployment. Read-only\" },\n { action: \"cron\", section: \"Deploy & observe\", description: \"The app's cron jobs and their run history. Read-only\" },\n\n { action: \"env\", section: \"Config\", description: \"Environment variables\" },\n { action: \"domains\", section: \"Config\", description: \"Custom domains, their DNS records, and verification\" },\n { action: \"extensions\", section: \"Config\", description: \"The Postgres extension allowlist\" },\n { action: \"settings\", section: \"Config\", description: \"Name, subdomain, repository, branch\" },\n { action: \"app-key\", section: \"Config\", args: \"[rotate]\", description: \"The app key `init --claim` wrote into .env, and replacing it. Owners and admins\" },\n { action: \"service-key\", section: \"Config\", args: \"[rotate]\", description: \"REBASE_SERVICE_KEY, admin on the app's API: its state, and replacing it. Owners and admins\" },\n\n { action: \"orgs\", section: \"Organizations\", description: \"Organizations you belong to, and their members\" },\n { action: \"activity\", section: \"Organizations\", description: \"Who did what in the organization: deploys, env vars, domains, backups, members. Owners and admins\" },\n\n { action: \"db\", section: \"Data\", description: \"Attach a database, back it up, restore, point-in-time recovery\" },\n { action: \"storage\", section: \"Data\", description: \"The project's object storage\" },\n\n { action: \"notifications\", section: \"Deploy & observe\", description: \"Send deploy, backup, billing and usage events to Slack, Discord or any URL\" },\n { action: \"webhooks\", section: \"Other resources\", description: \"Retired: use `notifications`, or a WebhookDispatcher in your app's code\" },\n // Both of these dispatch and have a page, and both were absent from this\n // list — so the command that names what a project costs, and the one that\n // names what it declares, were undiscoverable from `rebase cloud --help`,\n // which is where an agent finds the family.\n { action: \"resources\", section: \"Other resources\", description: \"What the code declares against what the platform provisioned\" },\n { action: \"compute\", section: \"Other resources\", description: \"What this project reserves, what it costs, and how to change it\" },\n { action: \"clusters\", section: \"Other resources\", description: \"The clusters tenants run on. Platform-admin only\" },\n { action: \"billing\", section: \"Other resources\", description: \"The organization's billing account and card on file\" },\n { action: \"usage\", section: \"Other resources\", args: \"[org]\", description: \"Requests used this month against the allowance, and the overage so far\" }\n];\n\n/** The dispatch words alone — what `--help` routing and the tests iterate. */\nexport const CLOUD_GROUP_NAMES = CLOUD_GROUPS.map(g => g.action);\n\nfunction printCloudHelp(): void {\n printGroupHelp({\n command: \"cloud\",\n title: \"Manage your apps on Rebase Cloud\",\n actions: CLOUD_GROUPS,\n notes: [\n \"Most commands act on the linked project (.rebase/cloud.json) unless --project is given.\",\n \"With REBASE_TOKEN set (a token from `rebase cloud tokens create`), commands use it instead of your login.\",\n \"Every group answers `--help` with its own page: actions, arguments and flags.\",\n \"Docs: https://rebase.pro/docs\"\n ]\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAa,eACT,4EAA4E,UAAU;;AAG1F,IAAa,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