@rebasepro/cli 0.23.0 → 0.24.1-canary.g56af4a4

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 (158) hide show
  1. package/README.md +19 -3
  2. package/bin/rebase.js +4 -1
  3. package/dist/agent-setup-B31F00DC.js +324 -0
  4. package/dist/agent-setup-B31F00DC.js.map +1 -0
  5. package/dist/api-keys-BPBi5nOF.js +524 -0
  6. package/dist/api-keys-BPBi5nOF.js.map +1 -0
  7. package/dist/apps-CPXNElX4.js +256 -0
  8. package/dist/apps-CPXNElX4.js.map +1 -0
  9. package/dist/args-BnmsEXvu.js +109 -0
  10. package/dist/args-BnmsEXvu.js.map +1 -0
  11. package/dist/atlas-dev-database-DTMuEScS.js +62 -0
  12. package/dist/atlas-dev-database-DTMuEScS.js.map +1 -0
  13. package/dist/auth-DvY94ZuL.js +395 -0
  14. package/dist/auth-DvY94ZuL.js.map +1 -0
  15. package/dist/branch-pointer-DIhKbQLp.js +2 -0
  16. package/dist/build-CFwUx-Ff.js +336 -0
  17. package/dist/build-CFwUx-Ff.js.map +1 -0
  18. package/dist/bundle-BQhP_xiA.js +1617 -0
  19. package/dist/bundle-BQhP_xiA.js.map +1 -0
  20. package/dist/bundle.d.ts +6 -2
  21. package/dist/cli.d.ts +23 -2
  22. package/dist/cloud-CkTr-yt0.js +9640 -0
  23. package/dist/cloud-CkTr-yt0.js.map +1 -0
  24. package/dist/collection-drift-BKj_BoMq.js +106 -0
  25. package/dist/collection-drift-BKj_BoMq.js.map +1 -0
  26. package/dist/commands/__test_support__/parser-specs.d.ts +13 -0
  27. package/dist/commands/agent-setup.d.ts +116 -0
  28. package/dist/commands/api-keys.d.ts +86 -23
  29. package/dist/commands/apps.d.ts +17 -0
  30. package/dist/commands/auth.d.ts +7 -0
  31. package/dist/commands/build.d.ts +5 -1
  32. package/dist/commands/cloud/auth.d.ts +4 -3
  33. package/dist/commands/cloud/bundle-deploy.d.ts +45 -0
  34. package/dist/commands/cloud/context.d.ts +44 -5
  35. package/dist/commands/cloud/cron.d.ts +53 -0
  36. package/dist/commands/cloud/debug.d.ts +134 -0
  37. package/dist/commands/cloud/index.d.ts +89 -12
  38. package/dist/commands/cloud/token-capabilities.d.ts +76 -0
  39. package/dist/commands/cloud/tokens.d.ts +23 -0
  40. package/dist/commands/db.d.ts +52 -25
  41. package/dist/commands/dev.d.ts +181 -7
  42. package/dist/commands/doctor.d.ts +5 -0
  43. package/dist/commands/generate_sdk.d.ts +29 -2
  44. package/dist/commands/init.d.ts +57 -14
  45. package/dist/commands/schema.d.ts +6 -0
  46. package/dist/commands/skills.d.ts +126 -7
  47. package/dist/commands/start.d.ts +29 -0
  48. package/dist/commands/storage.d.ts +46 -0
  49. package/dist/consent-BWHaYx5p.js +76 -0
  50. package/dist/consent-BWHaYx5p.js.map +1 -0
  51. package/dist/context-BqhRydBg.js +1234 -0
  52. package/dist/context-BqhRydBg.js.map +1 -0
  53. package/dist/daemon-DBn-shxX.js +2 -0
  54. package/dist/{daemon-entry-LTFKtpHy.js → daemon-entry-Da-D3rmH.js} +3 -4
  55. package/dist/daemon-entry-Da-D3rmH.js.map +1 -0
  56. package/dist/db-CMpBK3sv.js +1252 -0
  57. package/dist/db-CMpBK3sv.js.map +1 -0
  58. package/dist/derive-RPIsAVO4.js +474 -0
  59. package/dist/derive-RPIsAVO4.js.map +1 -0
  60. package/dist/dev-C9P5Yp9k.js +1593 -0
  61. package/dist/dev-C9P5Yp9k.js.map +1 -0
  62. package/dist/dev-db/atlas-dev-database.d.ts +32 -0
  63. package/dist/dev-db/daemon-entry.d.ts +13 -0
  64. package/dist/dev-db/daemon.d.ts +10 -0
  65. package/dist/dev-db/prepare.d.ts +10 -0
  66. package/dist/dev-preflight-N1evJL3S.js +2 -0
  67. package/dist/doctor-DYs-NqFI.js +771 -0
  68. package/dist/doctor-DYs-NqFI.js.map +1 -0
  69. package/dist/eject-BT6t37D0.js +335 -0
  70. package/dist/eject-BT6t37D0.js.map +1 -0
  71. package/dist/fold-static-C1EtHlfV.js +201 -0
  72. package/dist/fold-static-C1EtHlfV.js.map +1 -0
  73. package/dist/fold-static.d.ts +26 -3
  74. package/dist/function-portability-BIvlvR9q.js +265 -0
  75. package/dist/function-portability-BIvlvR9q.js.map +1 -0
  76. package/dist/generate_sdk-UV635zSe.js +477 -0
  77. package/dist/generate_sdk-UV635zSe.js.map +1 -0
  78. package/dist/index.es.js +189 -22095
  79. package/dist/index.es.js.map +1 -1
  80. package/dist/init-fXeBcxuN.js +1042 -0
  81. package/dist/init-fXeBcxuN.js.map +1 -0
  82. package/dist/manifest-DzlC60WX.js +871 -0
  83. package/dist/manifest-DzlC60WX.js.map +1 -0
  84. package/dist/manifest.d.ts +41 -1
  85. package/dist/normalize-imports-CmVdE9iZ.js +100 -0
  86. package/dist/normalize-imports-CmVdE9iZ.js.map +1 -0
  87. package/dist/package-manager-DSEOwTqM.js +193 -0
  88. package/dist/package-manager-DSEOwTqM.js.map +1 -0
  89. package/dist/path-flags-DUBuI2i1.js +77 -0
  90. package/dist/path-flags-DUBuI2i1.js.map +1 -0
  91. package/dist/precompress.d.ts +17 -0
  92. package/dist/prepare-Btn9Ewbn.js +1052 -0
  93. package/dist/prepare-Btn9Ewbn.js.map +1 -0
  94. package/dist/{project-3WCbrrfW.js → project-Wp2zoyeN.js} +34 -184
  95. package/dist/project-Wp2zoyeN.js.map +1 -0
  96. package/dist/resolve-CJLkfFV0.js +2 -0
  97. package/dist/resources-DT1COn_6.js +161 -0
  98. package/dist/resources-DT1COn_6.js.map +1 -0
  99. package/dist/schema-BDBWvCHu.js +125 -0
  100. package/dist/schema-BDBWvCHu.js.map +1 -0
  101. package/dist/skills-DTFibT1m.js +642 -0
  102. package/dist/skills-DTFibT1m.js.map +1 -0
  103. package/dist/start-rU2e3Kp5.js +228 -0
  104. package/dist/start-rU2e3Kp5.js.map +1 -0
  105. package/dist/{state-C59Elrnt.js → state-Do7ZJYkF.js} +49 -4
  106. package/dist/state-Do7ZJYkF.js.map +1 -0
  107. package/dist/status-BR9oyi-y.js +351 -0
  108. package/dist/status-BR9oyi-y.js.map +1 -0
  109. package/dist/storage-DyvrSTH3.js +303 -0
  110. package/dist/storage-DyvrSTH3.js.map +1 -0
  111. package/dist/telemetry-CAWNCugs.js +338 -0
  112. package/dist/telemetry-CAWNCugs.js.map +1 -0
  113. package/dist/telemetry-DbLqGIBW.js +129 -0
  114. package/dist/telemetry-DbLqGIBW.js.map +1 -0
  115. package/dist/unknown-command-DNwDcX3w.js +98 -0
  116. package/dist/unknown-command-DNwDcX3w.js.map +1 -0
  117. package/dist/upgrade-D-5-Od96.js +1265 -0
  118. package/dist/upgrade-D-5-Od96.js.map +1 -0
  119. package/dist/upgrade.d.ts +14 -2
  120. package/dist/utils/path-flags.d.ts +18 -0
  121. package/dist/utils/project.d.ts +16 -0
  122. package/dist/version-Buyyo1ut.js +58 -0
  123. package/dist/version-Buyyo1ut.js.map +1 -0
  124. package/package.json +7 -7
  125. package/templates/eject/backend/src/env.ts +1 -1
  126. package/templates/eject/backend/src/index.ts +23 -2
  127. package/templates/overlays/baas/ai-instructions.md +1 -1
  128. package/templates/overlays/baas/config/storage.ts +5 -3
  129. package/templates/template/.cursorrules +1 -1
  130. package/templates/template/.env.example +10 -6
  131. package/templates/template/.github/copilot-instructions.md +1 -1
  132. package/templates/template/.mcp.json +2 -2
  133. package/templates/template/.windsurfrules +1 -1
  134. package/templates/template/AGENTS.md +1 -1
  135. package/templates/template/CLAUDE.md +1 -1
  136. package/templates/template/README.md +11 -12
  137. package/templates/template/ai-instructions.md +5 -4
  138. package/templates/template/backend/functions/hello.ts +8 -0
  139. package/templates/template/backend/package.json +1 -1
  140. package/templates/template/config/storage.ts +5 -3
  141. package/templates/template/docker-compose.yml +6 -6
  142. package/templates/template/frontend/vite.config.ts +11 -3
  143. package/templates/template/gitignore +6 -1
  144. package/templates/template/package.json +4 -3
  145. package/templates/template/scripts/example.ts +6 -4
  146. package/dist/branch-pointer-dBiClJ0p.js +0 -111
  147. package/dist/branch-pointer-dBiClJ0p.js.map +0 -1
  148. package/dist/constraints-DKGbNfUW.js +0 -48
  149. package/dist/constraints-DKGbNfUW.js.map +0 -1
  150. package/dist/daemon-DR9Tk0La.js +0 -355
  151. package/dist/daemon-DR9Tk0La.js.map +0 -1
  152. package/dist/daemon-entry-LTFKtpHy.js.map +0 -1
  153. package/dist/dev-preflight-CNLl4rdo.js +0 -367
  154. package/dist/dev-preflight-CNLl4rdo.js.map +0 -1
  155. package/dist/project-3WCbrrfW.js.map +0 -1
  156. package/dist/resolve-BAeRUBhg.js +0 -74
  157. package/dist/resolve-BAeRUBhg.js.map +0 -1
  158. package/dist/state-C59Elrnt.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-CkTr-yt0.js","names":[],"sources":["../src/commands/cloud/token-capabilities.ts","../src/commands/cloud/auth.ts","../src/commands/cloud/tokens.ts","../src/commands/cloud/link.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/bundle-deploy.ts","../src/commands/cloud/rebuild-source.ts","../src/commands/cloud/deploy.ts","../src/commands/cloud/orgs.ts","../src/commands/cloud/env.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/debug.ts","../src/commands/cloud/cron.ts","../src/commands/cloud/declared-resources.ts","../src/commands/cloud/action-help.ts","../src/commands/cloud/index.ts"],"sourcesContent":["/**\n * What a Rebase Cloud token may do, named the way a person asks for it.\n *\n * A token is a personal API key on the control plane: it acts as the account\n * that created it, and holds only the scopes it was given. Nobody should have\n * to know that `rebase cloud deploy` reads the `deployments` collection, uploads\n * through the `deploy` function and needs `project:deploy` on one project — so\n * `rebase cloud tokens create --can deploy` and the console's token screen both\n * ask for a capability, and this module turns capabilities into scopes.\n *\n * One map, read by the CLI and by the console. Each capability covers exactly\n * the control-plane calls its commands make, traced from the commands\n * themselves and held there by `token-capabilities.test.ts`, which runs them\n * against a stand-in control plane that refuses everything a token does not\n * hold:\n *\n * - `deploy` — `rebase cloud deploy` (bundle and source paths, uploads, the\n * build follow) and `rebase cloud deployments`.\n * - `logs` — `rebase cloud logs` (build, `--follow`, `--runtime`),\n * `rebase cloud metrics` and `rebase cloud cron` — whose\n * `runtime-token` call is how a token reads the app's own\n * cron history.\n * - `env` — `rebase cloud env list|set|unset|reveal|pull`.\n * - `database` — `rebase cloud db list|info|connect`.\n * - `backups` — `rebase cloud db backup list|create|status|download` and\n * `db pitr status`. Restoring takes `project:restore`, which no\n * capability grants: putting old data over a live database is\n * for a signed-in person.\n *\n * Every project-level scope is narrowed to the one project the token is for\n * (`project:deploy:<projectId>`). The data and function scopes cannot be: they\n * name a collection or a function, not a row, and the control plane's\n * row-level security keeps the token to what its owner can see.\n *\n * Deliberately free of imports, so the control plane's console can read the\n * same file.\n *\n * @module\n */\n\n/** A capability a token can be given. */\nexport type TokenCapability = \"deploy\" | \"logs\" | \"env\" | \"database\" | \"backups\";\n\n/** Every capability, in the order they are offered. */\nexport const TOKEN_CAPABILITY_NAMES: readonly TokenCapability[] = [\"deploy\", \"logs\", \"env\", \"database\", \"backups\"];\n\n/**\n * Scopes every token holds, whatever it was created for: resolving a project\n * by its slug, reading the deployment a command follows, the organization a\n * project belongs to, and the control plane's public description of itself.\n */\nexport const ALWAYS_SCOPES: string[] = [\n \"data:read:projects\",\n \"data:read:deployments\",\n \"data:read:organizations\",\n \"functions:invoke:platform-config\"\n];\n\n/** Each capability: what it lets a token do, and the scopes that does on one project. */\nexport const TOKEN_CAPABILITIES: Record<TokenCapability, { label: string; scopes: (projectId: string) => string[] }> = {\n deploy: {\n label: \"Deploy the project and follow its builds\",\n scopes: (projectId) => [\n `project:read:${projectId}`,\n `project:deploy:${projectId}`,\n \"functions:invoke:deploy\"\n ]\n },\n logs: {\n label: \"Read build and runtime logs, cron history, and live metrics\",\n scopes: (projectId) => [\n `project:read:${projectId}`,\n `project:logs:${projectId}`,\n \"functions:invoke:runtime-logs\",\n \"functions:invoke:metrics\",\n \"functions:invoke:runtime-token\"\n ]\n },\n env: {\n label: \"Read and change environment variables, secrets included\",\n scopes: (projectId) => [\n `project:env:${projectId}`,\n \"functions:invoke:env-vars\"\n ]\n },\n database: {\n label: \"Connect to the database and read its password\",\n scopes: (projectId) => [\n `project:read:${projectId}`,\n `project:database:${projectId}`,\n \"functions:invoke:db-info\",\n \"data:read:databases\"\n ]\n },\n backups: {\n label: \"List, create and download backups (restoring needs a signed-in person)\",\n scopes: (projectId) => [\n `project:read:${projectId}`,\n `project:backups:${projectId}`,\n \"functions:invoke:backup\"\n ]\n }\n};\n\n/** Whether a word names a capability. */\nexport function isTokenCapability(value: string): value is TokenCapability {\n return (TOKEN_CAPABILITY_NAMES as readonly string[]).includes(value);\n}\n\n/**\n * The scopes a token for `capabilities` on one project holds: {@link ALWAYS_SCOPES}\n * first, then each capability's, each scope once.\n *\n * Throws on a project id a scope cannot carry — empty, or with whitespace — and\n * on an unknown capability, both of which are a caller's mistake rather than\n * something to mint a token from.\n */\nexport function scopesForCapabilities(projectId: string, capabilities: readonly TokenCapability[]): string[] {\n if (projectId.length === 0 || /\\s/.test(projectId)) {\n throw new Error(`\"${projectId}\" is not a project id a scope can be narrowed to.`);\n }\n const scopes = new Set<string>(ALWAYS_SCOPES);\n for (const capability of capabilities) {\n if (!isTokenCapability(capability)) {\n throw new Error(`\"${String(capability)}\" is not a token capability. Capabilities: ${TOKEN_CAPABILITY_NAMES.join(\", \")}.`);\n }\n for (const scope of TOKEN_CAPABILITIES[capability].scopes(projectId)) scopes.add(scope);\n }\n return [...scopes];\n}\n\n/**\n * Read a token's scopes back as capabilities: the projects its project scopes\n * name, and, for each, the capabilities it holds every scope of.\n *\n * For showing a token — `rebase cloud tokens list`, `rebase cloud whoami` — so\n * a list of fifteen scope strings reads as \"deploy, logs on <project>\".\n */\nexport function capabilitiesInScopes(scopes: readonly string[]): Array<{ projectId: string; capabilities: TokenCapability[] }> {\n const held = new Set(scopes);\n const projectIds: string[] = [];\n for (const scope of scopes) {\n const match = /^project:[a-z][a-z0-9-]*:(.+)$/.exec(scope);\n if (match && !projectIds.includes(match[1])) projectIds.push(match[1]);\n }\n return projectIds.map(projectId => ({\n projectId,\n capabilities: TOKEN_CAPABILITY_NAMES.filter(capability =>\n TOKEN_CAPABILITIES[capability].scopes(projectId).every(scope => held.has(scope)))\n }));\n}\n","/**\n * `rebase cloud` auth subcommands: login, logout, whoami.\n */\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\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 TOKEN_ENV,\n type CloudClient\n} from \"./context\";\nimport { capabilitiesInScopes } from \"./token-capabilities\";\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 \"-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 // 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 // Collect any missing credentials interactively — but only where a terminal\n // can supply them. Piped, this used to hang on a password prompt.\n const needsEmail = !args[\"--email\"] && !envEmail;\n const needsPassword = !args[\"--password\"] && !envPassword;\n if (needsEmail || needsPassword) {\n requireInteractive(\"credentials\", `--email and --password, or ${EMAIL_ENV} and ${PASSWORD_ENV}`);\n }\n\n // The questions' real type, not `Record<string, unknown>`. Inquirer infers\n // the answer shape from the array it is given, so an array of open records\n // matches no overload — which is what the\n // `as unknown as Parameters<typeof inquirer.prompt>[0]` here was answering.\n // Naming the two question kinds this command asks makes the call check.\n const prompts: Array<\n | { type: \"input\"; name: string; message: string }\n | { type: \"password\"; name: string; message: string; mask: string }\n > = [];\n if (needsEmail) {\n prompts.push({ type: \"input\",\nname: \"email\",\nmessage: \"Email:\" });\n }\n if (needsPassword) {\n prompts.push({ type: \"password\",\nname: \"password\",\nmessage: \"Password:\",\nmask: \"•\" });\n }\n const answers = prompts.length\n ? await inquirer.prompt(prompts)\n : {};\n\n const email = (args[\"--email\"] || envEmail || (answers as { email?: string }).email || \"\").trim();\n const password = args[\"--password\"] || envPassword || (answers as { password?: string }).password || \"\";\n\n if (!email || !password) {\n fail(\"Email and password are required.\");\n }\n\n const client = createCloudClient(url);\n try {\n const { user } = await 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) {\n fail(\"Invalid email or password.\", undefined, \"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 if (envToken()) {\n await whoamiToken(client, url);\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/** `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 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\", grants.length ? grants.map(g => `${g.capabilities.join(\", \")} on ${g.projectId}`).join(\"; \") : undefined],\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 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 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.\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 capabilitiesInScopes,\n isTokenCapability,\n scopesForCapabilities,\n TOKEN_CAPABILITY_NAMES,\n type TokenCapability\n} from \"./token-capabilities\";\nimport {\n confirmDestructive,\n displayProjectRef,\n emit,\n fail,\n keyValues,\n parseCloudArgs,\n reportError,\n requireKnownAction,\n requireProject,\n requireSessionClient,\n success,\n TOKEN_ENV\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} 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/**\n * The capabilities `--can` names, comma-separated or repeated, each once.\n *\n * Exported so its tests can drive it without a session.\n */\nexport function parseCapabilities(values: readonly string[] | undefined): TokenCapability[] {\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: ${TOKEN_CAPABILITY_NAMES.join(\", \")}.`,\n \"usage\"\n );\n }\n const unknown = words.filter(word => !isTokenCapability(word));\n if (unknown.length > 0) {\n fail(\n `--can takes capabilities, and ${unknown.map(word => `\"${word}\"`).join(\", \")} is not one.`,\n `Capabilities: ${TOKEN_CAPABILITY_NAMES.join(\", \")}.`,\n \"usage\"\n );\n }\n return words.filter(isTokenCapability);\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 capabilities = parseCapabilities(flags[\"--can\"]);\n const expiresAt = resolveTokenExpiry(flags[\"--expires-in\"]);\n\n const { client } = await requireSessionClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs) || projectId;\n const name = flags[\"--name\"]?.trim() || `${projectRef} ${capabilities.join(\"+\")}`;\n const scopes = scopesForCapabilities(projectId, capabilities);\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\", projectRef === projectId ? projectId : `${projectRef} (${projectId})`],\n [\"Can\", capabilities.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,\n capabilities,\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/** What a token was created for, read back from its scopes: `deploy, logs on proj_1`. */\nfunction describeGrant(scopes: readonly string[]): string {\n const grants = capabilitiesInScopes(scopes).filter(grant => grant.capabilities.length > 0);\n if (grants.length === 0) return `${scopes.length} scope${scopes.length === 1 ? \"\" : \"s\"}`;\n return grants.map(grant => `${grant.capabilities.join(\", \")} on ${grant.projectId}`).join(\"; \");\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 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` 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} 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 removeLink();\n success(\"Unlinked from cloud project\");\n emit(() => {}, { success: true,\nunlinked: true,\nlinkPath: projectLinkPath() });\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","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 requireCloudRow,\n billingAccountIdOf\n} from \"./context\";\nimport { DEFAULT_STORAGE_SOURCE_KEY } from \"@rebasepro/types\";\nimport { firstRow, latestDeployment, fmtDate } from \"./projects\";\nimport { wantsRawError } from \"./errors\";\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 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 ]);\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 (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 }\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 ─────────────────────────────────────────────────── */\n\n/**\n * The webhook `webhooks delete` names.\n *\n * The worst instance of the operand-filter bug in this family, because the\n * argument is consumed by a DELETE and the wrong value looks entirely\n * plausible: `rebase cloud webhooks delete --project acme 42` filtered out\n * `--project` and kept \"acme\", so the id it deleted was the project slug rather\n * than the 42 the caller wrote. Strict parsing consumes the flag with its\n * value, leaving `[\"42\"]`.\n *\n * Exported so its tests drive the real parser.\n */\nexport function resolveWebhookIdArg(rawArgs: string[]): string | undefined {\n return parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud webhooks delete\n command: \"cloud webhooks delete\",\n maxPositionals: 1\n }).positionals[0];\n}\n\n/** The action words `rebase cloud webhooks` dispatches. No word means `list`. */\nexport const WEBHOOKS_ACTIONS = [\"list\", \"create\", \"delete\"] as const;\n\nexport async function webhooksCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // Before the parse and before the client: `webhooks creat` used to fall past\n // both `if`s and LIST the webhooks, exit 0, and leave the caller believing\n // one had been created.\n requireKnownAction(\"webhooks\", subcommand, WEBHOOKS_ACTIONS);\n\n // Both lines are parsed BEFORE the client is built. A line the parser will\n // refuse is refused without first spending a login round-trip on it — and\n // for `delete`, without the ambiguity of a refusal that arrives after the\n // command has already started talking to the control plane.\n const create = subcommand === \"create\"\n ? parseCloudArgs({\n // `--endpoint`, not `--url`.\n //\n // Every command in this family inherits a global `--url`, which\n // names the CONTROL PLANE — `resolveCloudUrl` reads it straight off\n // the raw line, before any per-command spec exists. A second\n // `--url` here did not shadow it, because the two parses are\n // independent: `webhooks create --url https://example.com/hook`\n // sent the customer's webhook endpoint to `requireClient` as the\n // control plane to authenticate against, so the documented example\n // could not create a webhook. Renaming is the fix; a per-command\n // flag cannot be a global's spelling, and `action-help.test.ts`\n // now sweeps for the class.\n spec: { \"--name\": String,\n\"--table\": String,\n\"--endpoint\": String,\n\"--events\": String },\n rawArgs,\n commandWords: 3, // cloud webhooks create\n command: \"cloud webhooks create\",\n maxPositionals: 0\n }).flags\n : undefined;\n const deleteId = subcommand === \"delete\" ? resolveWebhookIdArg(rawArgs) : undefined;\n if (subcommand === \"delete\" && !deleteId) {\n fail(\"Usage: rebase cloud webhooks delete <id>\", undefined, \"usage\");\n }\n // The listing takes only the globals, and took them permissively: `webhooks\n // list --tabel orders` listed every webhook and exited 0.\n if (!create && !deleteId) {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud webhooks\",\nmaxPositionals: 0 });\n }\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n if (subcommand === \"create\") {\n const args = create!;\n const name = args[\"--name\"] || fail(\"--name is required.\", undefined, \"usage\");\n const table = args[\"--table\"] || fail(\"--table is required.\", undefined, \"usage\");\n const url = args[\"--endpoint\"] || fail(\"--endpoint is required.\", \"Where the POST goes.\", \"usage\");\n const events = (args[\"--events\"] || \"insert,update,delete\").split(\",\").map((s) => s.trim());\n\n const created = requireCloudRow(await client.data.collection(\"webhooks\").create({\n project: projectId,\n name,\n table,\n url,\n events,\n enabled: true\n }), \"webhook\");\n success(`Created webhook ${chalk.bold(name)} [${created.id}]`);\n emit(() => {}, {\n success: true,\n id: String(created.id),\n projectId,\n name,\n table,\n url,\n events,\n enabled: true\n });\n return;\n }\n\n if (subcommand === \"delete\") {\n await client.data.collection(\"webhooks\").delete(deleteId!);\n success(`Deleted webhook ${deleteId}`);\n emit(() => {}, { success: true,\nid: deleteId!,\nprojectId });\n return;\n }\n\n // list\n const hooks = (await client.data.collection(\"webhooks\").find({\n where: { project: [\"==\", projectId] },\n limit: 100\n })).data as Array<{ id: string | number; name?: string; table?: string; url?: string; enabled?: boolean; events?: string[] }>;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔗 Webhooks — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (hooks.length === 0) {\n console.log(chalk.gray(\" No webhooks. Add one with `rebase cloud webhooks create`.\"));\n console.log(\"\");\n return;\n }\n for (const h of hooks) {\n const state = h.enabled ? chalk.green(\"enabled\") : chalk.gray(\"disabled\");\n console.log(` ${chalk.bold(h.name ?? \"(unnamed)\")} ${chalk.gray(`[${h.id}]`)} ${state}`);\n console.log(` ${chalk.gray(`${h.table ?? \"?\"} → ${h.url ?? \"?\"} (${(h.events ?? []).join(\", \")})`)}`);\n }\n console.log(\"\");\n },\n {\n projectId,\n webhooks: hooks.map((h) => ({\n id: String(h.id),\n name: h.name ?? null,\n table: h.table ?? null,\n url: h.url ?? null,\n events: h.events ?? [],\n enabled: h.enabled ?? null\n }))\n }\n );\n } catch (e) {\n reportError(e, \"Webhook operation failed\");\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\"] 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 // `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\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\"] 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 action = parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 2, // cloud billing\n command: \"cloud billing\",\n maxPositionals: 1\n }).positionals[0];\n requireKnownAction(\"billing\", action, BILLING_ACTIONS);\n\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\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 \"--scale-to-zero\": \"scaleToZero\",\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/** 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\", \"scaleToZero\"]);\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 spec: (action === \"set\" ? COMPUTE_SET_FLAGS : {}) 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 [\"When idle\", dialLine(project!.scaleToZero, { true: \"scale to zero\", false: \"stay warm\" })],\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 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 if (rawArgs.includes(\"--no-autoscale\")) {\n patch.autoscaleMaxReplicas = null;\n patch.autoscaleTargetCpuPercent = null;\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 * 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 * 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\";\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 tarPath = path.join(os.tmpdir(), `rebase-rebuild-src-${process.pid}-${Date.now()}.tar.gz`);\n const cost = \"Platform upgrades will not rebuild this project until a later deploy uploads its source.\";\n\n try {\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 } 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 } finally {\n fs.rmSync(tarPath, { force: true });\n }\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 */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport os from \"os\";\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 fetchTenantBaseDomain,\n projectHost,\n type CloudClient,\n billingAccountIdOf\n} from \"./context\";\nimport { latestDeployment, fmtDate } from \"./projects\";\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 { listContextFiles, MAX_SOURCE_UPLOAD_BYTES, packSource, prepareRebuildSource, type RebuildSource } from \"./rebuild-source\";\nimport { buildBundle } from \"../../bundle\";\nimport { buildAssetApp } from \"../build\";\nimport { foldFrontendIntoBundle } from \"../../fold-static\";\nimport { loadManifest, findBackendApp, formatAppAddress, resolveBackendPaths, selectDeployApp } from \"../../manifest\";\nimport { findProjectRoot, requireProjectRoot } from \"../../utils/project\";\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; returns the temp archive path.\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): Promise<string> {\n const dir = path.resolve(sourceDir);\n if (!fs.existsSync(dir)) fail(`Source directory not found: ${dir}`);\n\n const tarPath = path.join(os.tmpdir(), `rebase-src-${Date.now()}.tar.gz`);\n try {\n const files = listContextFiles(dir);\n await packSource({ root: fs.realpathSync(dir), files }, tarPath);\n } catch (e) {\n fs.rmSync(tarPath, { force: true });\n fail(`Failed to package source: ${e instanceof Error ? e.message : String(e)}`);\n }\n return tarPath;\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 /** 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 /** 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}): 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 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 }\n }\n\n await uploadAndTrigger({ ...opts,\nprojectRoot,\nbundleDir });\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 uploadSource: boolean;\n allowDowngrade: boolean;\n /** When the command started, for the `cli.deploy` event's duration. */\n startedAt: number;\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.\n const tarPath = path.join(os.tmpdir(), `rebase-bundle-${Date.now()}.tar.gz`);\n\n let bundleId: string;\n try {\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 bundleId = await uploadBundle(url, await uploadToken(client, url), projectId, tarPath);\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e));\n return;\n } finally {\n fs.rmSync(tarPath, { force: true });\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(` 🚀 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 const declaredApps = 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.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 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 // A refused bundle is a decision with a code and a remedy, not a\n // transport failure — the same branch `resolveTriggerFailure` takes\n // for a source build, which this path never reached.\n const refusal = intakeRefusal(e);\n if (refusal) fail(refusal.message, refusal.hint, refusal.code);\n reportError(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 if (!opts.follow) {\n emit(\n () => {\n console.log(chalk.green(` ✓ Managed deploy started (deployment ${deploymentId}).`));\n console.log(chalk.gray(\" Not following (--no-follow). Track it with `rebase cloud logs`.\"));\n printPendingHosts(hosts);\n },\n { success: true,\ndeploymentId,\nmanaged,\nsourceUploaded: rebuildSource !== null,\nfollowing: false,\n...(hosts ? { hosts } : {}) }\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 hosts,\n onTerminal: (ended) => record(true, ended)\n });\n emit(() => printPendingHosts(hosts), { success: true,\ndeploymentId,\nmanaged,\nsourceUploaded: rebuildSource !== null,\nfollowing: true,\nstatus,\n...(hosts ? { hosts } : {}) });\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 \"--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 /* 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 \"-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 // 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 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 follow: args[\"--no-follow\"] !== true,\n timeoutMs: resolveDeployTimeout(args[\"--timeout\"]),\n uploadSource: args[\"--no-source\"] !== true,\n allowDowngrade: args[\"--allow-downgrade\"] === true,\n startedAt\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 tarPath = await createSourceTarball(args[\"--source\"]);\n try {\n source = await uploadSource(url, await uploadToken(client, url), projectId, tarPath);\n } finally {\n fs.rmSync(tarPath, { force: true });\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 if (args[\"--no-follow\"]) {\n emit(\n () => {\n console.log(chalk.gray(\" Not following logs (--no-follow). Check status with `rebase cloud logs`.\"));\n console.log(\"\");\n printPendingHosts(hosts);\n },\n { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: false,\n...(hosts ? { hosts } : {}),\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 hosts,\n onTerminal: (ended) => recordDeploy({ followed: true, status: ended, deduplicated, frameworkVersion, startedAt })\n });\n emit(\n () => printPendingHosts(hosts),\n { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: true,\nstatus,\n...(hosts ? { hosts } : {}),\n...warningPayload(warnings) }\n );\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): 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, \"Failed to trigger deployment\");\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 * The hostnames the deploy response named. The verified ones are\n * printed under the project's own URL on success: an app on a hostname\n * of its own is not at the project URL, and that address is the one the\n * person who deployed it is looking for.\n */\n hosts?: DeployHost[];\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): Promise<{ status: string; logs: string }> {\n const quiet = opts.quiet === true;\n const timeoutMs = opts.timeoutMs ?? POLL_TIMEOUT_MS;\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 `rebase cloud logs`.\",\n \"timeout\"\n );\n };\n\n for (;;) {\n let dep: Deployment | undefined;\n try {\n dep = (await client.data.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 `rebase cloud logs`.\",\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 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: `Deployment ${deploymentId} ${dep.status}.`,\n code: \"deploy_failed\",\n status: null,\n deploymentId,\n logs: withoutHeartbeat(dep.logs ?? \"\")\n }\n });\n process.exit(1);\n }\n console.log(\"\");\n console.log(chalk.bold.red(` ✗ Deployment ${dep.status}`));\n console.log(\"\");\n process.exit(1);\n }\n if (!quiet) {\n console.log(\"\");\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 for (const { host } of (opts.hosts ?? []).filter(h => h.status === \"verified\")) {\n if (host !== url) console.log(` ${chalk.cyan(`https://${host}`)}`);\n }\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} 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 } = parseCloudArgs({\n spec: LOGS_FLAGS,\n rawArgs,\n commandWords: 2, // cloud logs\n command: \"cloud logs\",\n maxPositionals: 0\n });\n const { client, url } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n if (args[\"--runtime\"]) {\n try {\n const res = await client.functions.invoke<{ logs?: string; error?: string }>(\n \"runtime-logs\",\n undefined,\n { method: \"GET\",\npath: projectId }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 📄 Runtime logs — project ${projectRef}`));\n console.log(\"\");\n console.log(res.logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n },\n { runtime: true,\nlogs: res.logs ?? null }\n );\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\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 * `rebase cloud orgs` — list / create / members.\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} 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 listMembers(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\nasync function listMembers(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud orgs\",\nmaxPositionals: 0 });\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\", \"no_org\");\n\n try {\n const members = (await client.data.collection(\"organization-members\").find({\n where: { organization: [\"==\", org] },\n limit: 200\n })).data as Array<{ id: string | number; userId?: string; role?: string }>;\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 console.log(` ${chalk.bold(m.userId ?? \"?\")} ${colorStatus(m.role)}`);\n }\n console.log(\"\");\n },\n {\n org,\n members: members.map((m) => ({\n id: String(m.id),\n userId: m.userId ?? null,\n role: m.role ?? null\n }))\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list members\");\n }\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 { action: \"members\",\ndescription: \"List members of the active organization\" }\n ],\n notes: [\"The active one is what `rebase cloud use` selects, and what billing is scoped to.\"]\n });\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 * 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 {\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\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 \"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 parseCloudArgs({ spec: {},\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 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/** 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} as const;\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,\nassignment: parseEnvAssignment(positionals) };\n}\n\nasync function setEnv(rawArgs: string[]): Promise<void> {\n const { flags: args, assignment: parsed } = resolveEnvSetArgs(rawArgs);\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 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 parseCloudArgs({\n spec: {},\n rawArgs,\n commandWords: 3, // cloud env <action>\n command: `cloud env ${action}`,\n maxPositionals: 1\n }).positionals[0];\n}\n\nasync function unsetEnv(rawArgs: string[], action: string): Promise<void> {\n const key = resolveEnvKeyArg(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\", undefined, \"usage\");\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\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\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\" },\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 ]\n },\n { action: \"unset\",\nargs: \"KEY\",\ndescription: \"Remove a variable\" },\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 ]\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/** 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 // Prefer the previous good image when the newest deploy is itself good\n // (rolling back to the live image is a no-op); otherwise the most recent\n // good one.\n target = rollbackable.find((d) => String(d.id) !== String(rows![0].id)) ?? rollbackable[0];\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 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 return /storage|Loaded function|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 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 { 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 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] [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 ]\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 [\"--scale-to-zero <true|false>\", \"Stop the instances when idle\"],\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 <size>\", \"Database volume size\"]\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.\",\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 [\"--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 [\"--allow-downgrade\", \"Deploy a bundle built on an older framework release than the project runs\"],\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 --timeout 300 --json\"\n ],\n notes: [\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 ]\n },\n\n logs: {\n command: \"cloud logs\",\n usage: \"cloud logs [--runtime] [--follow]\",\n summary: \"The latest build log, or the running container's log with --runtime.\",\n flags: [\n [\"--runtime\", \"The running app's log instead of the build log\"],\n [\"--follow, -f\", \"Tail a build that is still running\"]\n ],\n examples: [\"rebase cloud logs\", \"rebase cloud logs --runtime\", \"rebase cloud logs -f\"]\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 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 [--secret] [--force]\",\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 ],\n examples: [\n \"rebase cloud env set STRIPE_KEY=sk_live_… --secret\",\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 \"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 \"webhooks create\": {\n command: \"cloud webhooks create\",\n usage:\n \"cloud webhooks create --name <name> --table <table> --endpoint <url> [--events <list>]\",\n summary: \"Register an outbound webhook on a table's row changes.\",\n flags: [\n [\"--name <name>\", \"Required. What it is called in listings\"],\n [\"--table <table>\", \"Required. The table whose changes fire it\"],\n [\"--endpoint <url>\", \"Required. Where the POST goes\"],\n [\"--events <list>\", \"Comma-separated: insert, update, delete. Default: all three\"]\n ],\n examples: [\n \"rebase cloud webhooks create --name notify --table orders --endpoint https://example.com/hook\",\n \"rebase cloud webhooks create --name audit --table users --endpoint https://example.com/hook --events insert,delete\"\n ],\n notes: [\n \"`--endpoint`, not `--url`: every cloud command's `--url` names the control plane, and one written here would be authenticated against instead of called.\"\n ]\n },\n\n \"webhooks delete\": {\n command: \"cloud webhooks delete\",\n usage: \"cloud webhooks delete <id>\",\n summary: \"Remove one webhook by the id `webhooks list` prints.\",\n flags: [],\n examples: [\"rebase cloud webhooks delete 42\"]\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 <list|create|delete> [options]\",\n summary: \"Outbound webhooks on a table's row changes.\",\n flags: [],\n examples: [\n \"rebase cloud webhooks list\",\n \"rebase cloud webhooks create --help\",\n \"rebase cloud webhooks delete 42\"\n ]\n },\n\n billing: {\n command: \"cloud billing\",\n usage: \"cloud billing [setup|checkout]\",\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. \"\n + \"Organization-scoped, not project-scoped.\",\n flags: [],\n examples: [\n \"rebase cloud billing\",\n \"rebase cloud billing setup\",\n \"rebase cloud billing checkout --project shop\"\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 ]\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: 250m\"],\n [\"--memory <size>\", \"App memory request per instance, e.g. 512Mi or 2Gi. Default: 512Mi\"],\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 [\"--scale-to-zero <true|false>\", \"Request-billed compute that stops when idle, at the cost of a cold start\"],\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: 500m\"],\n [\"--db-memory <size>\", \"Database memory request per instance. Default: 2Gi\"],\n [\"--storage <size>\", \"Database volume size\"],\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>]\",\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 ],\n examples: [\n \"rebase cloud login\",\n \"rebase cloud login --email me@example.com\",\n \"rebase cloud login --url https://cloud.example.com\"\n ],\n notes: [\n \"--password warns, once, before the request: by the time a login succeeds the password is already in the history file.\",\n \"There is no machine token yet, so CI genuinely needs a human's credentials. REBASE_CLOUD_EMAIL and \"\n + \"REBASE_CLOUD_PASSWORD are how a secret store hands them 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>] [--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. The token is printed once, as the `export REBASE_TOKEN=…` line \"\n + \"to hand to CI.\",\n flags: [\n [\"--can <capabilities>\", `Comma-separated or repeated: ${TOKEN_CAPABILITY_NAMES.join(\", \")}`],\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 ],\n notes: [\n ...TOKEN_CAPABILITY_NAMES.map(name => `${name}: ${TOKEN_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 \"`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 { 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 {\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 \"--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 \"--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 \"--function\": String,\n \"--host\": String,\n \"--ingress-address\": String,\n \"--kubeconfig\": String,\n \"--limit\": String,\n \"--memory\": String,\n \"--message\": String,\n \"--name\": String,\n \"--org\": String,\n \"--output\": String,\n \"--password\": String,\n \"--platform-rebuilds\": String,\n \"--port\": String,\n \"--provider\": String,\n \"--region\": String,\n \"--replicas\": String,\n \"--repo\": 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 \"--table\": 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 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\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 \"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 \"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 \"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 \"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: \"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: \"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\n { action: \"orgs\", section: \"Organizations\", description: \"Organizations you belong to, and their members\" },\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: \"webhooks\", section: \"Other resources\", description: \"Outbound webhooks on a table's row changes\" },\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];\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":";;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,yBAAqD;CAAC;CAAU;CAAQ;CAAO;CAAY;AAAS;;;;;;AAOjH,IAAa,gBAA0B;CACnC;CACA;CACA;CACA;AACJ;;AAGA,IAAa,qBAA0G;CACnH,QAAQ;EACJ,OAAO;EACP,SAAS,cAAc;GACnB,gBAAgB;GAChB,kBAAkB;GAClB;EACJ;CACJ;CACA,MAAM;EACF,OAAO;EACP,SAAS,cAAc;GACnB,gBAAgB;GAChB,gBAAgB;GAChB;GACA;GACA;EACJ;CACJ;CACA,KAAK;EACD,OAAO;EACP,SAAS,cAAc,CACnB,eAAe,aACf,2BACJ;CACJ;CACA,UAAU;EACN,OAAO;EACP,SAAS,cAAc;GACnB,gBAAgB;GAChB,oBAAoB;GACpB;GACA;EACJ;CACJ;CACA,SAAS;EACL,OAAO;EACP,SAAS,cAAc;GACnB,gBAAgB;GAChB,mBAAmB;GACnB;EACJ;CACJ;AACJ;;AAGA,SAAgB,kBAAkB,OAAyC;CACvE,OAAQ,uBAA6C,SAAS,KAAK;AACvE;;;;;;;;;AAUA,SAAgB,sBAAsB,WAAmB,cAAoD;CACzG,IAAI,UAAU,WAAW,KAAK,KAAK,KAAK,SAAS,GAC7C,MAAM,IAAI,MAAM,IAAI,UAAU,kDAAkD;CAEpF,MAAM,SAAS,IAAI,IAAY,aAAa;CAC5C,KAAK,MAAM,cAAc,cAAc;EACnC,IAAI,CAAC,kBAAkB,UAAU,GAC7B,MAAM,IAAI,MAAM,IAAI,OAAO,UAAU,EAAE,6CAA6C,uBAAuB,KAAK,IAAI,EAAE,EAAE;EAE5H,KAAK,MAAM,SAAS,mBAAmB,WAAW,CAAC,OAAO,SAAS,GAAG,OAAO,IAAI,KAAK;CAC1F;CACA,OAAO,CAAC,GAAG,MAAM;AACrB;;;;;;;;AASA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