@rebasepro/cli 0.11.1-canary.gfd39654 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/rebase.js +21 -0
- package/dist/bundle.d.ts +24 -7
- package/dist/commands/eject.d.ts +1 -0
- package/dist/commands/init.d.ts +19 -15
- package/dist/fold-static.d.ts +41 -15
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +894 -246
- package/dist/index.es.js.map +1 -1
- package/dist/manifest.d.ts +27 -8
- package/package.json +7 -7
- package/runtime/dev-server.mjs +0 -1
- package/templates/{template/backend → eject}/Dockerfile +16 -4
- package/templates/{template → eject}/backend/src/env.ts +0 -1
- package/templates/{template → eject}/backend/src/index.ts +41 -27
- package/templates/eject/docker-compose.custom.yml +71 -0
- package/templates/overlays/baas/backend/package.json +1 -4
- package/templates/overlays/baas/backend/tsconfig.json +8 -2
- package/templates/overlays/baas/config/index.ts +15 -0
- package/templates/overlays/baas/config/package.json +28 -0
- package/templates/overlays/baas/package.json +2 -1
- package/templates/overlays/baas/pnpm-workspace.yaml +1 -0
- package/templates/overlays/baas/rebase.json +2 -6
- package/templates/template/.env.example +15 -0
- package/templates/template/README.md +56 -22
- package/templates/template/ai-instructions.md +1 -0
- package/templates/template/backend/functions/hello.ts +45 -14
- package/templates/template/backend/package.json +1 -4
- package/templates/template/backend/tsconfig.json +23 -2
- package/templates/template/config/tsconfig.json +16 -1
- package/templates/template/docker-compose.yml +62 -38
- package/templates/template/frontend/src/main.tsx +8 -1
- package/templates/template/frontend/vite.config.ts +5 -0
- package/templates/template/rebase.json +5 -8
- package/templates/overlays/baas/backend/src/index.ts +0 -216
- package/templates/template/frontend/Dockerfile +0 -52
- package/templates/template/frontend/nginx.conf +0 -40
- /package/templates/overlays/baas/{backend/src → config}/storage.ts +0 -0
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","names":[],"sources":["../src/utils/package-manager.ts","../src/utils/project.ts","../src/commands/cloud/context.ts","../src/commands/init.ts","../src/commands/generate_sdk.ts","../src/commands/schema.ts","../src/commands/db.ts","../src/manifest.ts","../src/commands/dev.ts","../src/bundle.ts","../src/fold-static.ts","../src/commands/build.ts","../src/commands/start.ts","../src/commands/auth.ts","../src/commands/doctor.ts","../src/commands/skills.ts","../src/commands/api-keys.ts","../src/commands/cloud/auth.ts","../src/commands/cloud/link.ts","../src/commands/cloud/projects.ts","../src/commands/cloud/bundle-deploy.ts","../src/commands/cloud/deploy.ts","../src/commands/cloud/orgs.ts","../src/commands/cloud/databases.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/resources.ts","../src/commands/cloud/index.ts","../src/commands/apps.ts","../src/cli.ts"],"sourcesContent":["/**\n * Package manager detection and command abstraction.\n *\n * Detects whether the user is running pnpm or npm and provides\n * a unified interface for common package-manager operations so\n * the rest of the CLI never has to hardcode a specific PM.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { spawnSync } from \"child_process\";\n\nexport type PackageManager = \"pnpm\" | \"npm\";\n\nexport interface PMCommands {\n /** The binary name (\"pnpm\" | \"npm\"). */\n name: PackageManager;\n /** Install all dependencies — e.g. `pnpm install` / `npm install`. */\n install: string[];\n /** Run a script — e.g. `pnpm run dev` / `npm run dev`. */\n run: (script: string) => string[];\n /** Execute a local bin — e.g. `pnpm exec rebase ...` / `npx rebase ...`. */\n exec: (bin: string, args: string[]) => string[];\n /** Query the registry — e.g. `pnpm view <pkg> version` / `npm view <pkg> version`. */\n view: (pkg: string, field: string) => string[];\n /** Run all workspace scripts — e.g. `pnpm -r run build` / `npm run build --workspaces`. */\n runAll: (script: string) => string[];\n /** Run a script in a specific workspace — e.g. `pnpm --filter \"*-backend\" start` / `npm run start -w backend`. */\n runWorkspace: (workspace: string, script: string) => string[];\n /** Execute a one-off package — e.g. `pnpm dlx skills ...` / `npx -y skills ...`. */\n dlx: (pkg: string, args: string[]) => string[];\n /** The workspace dependency protocol: `\"workspace:*\"` for pnpm, `\"*\"` for npm. */\n workspaceProtocol: string;\n}\n\n/**\n * How long to wait for `pnpm --version` before giving up on the probe.\n *\n * `pnpm --version` is a cold Node start, and on a machine that is busy — a\n * parallel install, a full test run — it routinely takes seconds. Measured at\n * 630ms, 990ms and 4293ms on three consecutive runs of one developer laptop\n * under load, so the previous 3s budget was inside the normal spread rather\n * than safely outside it.\n */\nconst PNPM_PROBE_TIMEOUT_MS = 5000;\n\n/** Memoised result of the probe. pnpm cannot appear or vanish mid-process. */\nlet cachedPnpmAvailable: boolean | undefined;\n\n/**\n * Decide availability from a `spawnSync` outcome.\n *\n * Split out from the spawn itself so the decision is testable without starting\n * a process — which is what made the old test load-sensitive and occasionally\n * red for reasons that had nothing to do with the code under test.\n *\n * The three outcomes are distinguishable, and the old code conflated two of\n * them by asking only `status === 0`:\n *\n * not installed status null, signal null, error.code ENOENT\n * timed out status null, signal SIGTERM, error.code ETIMEDOUT\n * broken install status non-zero, no error\n */\nexport function pnpmAvailabilityFromProbe(res: {\n status: number | null;\n signal?: NodeJS.Signals | null;\n error?: { code?: string } | Error;\n}): boolean {\n const code = (res.error as { code?: string } | undefined)?.code;\n\n // The binary is not on PATH. Genuinely absent.\n if (code === \"ENOENT\") return false;\n\n // We killed it for taking too long. That means it WAS found and did start,\n // so pnpm is installed — it was merely slow, which on a loaded machine is\n // routine rather than exceptional. Reporting \"absent\" here is what silently\n // scaffolded npm projects for developers who had pnpm all along.\n //\n // The trade-off, stated plainly: a pnpm that hangs forever (a misbehaving\n // corepack shim) now resolves to pnpm instead of falling back to npm. That\n // is the rarer and more visible failure — the user sees their next command\n // hang — whereas the case this fixes was silent and produced a project\n // pinned to the wrong package manager. The timeout still bounds how long\n // detection itself waits, which was always its real job.\n if (code === \"ETIMEDOUT\" || res.signal) return true;\n\n // Any other spawn error: treat as unavailable rather than guess.\n if (res.error) return false;\n\n return res.status === 0;\n}\n\n/**\n * Whether pnpm is runnable on this machine.\n *\n * Used to decide whether a fresh project can be scaffolded with pnpm. Kept\n * cheap and non-interactive (bounded timeout, output discarded) so it never\n * hangs detection if a corepack shim misbehaves, and memoised so that repeated\n * detection in one CLI run costs one process rather than one per call.\n */\nexport function isPnpmAvailable(): boolean {\n if (cachedPnpmAvailable !== undefined) return cachedPnpmAvailable;\n try {\n const res = spawnSync(\"pnpm\", [\"--version\"], {\n stdio: \"ignore\",\n timeout: PNPM_PROBE_TIMEOUT_MS\n });\n cachedPnpmAvailable = pnpmAvailabilityFromProbe(res);\n } catch {\n cachedPnpmAvailable = false;\n }\n return cachedPnpmAvailable;\n}\n\n/** Forget the memoised probe. For tests; nothing in a CLI run needs it. */\nexport function resetPnpmAvailabilityCache(): void {\n cachedPnpmAvailable = undefined;\n}\n\n/**\n * Detect the package manager for a Rebase project.\n *\n * Rebase recommends pnpm, so detection prefers it. Crucially, *how the CLI was\n * invoked* (`npx` vs `pnpm dlx`, i.e. `npm_config_user_agent`) is deliberately\n * ignored: running `npx @rebasepro/cli init` says nothing about how the user\n * wants to manage the project they're creating, and letting it pin the scaffold\n * to npm is what made every `npx`-invoked project an npm project.\n *\n * Detection order:\n * 1. An existing lock file — an explicit choice we always respect\n * (`pnpm-lock.yaml` wins over `package-lock.json` when both are present).\n * 2. pnpm, whenever it is installed.\n * 3. npm, only as a fallback when pnpm is genuinely unavailable.\n */\nexport function detectPackageManager(targetDir?: string): PackageManager {\n // 1. Respect an existing project's lock file.\n const dirs = [targetDir, process.cwd()].filter((d): d is string => !!d);\n for (const dir of dirs) {\n if (fs.existsSync(path.join(dir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (fs.existsSync(path.join(dir, \"package-lock.json\"))) return \"npm\";\n }\n\n // 2. Prefer pnpm whenever it's installed.\n if (isPnpmAvailable()) return \"pnpm\";\n\n // 3. Fall back to npm only when pnpm is genuinely unavailable.\n return \"npm\";\n}\n\n/** Build the command helpers for a given package manager. */\nexport function getPMCommands(pm: PackageManager): PMCommands {\n if (pm === \"npm\") {\n return {\n name: \"npm\",\n install: [\"npm\", \"install\"],\n run: (script) => [\"npm\", \"run\", script],\n exec: (bin, args) => [\"npx\", bin, ...args],\n view: (pkg, field) => [\"npm\", \"view\", pkg, field],\n runAll: (script) => [\"npm\", \"run\", script, \"--workspaces\", \"--if-present\"],\n runWorkspace: (workspace, script) => [\"npm\", \"run\", script, \"-w\", workspace],\n dlx: (pkg, args) => [\"npx\", \"-y\", pkg, ...args],\n workspaceProtocol: \"*\"\n };\n }\n\n return {\n name: \"pnpm\",\n install: [\"pnpm\", \"install\"],\n run: (script) => [\"pnpm\", \"run\", script],\n exec: (bin, args) => [\"pnpm\", \"exec\", bin, ...args],\n view: (pkg, field) => [\"pnpm\", \"view\", pkg, field],\n runAll: (script) => [\"pnpm\", \"-r\", \"run\", script],\n // Filter by directory (`./backend`), not name: pnpm's `--filter` matches\n // the package *name* (e.g. `my-app-backend`), so a bare `backend` matches\n // nothing. npm's `-w` is path-based, which is why this only bites pnpm.\n runWorkspace: (workspace, script) => [\"pnpm\", \"--filter\", `./${workspace}`, \"run\", script],\n dlx: (pkg, args) => [\"pnpm\", \"dlx\", pkg, ...args],\n workspaceProtocol: \"workspace:*\"\n };\n}\n","/**\n * Project discovery utilities for the Rebase CLI.\n *\n * These helpers locate the project root, backend directory, .env file,\n * and local binaries — used by all CLI command modules.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\nimport chalk from \"chalk\";\n\n/** The authored project manifest. Its presence alone marks a project root. */\nexport const MANIFEST_FILENAME = \"rebase.json\";\n\n/**\n * Walk up from `startDir` to find the Rebase project root.\n *\n * A directory is the root when it holds a `rebase.json`, or when it holds a\n * `package.json` that either lists `backend` as a workspace or sits beside both\n * `backend/` and `config/`.\n *\n * `rebase.json` is checked first and needs no `package.json` beside it, because\n * the conventions below all describe a repository that *contains the backend*.\n * A repository holding only a frontend — the normal shape once a project's apps\n * live in separate repositories — matches none of them, so without this the\n * tooling could not run there at all.\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n if (fs.existsSync(path.join(dir, MANIFEST_FILENAME))) {\n return dir;\n }\n\n const pkgPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n // Check for workspace-based project (monorepo root)\n if (pkg.workspaces && Array.isArray(pkg.workspaces)) {\n const hasBackend = pkg.workspaces.some((w: string) =>\n w === \"backend\"\n );\n if (hasBackend) return dir;\n }\n } catch {\n // ignore parse errors\n }\n\n // Check for sibling backend directory\n if (fs.existsSync(path.join(dir, \"backend\")) && fs.existsSync(path.join(dir, \"config\"))) {\n return dir;\n }\n }\n\n dir = path.dirname(dir);\n }\n\n return null;\n}\n\n/**\n * Locate the backend directory within the project root.\n */\nexport function findBackendDir(projectRoot: string): string | null {\n const backendDir = path.join(projectRoot, \"backend\");\n return fs.existsSync(backendDir) ? backendDir : null;\n}\n\n/**\n * Detect the active backend plugin (e.g. @rebasepro/server-postgres) from the backend's package.json.\n */\nexport function getActiveBackendPlugin(backendDir: string): string | null {\n const pkgPath = path.join(backendDir, \"package.json\");\n if (!fs.existsSync(pkgPath)) return null;\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const deps = { ...pkg.dependencies,\n...pkg.devDependencies };\n\n // Collect all @rebasepro/server-* driver plugins (exclude server itself)\n const candidates = Object.keys(deps).filter(\n dep => dep.startsWith(\"@rebasepro/server-\") && dep !== \"@rebasepro/server\"\n );\n\n if (candidates.length === 0) return null;\n\n // Prefer server-postgres — it's the primary supported driver\n if (candidates.includes(\"@rebasepro/server-postgres\")) {\n return \"@rebasepro/server-postgres\";\n }\n\n // Fallback: return the first candidate that actually has a CLI entry point\n for (const candidate of candidates) {\n if (resolvePluginCliScript(backendDir, candidate)) {\n return candidate;\n }\n }\n\n // Last resort: return whatever we found\n return candidates[0];\n } catch {\n // Ignore parse errors\n }\n return null;\n}\n\n/**\n * Resolve the active plugin's CLI script.\n */\nexport function resolvePluginCliScript(backendDir: string, pluginName: string): string | null {\n const candidates: string[] = [];\n\n // Walk up from the backend dir: pnpm links the plugin into\n // backend/node_modules, while npm workspaces hoist it to the project (or an\n // enclosing monorepo) root.\n let dir = path.resolve(backendDir);\n const fsRoot = path.parse(dir).root;\n while (dir !== fsRoot) {\n candidates.push(\n path.join(dir, \"node_modules\", pluginName, \"src\", \"cli.ts\"),\n path.join(dir, \"node_modules\", pluginName, \"dist\", \"cli.js\")\n );\n dir = path.dirname(dir);\n }\n\n candidates.push(\n // For monorepo dev mode:\n path.resolve(backendDir, \"..\", \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\")\n );\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Locate the frontend directory within the project root.\n */\nexport function findFrontendDir(projectRoot: string): string | null {\n const frontendDir = path.join(projectRoot, \"frontend\");\n return fs.existsSync(frontendDir) ? frontendDir : null;\n}\n\n/**\n * Find the .env file. Checks the project root first, then backend.\n */\nexport function findEnvFile(projectRoot: string): string | null {\n const candidates = [\n path.join(projectRoot, \".env\"),\n path.join(projectRoot, \"backend\", \".env\")\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n return null;\n}\n\n/**\n * Resolve a binary from the project's node_modules/.bin.\n * Checks backend, root, parent monorepo root, then falls back to PATH.\n */\nexport function resolveLocalBin(projectRoot: string, binName: string): string | null {\n const candidates = [\n path.join(projectRoot, \"backend\", \"node_modules\", \".bin\", binName),\n path.join(projectRoot, \"node_modules\", \".bin\", binName)\n ];\n\n // Also check parent directories (for monorepo setups where app/ is nested)\n let parent = path.dirname(projectRoot);\n const rootDir = path.parse(parent).root;\n while (parent !== rootDir) {\n candidates.push(path.join(parent, \"node_modules\", \".bin\", binName));\n parent = path.dirname(parent);\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n // Fall back to globally installed binary via which\n try {\n const globalPath = execSync(`which ${binName}`, { encoding: \"utf-8\" }).trim();\n if (globalPath && fs.existsSync(globalPath)) return globalPath;\n } catch {\n // not found globally\n }\n\n return null;\n}\n\n/**\n * Resolve the tsx binary. Checks backend node_modules first, then root.\n */\nexport function resolveTsx(projectRoot: string): string | null {\n return resolveLocalBin(projectRoot, \"tsx\");\n}\n\n/**\n * Validate that a resolved tsx binary actually has an intact installation.\n *\n * `resolveLocalBin` only checks whether `node_modules/.bin/tsx` (a symlink)\n * exists. If the pnpm content-addressable store was cleaned or a previous\n * install was interrupted, the symlink can exist while critical files inside\n * the tsx package (e.g. `dist/preflight.cjs`) are missing — causing a\n * confusing MODULE_NOT_FOUND error at runtime.\n *\n * This function follows the symlink, walks up to find the tsx package root\n * (`package.json` with `name: \"tsx\"`), and verifies that `dist/preflight.cjs`\n * is present. Returns `null` when the installation looks healthy, or an\n * error description string when it appears corrupted.\n */\nexport function validateTsxInstallation(tsxBinPath: string): string | null {\n try {\n // Follow the symlink chain to the real tsx entry script\n const realPath = fs.realpathSync(tsxBinPath);\n\n // Walk up from the real binary to locate the tsx package root\n let dir = path.dirname(realPath);\n const fsRoot = path.parse(dir).root;\n for (let depth = 0; depth < 10 && dir !== fsRoot; depth++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg.name === \"tsx\") {\n // Found the tsx package root — verify critical preload file\n const preflightPath = path.join(dir, \"dist\", \"preflight.cjs\");\n if (!fs.existsSync(preflightPath)) {\n return `tsx package at ${dir} is missing dist/preflight.cjs`;\n }\n return null; // Installation looks healthy\n }\n } catch {\n // Malformed package.json — keep walking\n }\n }\n dir = path.dirname(dir);\n }\n\n // Could not determine tsx root — don't block, assume valid\n return null;\n } catch (err) {\n // realpathSync throws if the symlink target is completely gone\n return `tsx binary symlink is broken: ${err instanceof Error ? err.message : String(err)}`;\n }\n}\n\n/**\n * Require the project root or exit with a helpful error.\n */\nexport function requireProjectRoot(): string {\n const root = findProjectRoot();\n if (!root) {\n console.error(chalk.red(\"✗ Could not find a Rebase project root.\"));\n console.error(chalk.gray(\" Make sure you are inside a Rebase project directory\"));\n console.error(chalk.gray(\" (one with backend/, frontend/, and config/ directories).\"));\n process.exit(1);\n }\n return root;\n}\n\n/**\n * Require the backend directory or exit with a helpful error.\n */\nexport function requireBackendDir(projectRoot: string): string {\n const backendDir = findBackendDir(projectRoot);\n if (!backendDir) {\n console.error(chalk.red(\"✗ Could not find a backend/ directory.\"));\n console.error(chalk.gray(` Expected at: ${path.join(projectRoot, \"backend\")}`));\n process.exit(1);\n }\n return backendDir;\n}\n","/**\n * Shared foundation for the `rebase cloud` command family.\n *\n * Everything cloud subcommands need in common lives here:\n * - credential storage (~/.rebase/credentials.json, keyed per control-plane host)\n * - project link file (.rebase/cloud.json in the project dir)\n * - control-plane URL resolution\n * - an authenticated `@rebasepro/client` instance (createCloudClient / requireClient)\n * - small output helpers shared across subcommands\n *\n * The control plane is itself a Rebase app, so we reuse the same SDK the web\n * console uses (`@rebasepro/client`). Auth, token refresh, the data REST client\n * and function invocation all come from the SDK — the CLI only supplies a\n * file-backed AuthStorage so a login persists across invocations.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { spawn } from \"child_process\";\nimport chalk from \"chalk\";\nimport arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport { createRebaseClient, type AuthStorage } from \"@rebasepro/client\";\nimport { findProjectRoot } from \"../../utils/project\";\n\n/* ═══════════════════════════════════════════════════════════════\n Constants & paths\n ═══════════════════════════════════════════════════════════════ */\n\n/** Default hosted control plane (the Rebase Cloud console origin). */\nconst DEFAULT_CLOUD_URL = \"https://app.rebase.pro\";\n\n/** The storage key the SDK's auth module reads/writes the session under. */\nconst SDK_SESSION_KEY = \"rebase_auth\";\n\n/** ~/.rebase/credentials.json — one file, many hosts. */\nfunction credentialsPath(): string {\n return path.join(os.homedir(), \".rebase\", \"credentials.json\");\n}\n\n/** Project-local link file: <project>/.rebase/cloud.json */\nexport function projectLinkPath(cwd: string = process.cwd()): string {\n const root = findProjectRoot(cwd) || cwd;\n return path.join(root, \".rebase\", \"cloud.json\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Credentials file model\n ═══════════════════════════════════════════════════════════════\n\n {\n \"current\": \"https://app.rebase.pro\",\n \"contexts\": {\n \"https://app.rebase.pro\": { \"auth\": \"<sdk session json>\", \"org\": \"42\" }\n }\n }\n*/\n\ninterface CloudContextEntry {\n /** Raw JSON blob the SDK auth module persists (the RebaseSession). */\n auth?: string;\n /** Active organization id for this host, if the user selected one. */\n org?: string;\n}\n\ninterface CredentialsFile {\n current?: string;\n contexts: Record<string, CloudContextEntry>;\n}\n\nfunction readCredentials(): CredentialsFile {\n try {\n const raw = fs.readFileSync(credentialsPath(), \"utf-8\");\n const parsed = JSON.parse(raw) as CredentialsFile;\n if (!parsed.contexts) parsed.contexts = {};\n return parsed;\n } catch {\n return { contexts: {} };\n }\n}\n\nfunction writeCredentials(data: CredentialsFile): void {\n const file = credentialsPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n // Written with private perms — this file holds refresh tokens.\n fs.writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 });\n try {\n fs.chmodSync(file, 0o600);\n } catch {\n // best effort on platforms without chmod semantics\n }\n}\n\n/** Host that a bare `rebase cloud` command should target, if any. */\nfunction currentContextUrl(): string | undefined {\n return readCredentials().current;\n}\n\n/** Persist the active organization id for a host. */\nexport function setContextOrg(url: string, org: string | undefined): void {\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n if (org) entry.org = org;\n else delete entry.org;\n creds.contexts[url] = entry;\n writeCredentials(creds);\n}\n\nexport function getContextOrg(url: string): string | undefined {\n return readCredentials().contexts[url]?.org;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n File-backed AuthStorage (per host)\n ═══════════════════════════════════════════════════════════════ */\n\nfunction createFileAuthStorage(url: string): AuthStorage {\n return {\n getItem(key) {\n if (key !== SDK_SESSION_KEY) return null;\n return readCredentials().contexts[url]?.auth ?? null;\n },\n setItem(key, value) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n entry.auth = value;\n creds.contexts[url] = entry;\n if (!creds.current) creds.current = url;\n writeCredentials(creds);\n },\n removeItem(key) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n if (creds.contexts[url]) {\n delete creds.contexts[url].auth;\n delete creds.contexts[url].org;\n }\n writeCredentials(creds);\n }\n };\n}\n\n/** Mark a host as the active context (called on login). */\nexport function setCurrentContext(url: string): void {\n const creds = readCredentials();\n creds.current = url;\n if (!creds.contexts[url]) creds.contexts[url] = {};\n writeCredentials(creds);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n URL resolution\n ═══════════════════════════════════════════════════════════════\n\n Priority: --url flag > REBASE_CLOUD_URL env > linked project's url\n > stored current context > default hosted URL.\n*/\n\nexport function resolveCloudUrl(rawArgs: string[]): string {\n const parsed = arg({ \"--url\": String }, { argv: rawArgs.slice(2),\npermissive: true });\n const explicit = parsed[\"--url\"] || process.env.REBASE_CLOUD_URL;\n if (explicit) return normalizeUrl(explicit);\n\n const link = readLink();\n if (link?.url) return normalizeUrl(link.url);\n\n const current = currentContextUrl();\n if (current) return normalizeUrl(current);\n\n return DEFAULT_CLOUD_URL;\n}\n\nfunction normalizeUrl(url: string): string {\n let u = url.trim().replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(u)) u = `https://${u}`;\n return u;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Rebase client factory + auth guard\n ═══════════════════════════════════════════════════════════════ */\n\nexport type CloudClient = ReturnType<typeof createRebaseClient>;\n\n/**\n * Build an SDK client bound to a control-plane host, backed by the on-disk\n * credential store. `autoRefresh` is disabled so we never leave a dangling\n * setTimeout that keeps the CLI process alive; token refresh is done on demand\n * by `requireClient`.\n */\nexport function createCloudClient(url: string): CloudClient {\n return createRebaseClient({\n baseUrl: url,\n // Empty string disables the realtime socket — a short-lived CLI has no\n // use for it, and leaving it on opens a connection (and noisy errors)\n // on every invocation.\n websocketUrl: \"\",\n auth: {\n storage: createFileAuthStorage(url),\n persistSession: true,\n autoRefresh: false\n }\n });\n}\n\n/** Two minutes of head-room before a token is treated as expired. */\nconst EXPIRY_BUFFER_MS = 120_000;\n\n/**\n * Return an authenticated client for the resolved host, refreshing the access\n * token if it is close to expiry. Exits with a helpful message when there is no\n * usable session (never logged in, or the refresh token was revoked).\n */\nexport async function requireClient(rawArgs: string[]): Promise<{ client: CloudClient; url: string }> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n const session = client.auth.getSession();\n\n if (!session || !session.accessToken) {\n fail(\n `Not logged in to ${chalk.cyan(url)}.`,\n `Run ${chalk.bold(\"rebase cloud login\")} first.`\n );\n }\n\n if (session.expiresAt <= Date.now() + EXPIRY_BUFFER_MS) {\n try {\n await client.auth.refreshSession();\n } catch {\n fail(\n `Your session for ${chalk.cyan(url)} has expired.`,\n `Run ${chalk.bold(\"rebase cloud login\")} to sign in again.`\n );\n }\n }\n\n return { client,\nurl };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Tenant hostnames\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The base domain tenant projects are served at, as reported by the control\n * plane (`platform-config`, which derives it from the same TENANT_BASE_DOMAIN\n * the ingress and the console read — see saas/backend/src/utils/tenant-domain.ts).\n *\n * The CLI cannot know this value: it is per-deployment configuration (production\n * serves tenants at `apps.rebase.pro`, a dev control plane at `localhost`). It\n * used to be hardcoded to `rebase.pro`, so `cloud projects create` congratulated\n * the user with a URL that resolves nowhere near their app.\n *\n * Cached per host for the process: it is fixed for a control plane's lifetime,\n * and `projects list` formats one host per row off a single fetch.\n *\n * @returns the base domain, or `undefined` if the control plane doesn't serve\n * `platform-config` (an older deployment) or the request failed. A failure is\n * cached too — the caller renders a subdomain either way, and a short-lived\n * CLI should not retry once per row.\n */\nconst tenantBaseDomainCache = new Map<string, Promise<string | undefined>>();\n\nexport function fetchTenantBaseDomain(client: CloudClient, url: string): Promise<string | undefined> {\n let pending = tenantBaseDomainCache.get(url);\n if (!pending) {\n pending = client.functions\n .invoke<{ tenantBaseDomain?: string }>(\"platform-config\", undefined, { method: \"GET\" })\n .then((cfg) => cfg?.tenantBaseDomain?.trim() || undefined)\n .catch(() => undefined);\n tenantBaseDomainCache.set(url, pending);\n }\n return pending;\n}\n\n/**\n * Public host for a project — `<subdomain>.<base>`, or the bare subdomain when\n * the base domain is unknown.\n *\n * It deliberately never falls back to a guessed domain. The user copies this\n * string into a browser, so a plausible-but-wrong hostname is worse than an\n * obviously incomplete one: `acme.rebase.pro` looks reachable and isn't, while\n * `acme` reads as \"the subdomain is acme\" and prompts no wasted debugging.\n */\nexport function formatTenantHost(\n subdomain: string | undefined,\n baseDomain: string | undefined\n): string | undefined {\n if (!subdomain) return undefined;\n return baseDomain ? `${subdomain}.${baseDomain}` : subdomain;\n}\n\n/** The fields of a project row this module needs to render a host. */\nexport interface HostableProject {\n subdomain?: string;\n /** Resolved server-side; absent on control planes older than the host hook. */\n host?: string;\n}\n\n/**\n * The host to display for a project.\n *\n * Prefers `host` off the record: the control plane resolves it through the same\n * `tenantHost()` the ingress uses, so it accounts for the project's *cluster*\n * base domain. The CLI cannot compute that itself — `clusters` is admin-only\n * under RLS, so a normal user's token cannot read `baseDomain`, and a project on\n * a second cluster is served somewhere the platform default does not name.\n *\n * `baseDomain` (from `platform-config`) remains the fallback for a control plane\n * that predates the hook — right for the single-cluster case, which is every\n * project today.\n */\nexport function projectHost(\n project: HostableProject,\n baseDomain: string | undefined\n): string | undefined {\n return project.host || formatTenantHost(project.subdomain, baseDomain);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Project link file (.rebase/cloud.json)\n ═══════════════════════════════════════════════════════════════ */\n\nexport interface ProjectLink {\n url: string;\n projectId: string;\n /** The project's subdomain — the slug users see in console URLs and type into --project. */\n slug?: string;\n projectName?: string;\n orgId?: string;\n /**\n * Base URL of the project's own API.\n *\n * For a cloud project this is a convenience derived from the subdomain. For\n * a **self-hosted** project it is the entire link: there is no control plane\n * to look anything up in, so `projectId` is empty and this is what commands\n * resolve against.\n *\n * Keeping both kinds of link in one file is deliberate. A second link file\n * for self-hosting would fork every command that reads one, and the tooling\n * would drift into being cloud-only by accident.\n */\n apiUrl?: string;\n /**\n * How this checkout is linked. Absent means `cloud` — which is every link\n * written before this field existed.\n */\n mode?: \"cloud\" | \"direct\";\n}\n\nexport function readLink(cwd: string = process.cwd()): ProjectLink | null {\n try {\n return JSON.parse(fs.readFileSync(projectLinkPath(cwd), \"utf-8\")) as ProjectLink;\n } catch {\n return null;\n }\n}\n\nexport function writeLink(link: ProjectLink, cwd: string = process.cwd()): void {\n const file = projectLinkPath(cwd);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, JSON.stringify(link, null, 2));\n}\n\nexport function removeLink(cwd: string = process.cwd()): boolean {\n const file = projectLinkPath(cwd);\n if (fs.existsSync(file)) {\n fs.rmSync(file);\n return true;\n }\n return false;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * The raw project reference to operate on: explicit `--project` flag wins,\n * otherwise the linked project. Exits with guidance when neither is present.\n * The value is a slug (the project's subdomain, as shown in console URLs) or,\n * for old scripts and link files, a raw project UUID.\n */\nexport function requireProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n if (link?.projectId) return link.projectId;\n fail(\n \"No project specified and this directory is not linked.\",\n `Pass ${chalk.bold(\"--project <slug>\")} or run ${chalk.bold(\"rebase cloud link\")}.`\n );\n}\n\n/**\n * Resolve a project reference — slug or UUID — to the internal id the API\n * takes, or undefined when no such project is visible. Slugs cost one lookup;\n * UUIDs pass through untouched so linked directories and old scripts skip the\n * round-trip.\n */\nexport async function lookupProjectId(ref: string, client: CloudClient): Promise<string | undefined> {\n if (UUID_RE.test(ref)) return ref;\n const res = await client.data.collection(\"projects\").find({\n where: { subdomain: [\"==\", ref] },\n limit: 1\n });\n const row = res.data[0] as { id?: string | number } | undefined;\n return row?.id === undefined ? undefined : String(row.id);\n}\n\n/** Like `lookupProjectId`, but exits with guidance when the ref matches nothing. */\nexport async function resolveProjectRef(ref: string, client: CloudClient): Promise<string> {\n const id = await lookupProjectId(ref, client);\n if (id === undefined) {\n fail(\n `No project with slug ${chalk.bold(ref)}.`,\n `List yours with ${chalk.bold(\"rebase cloud projects\")}.`\n );\n }\n return id;\n}\n\n/** `requireProjectRef` + `resolveProjectRef` in one step. */\nexport async function requireProject(rawArgs: string[], client: CloudClient): Promise<string> {\n return resolveProjectRef(requireProjectRef(rawArgs), client);\n}\n\n/**\n * The project reference to SHOW: the slug the user typed or the linked slug.\n * Never resolves — for human output only. Old link files predate `slug` and\n * fall back to the stored id.\n */\nexport function displayProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n return link?.slug || link?.projectId || \"\";\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Machine-readable output mode\n ═══════════════════════════════════════════════════════════════\n\n Rebase is built for agents, and the CLI is their primary interface. An agent\n must never scrape a colorized table, so every cloud command can emit a single\n JSON value instead of human output.\n\n JSON mode is on when ANY of these hold:\n • `--json` was passed,\n • `REBASE_JSON=1` is set, or\n • stdout is not a TTY (piped/redirected — i.e. a program is reading it).\n\n In JSON mode a command prints exactly one JSON value to stdout and nothing\n else; errors print `{\"error\":{...}}` and exit non-zero. The mode is a\n process-global set once, at dispatch, by `initOutputMode` — every helper here\n (fail, reportError, emit) reads it so the whole family is consistent.\n*/\n\nlet JSON_MODE = false;\n\n/**\n * Resolve and latch the output mode for this invocation. Call once at the top of\n * `cloudCommand`, before anything can print or `fail`. Returns the resolved mode\n * (handy for tests, which otherwise leave it at its `false` default).\n */\nexport function initOutputMode(rawArgs: string[]): boolean {\n const parsed = arg({ \"--json\": Boolean }, { argv: rawArgs.slice(2), permissive: true });\n JSON_MODE =\n Boolean(parsed[\"--json\"]) ||\n process.env.REBASE_JSON === \"1\" ||\n process.stdout.isTTY !== true;\n return JSON_MODE;\n}\n\n/** Whether the current invocation is emitting machine-readable JSON. */\nexport function isJsonMode(): boolean {\n return JSON_MODE;\n}\n\n/** Force the mode (tests only — production latches it via `initOutputMode`). */\nexport function setJsonModeForTest(value: boolean): void {\n JSON_MODE = value;\n}\n\n/** Strip ANSI colour codes — JSON output must never carry terminal escapes. */\n// eslint-disable-next-line no-control-regex\nconst ANSI_RE = /\u001b\\[[0-9;]*m/g;\nfunction stripAnsi(s: string): string {\n return s.replace(ANSI_RE, \"\");\n}\n\n/**\n * Write one JSON value to stdout, followed by a newline.\n *\n * Indented, because the overwhelmingly common reader is a person or an agent\n * looking at a terminal — JSON mode is entered automatically whenever stdout is\n * not a TTY, so `rebase cloud deployments list` piped anywhere at all produced\n * a project's entire deployment history as one unwrapped line. `JSON.parse`\n * does not care about the whitespace; everything else does.\n */\nexport function printJson(value: unknown): void {\n process.stdout.write(JSON.stringify(value, null, 2) + \"\\n\");\n}\n\n/**\n * The one output primitive every new command uses: in JSON mode emit `json`\n * (and nothing else); otherwise run `human`. Keeping the two behind a single\n * call is what guarantees a command can never print a table AND a JSON blob.\n */\nexport function emit(human: () => void, json: unknown): void {\n if (JSON_MODE) printJson(json);\n else human();\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Output helpers\n ═══════════════════════════════════════════════════════════════ */\n\n/** Print an error (+ optional hint) and exit non-zero. Never returns. */\nexport function fail(message: string, hint?: string, code?: string): never {\n if (JSON_MODE) {\n printJson({ error: { message: stripAnsi(message), code: code ?? null, hint: hint ? stripAnsi(hint) : undefined } });\n process.exit(1);\n }\n console.error(\"\");\n console.error(chalk.red(` ✗ ${message}`));\n if (hint) console.error(chalk.gray(` ${hint}`));\n console.error(\"\");\n process.exit(1);\n}\n\n/**\n * Confirm a destructive/irreversible action, respecting non-interactive use.\n *\n * With `--yes`/`-y` it proceeds silently. In JSON mode or a non-TTY it REFUSES\n * to prompt — a prompt that can hang is a known repo landmine — and fails,\n * telling the caller to pass `--yes`. Only an interactive terminal gets a real\n * confirm prompt; declining there aborts cleanly (exit 0).\n */\nexport async function confirmDestructive(opts: { yes: boolean; prompt: string }): Promise<void> {\n if (opts.yes) return;\n if (JSON_MODE || process.stdin.isTTY !== true) {\n fail(\n \"This action is destructive and needs confirmation.\",\n `Re-run with ${chalk.bold(\"--yes\")} to proceed.`,\n \"confirmation_required\"\n );\n }\n const { confirmed } = (await inquirer.prompt([\n { type: \"confirm\", name: \"confirmed\", default: false, message: opts.prompt }\n ] as unknown as Parameters<typeof inquirer.prompt>[0])) as { confirmed: boolean };\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n process.exit(0);\n }\n}\n\n/**\n * Positional tokens after `rebase cloud` — `[group, action, arg1, …]`.\n *\n * Deliberately NOT `arg({}, { permissive: true })._`: in permissive mode `arg`\n * pushes UNKNOWN FLAGS onto `_` too, so `rollback --yes --json` would report\n * `--yes` as the deployment id. Operand extraction must see operands only, so\n * anything starting with `-` is dropped — the same filter the db backup handler\n * has always used.\n */\nexport function cloudPositionals(rawArgs: string[]): string[] {\n return rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"));\n}\n\nexport function success(message: string): void {\n console.log(\"\");\n console.log(chalk.bold.green(` ✓ ${message}`));\n console.log(\"\");\n}\n\n/** Colorize a deployment / resource status token. */\nexport function colorStatus(status: string | undefined): string {\n switch (status) {\n case \"active\":\n case \"success\":\n case \"connected\":\n return chalk.green(status);\n case \"deploying\":\n case \"provisioning\":\n case \"pending_billing\":\n case \"untested\":\n return chalk.yellow(status ?? \"\");\n case \"failed\":\n return chalk.red(status);\n case \"stopped\":\n return chalk.gray(status);\n default:\n return chalk.gray(status ?? \"unknown\");\n }\n}\n\n/**\n * Render a two-column key/value block with aligned keys. Empty rows are skipped\n * — including `null`, which the API sends for an unset column and which used to\n * print the literal string \"null\" (e.g. `Custom domain: null`).\n */\nexport function keyValues(rows: Array<[string, string | null | undefined]>): void {\n const width = Math.max(...rows.map(([k]) => k.length));\n for (const [k, v] of rows) {\n if (v === undefined || v === null || v === \"\") continue;\n console.log(` ${chalk.gray(`${k}:`.padEnd(width + 1))} ${v}`);\n }\n}\n\n/**\n * Surface an SDK/HTTP error consistently. The SDK throws RebaseApiError with\n * a `.status` and `.message`; anything else falls back to its string form.\n */\nexport function reportError(e: unknown, context: string): never {\n const err = e as { status?: number; message?: string; code?: string };\n if (JSON_MODE) {\n printJson({\n error: {\n message: err?.message ? stripAnsi(err.message) : String(e),\n code: err?.code ?? null,\n status: err?.status ?? null,\n context\n }\n });\n process.exit(1);\n }\n const status = err?.status ? ` (${err.status})` : \"\";\n fail(`${context}${status}: ${err?.message ?? String(e)}`);\n}\n\n/**\n * Open a URL in the user's default browser (best effort). Always prints the URL\n * first so it stays usable over SSH or when no browser is available.\n */\nexport function openUrl(target: string, label = \"Opening\"): void {\n console.log(\"\");\n console.log(` ${label} ${chalk.cyan(target)}`);\n console.log(\"\");\n const opener =\n process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n try {\n const child = spawn(opener, [target], {\n stdio: \"ignore\",\n detached: true,\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", () => {\n /* URL already printed for manual copy */\n });\n child.unref();\n } catch {\n /* URL already printed */\n }\n}\n","import arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport { promisify } from \"util\";\nimport { execa } from \"execa\";\nimport { cp } from \"fs/promises\";\nimport { fileURLToPath } from \"url\";\nimport crypto from \"crypto\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { resolveCloudUrl, writeLink } from \"./cloud/context\";\nimport type { PackageManager, PMCommands } from \"../utils/package-manager\";\n\nconst access = promisify(fs.access);\n\n\n// Resolve template path relative to this file\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction findParentDir(currentDir: string, targetName: string): string | null {\n const root = path.parse(currentDir).root;\n while (currentDir && currentDir !== root) {\n if (path.basename(currentDir) === targetName) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nconst cliRoot = findParentDir(__dirname, \"cli\");\n\nconst PROJECT_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;\n\n/** Returns an error message, or null when the name is a valid package name. */\nexport function validateProjectName(name: string): string | null {\n if (!name.trim()) return \"Project name is required\";\n if (!PROJECT_NAME_RE.test(name)) {\n return \"Project name must start with a lowercase letter or number and contain only lowercase letters, numbers, hyphens, dots, or underscores\";\n }\n return null;\n}\n\nexport type TemplatePreset = \"blog\" | \"ecommerce\" | \"blank\";\n\n/**\n * How much of Rebase to scaffold.\n *\n * `cms` is the full triad (config + backend + frontend). `baas` is the backend\n * alone, serving the database over REST with no collection files and no UI.\n */\n/**\n * `cms` scaffolds BaaS + the admin UI; `baas` scaffolds the API alone. The\n * values match `RebaseBackendConfig.mode`, which is what the generated backend\n * sets — the labels below are what users actually read.\n */\nexport type TemplateFlavor = \"cms\" | \"baas\";\n\nconst FLAVOR_CHOICES: Array<{ name: string; value: TemplateFlavor; short: string }> = [\n { name: \"BaaS + admin — API plus an admin UI, driven by collections you define (like Payload/Directus)\",\nvalue: \"cms\",\nshort: \"BaaS + admin\" },\n { name: \"BaaS only — headless API over your database. No collections, no UI (like Supabase)\",\nvalue: \"baas\",\nshort: \"BaaS only\" }\n];\n\nconst PRESET_CHOICES: Array<{ name: string; value: TemplatePreset; short: string }> = [\n { name: \"Blog — Posts, Authors, Tags (with markdown editor)\",\nvalue: \"blog\",\nshort: \"Blog\" },\n { name: \"E-commerce — Products, Categories, Orders\",\nvalue: \"ecommerce\",\nshort: \"E-commerce\" },\n { name: \"Blank — Empty project, just authentication\",\nvalue: \"blank\",\nshort: \"Blank\" }\n];\n\nexport interface InitOptions {\n projectName: string;\n git: boolean;\n installDeps: boolean;\n targetDirectory: string;\n templateDirectory: string;\n databaseUrl?: string;\n introspect?: boolean;\n /** Starter template preset. */\n preset: TemplatePreset;\n /** Whether `preset` came from an explicit --template rather than the default. */\n explicitPreset?: boolean;\n /** Which parts of Rebase to scaffold. */\n flavor: TemplateFlavor;\n /** Detected package manager (pnpm or npm). */\n pm: PackageManager;\n /** Command helpers for the detected PM. */\n pmCommands: PMCommands;\n /** Cloud project slug (its subdomain) to link the scaffold to. */\n cloudProject?: string;\n /** One-time setup key that authenticates the cloud link. */\n setupKey?: string;\n /** Control-plane URL the setup key is redeemed against. */\n cloudUrl?: string;\n}\n\nexport interface BuildQuestionsParams {\n nameArg?: string;\n templateArg?: TemplatePreset;\n flavorArg?: TemplateFlavor;\n hasGitFlag: boolean;\n hasInstallFlag: boolean;\n pm: PackageManager;\n}\n\n/**\n * Builds the interactive prompt questions for `rebase init`.\n * Exported for testability — all prompt `type` values must match\n * types registered by the installed version of inquirer.\n */\nexport function buildInitQuestions(params: BuildQuestionsParams): Record<string, unknown>[] {\n const { nameArg, templateArg, flavorArg, hasGitFlag, hasInstallFlag, pm } = params;\n const questions: Record<string, unknown>[] = [];\n\n if (!nameArg) {\n questions.push({\n type: \"input\",\n name: \"projectName\",\n message: \"Project name:\",\n default: \"my-rebase-app\",\n validate: (input: string) => validateProjectName(input) ?? true\n });\n }\n\n if (!flavorArg) {\n questions.push({\n type: \"select\",\n name: \"flavor\",\n message: \"What do you want to build?\",\n choices: FLAVOR_CHOICES,\n default: \"cms\"\n });\n }\n\n if (!templateArg) {\n questions.push({\n type: \"select\",\n name: \"preset\",\n message: \"Choose a starter template:\",\n choices: PRESET_CHOICES,\n default: \"blog\",\n // BaaS has no collection files, so a collections preset is moot.\n when: (answers: Record<string, unknown>) => (flavorArg ?? answers.flavor) !== \"baas\"\n });\n }\n\n if (!hasGitFlag) {\n questions.push({\n type: \"confirm\",\n name: \"git\",\n message: \"Initialize a git repository?\",\n default: true\n });\n }\n\n if (!hasInstallFlag) {\n questions.push({\n type: \"confirm\",\n name: \"installDeps\",\n message: `Install dependencies with ${pm}?`,\n default: true\n });\n }\n\n questions.push({\n type: \"input\",\n name: \"databaseUrl\",\n message: \"Enter your PostgreSQL database connection string (leave blank to use a local default):\",\n default: \"\",\n validate: (input: string) => {\n if (input.trim() && /[\\r\\n]/.test(input)) {\n return \"Database URL cannot contain newline characters.\";\n }\n return true;\n }\n });\n\n questions.push({\n type: \"confirm\",\n name: \"introspect\",\n message: \"Would you like to introspect this database to automatically generate collections?\",\n default: true,\n when: (answers: Record<string, unknown>) => !!(answers.databaseUrl as string)?.trim()\n });\n\n return questions;\n}\n\n/**\n * The `cd` a user must type to enter the new project.\n *\n * Not the project's basename: `init apps/my-app` has to say `cd apps/my-app`,\n * and `init .` returns \"\" because they are already in the project.\n */\nexport function formatCdTarget(cwd: string, targetDirectory: string): string {\n return path.relative(cwd, targetDirectory);\n}\n\n/** Help for `rebase init` — the flags were previously only discoverable by\n * triggering the non-TTY error. */\nexport function printInitHelp(): void {\n console.log(`\n${chalk.bold(\"rebase init\")} — Create a new Rebase project\n\n${chalk.bold(\"Usage\")}\n rebase init ${chalk.blue(\"[name]\")} [options]\n\n ${chalk.gray(\"The name may be a nested path (apps/my-app) or \\\".\\\" for the current directory.\")}\n ${chalk.gray(\"Defaults to \\\"my-rebase-app\\\" when omitted with --yes.\")}\n\n${chalk.bold(\"Options\")}\n ${chalk.blue(\"-t, --template\")} ${chalk.gray(\"<preset>\")} blog | ecommerce | blank ${chalk.gray(\"(default: blog)\")}\n ${chalk.blue(\"-f, --flavor\")} ${chalk.gray(\"<flavor>\")} cms | baas ${chalk.gray(\"(default: cms)\")}\n ${chalk.blue(\"-y, --yes\")} Accept defaults, never prompt ${chalk.gray(\"(required for CI / non-TTY)\")}\n ${chalk.blue(\"-i, --install\")} Install dependencies after scaffolding\n ${chalk.blue(\"-g, --git\")} Initialize a git repository and make an initial commit\n ${chalk.blue(\"--database-url\")} ${chalk.gray(\"<url>\")} Use an existing database instead of the generated one\n ${chalk.blue(\"--introspect\")} Generate collections from that database ${chalk.gray(\"(implies --template blank; needs --install)\")}\n ${chalk.blue(\"--project\")} ${chalk.gray(\"<slug>\")} Link the scaffold to a Rebase Cloud project\n ${chalk.blue(\"--setup-key\")} ${chalk.gray(\"<key>\")} One-time key authenticating the cloud link ${chalk.gray(\"(use with --project)\")}\n\n${chalk.bold(\"Flavors\")}\n ${chalk.blue(\"cms\")} BaaS + admin UI, driven by collections you define ${chalk.gray(\"(like Payload/Directus)\")}\n ${chalk.blue(\"baas\")} Headless API over your database — no collections, no UI ${chalk.gray(\"(like Supabase)\")}\n ${chalk.gray(\"--template has no effect on this flavor.\")}\n\n${chalk.bold(\"Examples\")}\n ${chalk.gray(\"$\")} rebase init my-shop --template ecommerce --install\n ${chalk.gray(\"$\")} rebase init my-api --flavor baas --yes\n ${chalk.gray(\"$\")} rebase init . --yes --git\n`);\n}\n\nexport async function createRebaseApp(rawArgs: string[]) {\n if (rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n printInitHelp();\n return;\n }\n\n console.log(`\n${chalk.bold(\"Rebase\")} — Create a new project 🚀\n`);\n\n const pm = detectPackageManager();\n const options = await promptForOptions(rawArgs, pm);\n await createProject(options);\n}\n\nasync function promptForOptions(rawArgs: string[], pm: PackageManager): Promise<InitOptions> {\n const args = arg(\n {\n \"--git\": Boolean,\n \"--install\": Boolean,\n \"--database-url\": String,\n \"--introspect\": Boolean,\n \"--template\": String,\n \"--flavor\": String,\n \"--project\": String,\n \"--setup-key\": String,\n \"--yes\": Boolean,\n \"-g\": \"--git\",\n \"-i\": \"--install\",\n \"-t\": \"--template\",\n \"-f\": \"--flavor\",\n \"-y\": \"--yes\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node\", \"rebase\", \"init\"\n permissive: true\n }\n );\n\n // The first positional arg after \"init\" is the project name\n const nameArg = args._[0];\n const isNonInteractive = args[\"--yes\"] || false;\n\n // The interactive prompt validates typed names; a name passed as an\n // argument must pass the same check or it becomes an invalid package.json\n // \"name\" that only fails later, at install time. Validate the basename so\n // nested paths (\"apps/my-app\") and \".\" still work.\n if (nameArg) {\n const resolvedName = path.basename(path.resolve(process.cwd(), nameArg));\n const nameError = validateProjectName(resolvedName);\n if (nameError) {\n console.error(chalk.red(`Invalid project name \"${resolvedName}\": ${nameError}`));\n process.exit(1);\n }\n }\n\n const templateArg = args[\"--template\"] as TemplatePreset | undefined;\n if (templateArg && !PRESET_CHOICES.some(p => p.value === templateArg)) {\n console.error(chalk.red(`Unknown template \"${templateArg}\". Available: ${PRESET_CHOICES.map(p => p.value).join(\", \")}`));\n process.exit(1);\n }\n\n const flavorArg = args[\"--flavor\"] as TemplateFlavor | undefined;\n if (flavorArg && !FLAVOR_CHOICES.some(f => f.value === flavorArg)) {\n console.error(chalk.red(`Unknown flavor \"${flavorArg}\". Available: ${FLAVOR_CHOICES.map(f => f.value).join(\", \")}`));\n process.exit(1);\n }\n\n if (isNonInteractive) {\n const projectName = nameArg || \"my-rebase-app\";\n const targetDirectory = path.resolve(process.cwd(), projectName);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName: path.basename(targetDirectory),\n git: args[\"--git\"] ?? false,\n installDeps: args[\"--install\"] ?? false,\n targetDirectory,\n templateDirectory,\n databaseUrl: args[\"--database-url\"] || undefined,\n introspect: args[\"--introspect\"] || false,\n preset: templateArg || \"blog\",\n explicitPreset: !!templateArg,\n flavor: flavorArg || \"cms\",\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n }\n\n // A non-interactive stdin (CI, a pipe, no TTY) can't answer prompts:\n // inquirer either blocks forever waiting for input or aborts with a raw\n // ExitPromptError stack trace. Fail fast with actionable guidance instead.\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"Cannot prompt: this is a non-interactive terminal (no TTY).\"));\n console.error(chalk.yellow(\" Re-run with --yes to accept defaults, passing any choices as flags, e.g.:\"));\n console.error(chalk.yellow(` rebase init ${nameArg || \"my-app\"} --yes --template blog --flavor cms`));\n console.error(chalk.gray(\" Options: --template <blog|ecommerce|blank> --flavor <cms|baas> --database-url <url> --install --git\"));\n process.exit(1);\n }\n\n const questions = buildInitQuestions({\n nameArg,\n templateArg,\n flavorArg,\n hasGitFlag: !!args[\"--git\"],\n hasInstallFlag: !!args[\"--install\"],\n pm\n });\n\n\n const answers = await inquirer.prompt(questions as unknown as Parameters<typeof inquirer.prompt>[0]);\n\n const targetDirectory = path.resolve(process.cwd(), nameArg || answers.projectName);\n const projectName = path.basename(targetDirectory);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName,\n git: args[\"--git\"] || answers.git || false,\n installDeps: args[\"--install\"] || answers.installDeps || false,\n targetDirectory,\n templateDirectory,\n databaseUrl: (answers.databaseUrl as string)?.trim() || undefined,\n introspect: answers.introspect || false,\n preset: templateArg || (answers.preset as TemplatePreset) || \"blog\",\n // Only a flag is \"explicit\" here: the interactive path never asks for a\n // preset once baas is chosen, so it can't produce a conflicting answer.\n explicitPreset: !!templateArg,\n flavor: flavorArg || (answers.flavor as TemplateFlavor) || \"cms\",\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n}\n\n/**\n * Redeem the one-time setup key from the console's setup page and write the\n * `.rebase/cloud.json` link into the scaffold, so `rebase cloud deploy` etc.\n * work in the new directory with no further flags. `--project` carries the\n * project's slug (its subdomain, as shown in console URLs); the control plane\n * also accepts a raw id for old copies of the command.\n *\n * Best-effort by design: a failed link must never fail the scaffold, so every\n * exit path other than success is a warning plus instructions to link later.\n */\nasync function linkScaffoldToCloud(options: InitOptions): Promise<void> {\n if (!options.cloudProject && !options.setupKey) return;\n\n const linkLater = `Link it later with ${chalk.bold(\"rebase cloud login\")} then ${chalk.bold(\"rebase cloud link\")}.`;\n if (!options.cloudProject || !options.setupKey) {\n console.warn(chalk.yellow(\" --project and --setup-key go together; skipping the cloud link.\"));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n\n try {\n const res = await fetch(`${options.cloudUrl}/api/functions/setup-key/validate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ projectId: options.cloudProject,\nsetupKey: options.setupKey })\n });\n const body = (await res.json().catch(() => ({}))) as {\n error?: { message?: string };\n project?: { id?: string | number; subdomain?: string; name?: string };\n };\n if (!res.ok || body.project?.id === undefined) {\n console.warn(chalk.yellow(` Could not verify the setup key: ${body.error?.message || res.statusText}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n writeLink(\n {\n url: String(options.cloudUrl),\n projectId: String(body.project.id),\n slug: body.project.subdomain,\n projectName: body.project.name\n },\n options.targetDirectory\n );\n console.log(\"\");\n console.log(` ${chalk.green(\"✓\")} Linked to cloud project ${chalk.bold(body.project.subdomain ?? options.cloudProject)}`);\n } catch (e) {\n console.warn(chalk.yellow(` Could not reach the control plane: ${e instanceof Error ? e.message : String(e)}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n }\n}\n\nasync function createProject(options: InitOptions) {\n // Check if directory already exists and is not empty\n if (fs.existsSync(options.targetDirectory)) {\n if (fs.readdirSync(options.targetDirectory).length !== 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} Directory \"${options.projectName}\" already exists and is not empty`);\n process.exit(1);\n }\n } else {\n fs.mkdirSync(options.targetDirectory, { recursive: true });\n }\n\n // Verify template exists\n try {\n await access(options.templateDirectory, fs.constants.R_OK);\n } catch {\n console.error(`${chalk.red.bold(\"ERROR\")} Template not found at ${options.templateDirectory}`);\n process.exit(1);\n }\n\n // Copy template files\n console.log(chalk.gray(\" Copying project files...\"));\n try {\n await cp(options.templateDirectory, options.targetDirectory, {\n recursive: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n // Skip node_modules and .DS_Store\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n } catch (err: unknown) {\n console.error(`${chalk.red.bold(\"ERROR\")} Failed to copy template files: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n // npm/pnpm always strip files named .gitignore and .npmrc from published\n // tarballs, so the template ships them un-dotted and we restore the real\n // names here.\n for (const [from, to] of [[\"gitignore\", \".gitignore\"], [\"npmrc\", \".npmrc\"]] as const) {\n const shipped = path.join(options.targetDirectory, from);\n if (fs.existsSync(shipped)) {\n fs.renameSync(shipped, path.join(options.targetDirectory, to));\n }\n }\n\n // Apply the selected template preset (swap collection files)\n if (options.flavor === \"baas\" && options.explicitPreset) {\n // baas has no collections, so there is nothing for a preset to swap.\n // Say so rather than accepting the flag and silently dropping it.\n console.log(chalk.yellow(` Ignoring --template ${options.preset}: the baas flavor has no collections.`));\n }\n if (options.flavor !== \"baas\") {\n // When introspecting, the database is the source of truth: start from\n // the blank preset so example collections never register on top of\n // tables the database doesn't have.\n if (options.introspect && options.preset !== \"blank\") {\n console.log(chalk.gray(\" Using the blank template: collections will come from your database.\"));\n }\n await applyPreset(options.targetDirectory, options.introspect ? \"blank\" : options.preset);\n }\n\n // Reduce the project to the selected flavor\n await applyFlavor(options.targetDirectory, options.flavor);\n\n // Replace placeholder project name in package.json files\n await replacePlaceholders(options);\n\n // Rename .env.example to .env if it exists and randomize secrets\n await configureEnvFile(options.targetDirectory, options.databaseUrl);\n\n // Initialize git\n if (options.git) {\n console.log(chalk.gray(\" Initializing git repository...\"));\n try {\n await execa(\"git\", [\"init\"], { cwd: options.targetDirectory });\n // Name the branch `main` rather than inheriting whatever\n // `init.defaultBranch` is (often still `master`). `git init -b` would\n // be the obvious way, but it needs git >= 2.28; rewriting HEAD works\n // on every version and is safe before the first commit.\n try {\n await execa(\"git\", [\"symbolic-ref\", \"HEAD\", \"refs/heads/main\"], { cwd: options.targetDirectory });\n } catch {\n // Leave the default branch name; not worth failing the scaffold.\n }\n // Leaving the tree uncommitted makes the very first `git diff`\n // useless and hides the scaffold in a wall of untracked files.\n // .gitignore is already in place, so .env is never committed.\n await execa(\"git\", [\"add\", \"-A\"], { cwd: options.targetDirectory });\n // A machine with no user.email configured cannot commit at all.\n // Supply an identity only in that case, so a configured user still\n // authors their own initial commit.\n let identity: Record<string, string> = {};\n try {\n await execa(\"git\", [\"config\", \"user.email\"], { cwd: options.targetDirectory });\n } catch {\n identity = {\n GIT_AUTHOR_NAME: \"Rebase\", GIT_AUTHOR_EMAIL: \"noreply@rebase.pro\",\n GIT_COMMITTER_NAME: \"Rebase\", GIT_COMMITTER_EMAIL: \"noreply@rebase.pro\"\n };\n }\n await execa(\"git\", [\"commit\", \"-m\", \"Initial commit from Rebase\"], {\n cwd: options.targetDirectory,\n env: identity\n });\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to initialize git repository\"));\n }\n }\n\n const { pm, pmCommands } = options;\n const installCmd = pmCommands.install;\n const execCmd = pmCommands.exec(\"rebase\", [\"schema\", \"introspect\", \"--force\"]);\n const generateCmd = pmCommands.exec(\"rebase\", [\"schema\", \"generate\", \"--collections\", \"../config/collections\"]);\n\n if (options.installDeps) {\n console.log(\"\");\n console.log(chalk.gray(` Installing dependencies with ${pm}...`));\n console.log(\"\");\n try {\n await execa(installCmd[0], installCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n } catch {\n console.warn(chalk.yellow(` Warning: Failed to install dependencies. You may need to run \\`${installCmd.join(\" \")}\\` manually.`));\n }\n }\n\n // Whether introspection actually ran and produced collections. The next\n // steps below report what really happened, so a skipped or failed\n // introspection is never announced as a success.\n let introspected = false;\n\n if (options.introspect) {\n console.log(\"\");\n if (options.installDeps) {\n console.log(chalk.gray(\" Introspecting database and generating collections...\"));\n console.log(\"\");\n try {\n // --force overwrites template example collections with real ones\n await execa(execCmd[0], execCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n // The template ships a schema.generated.ts for the example blog\n // collections; regenerate it from the introspected collections or\n // the backend serves a schema that doesn't match the database.\n await execa(generateCmd[0], generateCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n console.log(chalk.green(\" Database successfully introspected!\"));\n introspected = true;\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to introspect database automatically.\"));\n console.warn(chalk.yellow(` You can run \\`${execCmd.join(\" \")}\\` then \\`${generateCmd.join(\" \")}\\` manually after setup.`));\n }\n } else {\n console.warn(chalk.yellow(\" Skipping introspection because dependencies were not installed.\"));\n console.warn(chalk.yellow(` Run \\`${installCmd.join(\" \")}\\` then \\`${execCmd.join(\" \")}\\` manually.`));\n }\n }\n\n await linkScaffoldToCloud(options);\n\n // Success message\n console.log(\"\");\n console.log(`${chalk.green.bold(\"✓\")} Project ${chalk.bold(options.projectName)} created successfully!`);\n console.log(\"\");\n console.log(chalk.bold(\"Next steps:\"));\n console.log(\"\");\n const runDev = pmCommands.run(\"dev\");\n const runDbPush = pmCommands.run(\"db:push\");\n const isBaas = options.flavor === \"baas\";\n // The path the user has to type, not the project's basename: `init\n // apps/my-app` must say `cd apps/my-app`, and `init .` needs no cd at all\n // because they are already standing in the project.\n const cdTarget = formatCdTarget(process.cwd(), options.targetDirectory);\n if (cdTarget) {\n console.log(` ${chalk.cyan(\"cd\")} ${cdTarget}`);\n }\n if (!options.installDeps) {\n console.log(` ${chalk.cyan(installCmd.join(\" \"))}`);\n }\n console.log(\"\");\n\n if (options.databaseUrl) {\n if (introspected) {\n console.log(chalk.gray(\" # Database has been introspected & collections generated!\"));\n console.log(chalk.gray(\" # Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else if (options.introspect) {\n // Introspection was requested but did not run. Point at the steps\n // that finish the job rather than claiming collections exist.\n console.log(chalk.gray(\" # Introspection did not run — finish it with:\"));\n console.log(` ${chalk.cyan(execCmd.join(\" \"))}`);\n console.log(` ${chalk.cyan(generateCmd.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # Then start the development server:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # Your custom database is configured in .env.\"));\n console.log(chalk.gray(\" # If the database is empty, push the Rebase schema to initialize it:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # Then start the development server:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n } else if (isBaas) {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Create your tables (migrations, SQL, any tool you like).\"));\n console.log(chalk.gray(\" # A table is served once it has an authorization model, i.e.\"));\n console.log(chalk.gray(\" # row-level security enabled plus at least one policy:\"));\n console.log(` ${chalk.cyan(\"ALTER TABLE your_table ENABLE ROW LEVEL SECURITY;\")}`);\n console.log(chalk.gray(\" # The API logs any table it skips, and why.\"));\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the API — every protected table is served automatically:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Push the Rebase schema to initialize database tables:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n\n console.log(\"\");\n console.log(isBaas\n ? chalk.gray(\"This starts a headless API (Hono + PostgreSQL). There are no collection files: \")\n + chalk.gray(\"the API is derived from your database schema. Once it serves a table, docs are at /api/swagger.\")\n : chalk.gray(\"This starts both the backend (Hono + PostgreSQL)\")\n + chalk.gray(\" and the frontend (Vite + React) concurrently.\"));\n console.log(\"\");\n console.log(chalk.gray(\"Docs: https://rebase.pro/docs\"));\n console.log(chalk.gray(\"GitHub: https://github.com/rebasepro/rebase\"));\n console.log(\"\");\n console.log(chalk.bold(\"🤖 AI Agent Skills\"));\n console.log(\"\");\n console.log(chalk.gray(\" Install Rebase agent skills for your AI coding assistant:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(\"rebase skills install\")} ${chalk.gray(\"or\")} ${chalk.cyan(pmCommands.run(\"skills:install\").join(\" \"))}`);\n console.log(\"\");\n}\n\n/**\n * Apply a template preset by replacing the default collection files.\n *\n * The template ships with blog collections at the top level and\n * preset alternatives under `config/collections/presets/<name>/`.\n * This function swaps the active collection files and removes the\n * presets directory so the final project is clean.\n */\n/**\n * Reduce the scaffolded project to the chosen flavor.\n *\n * The base template is the full CMS triad. `baas` drops the frontend and the\n * collections config entirely — there is nothing to define, since the server\n * derives its API from the database — and overlays the files that differ.\n */\nasync function applyFlavor(targetDirectory: string, flavor: TemplateFlavor): Promise<void> {\n if (flavor !== \"baas\") return;\n\n for (const dir of [\"frontend\", \"config\"]) {\n fs.rmSync(path.join(targetDirectory, dir), { recursive: true, force: true });\n }\n // Generated from collection files in cms mode; baas reads the live schema.\n fs.rmSync(path.join(targetDirectory, \"backend\", \"src\", \"schema.generated.ts\"), { force: true });\n\n const overlayDir = path.resolve(cliRoot!, \"templates\", \"overlays\", \"baas\");\n if (!fs.existsSync(overlayDir)) {\n console.error(`${chalk.red.bold(\"ERROR\")} BaaS template overlay not found at ${overlayDir}`);\n process.exit(1);\n }\n\n await cp(overlayDir, targetDirectory, {\n recursive: true,\n force: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n}\n\nasync function applyPreset(targetDirectory: string, preset: TemplatePreset): Promise<void> {\n const collectionsDir = path.join(targetDirectory, \"config\", \"collections\");\n const presetsDir = path.join(collectionsDir, \"presets\");\n\n if (preset !== \"blog\") {\n const presetDir = path.join(presetsDir, preset);\n if (!fs.existsSync(presetDir)) {\n console.warn(chalk.yellow(` Warning: Preset \"${preset}\" not found, falling back to blog template.`));\n cleanupPresets(presetsDir);\n return;\n }\n\n // Remove the default blog collection files (keep users.ts — it's shared)\n const blogFiles = [\"posts.ts\", \"authors.ts\", \"tags.ts\", \"index.ts\"];\n for (const file of blogFiles) {\n const filePath = path.join(collectionsDir, file);\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n }\n }\n\n // Copy preset files into the collections directory\n const presetFiles = fs.readdirSync(presetDir).filter(f => f.endsWith(\".ts\"));\n for (const file of presetFiles) {\n fs.copyFileSync(\n path.join(presetDir, file),\n path.join(collectionsDir, file)\n );\n }\n }\n\n // Always clean up the presets directory — it shouldn't ship with the final project\n cleanupPresets(presetsDir);\n}\n\nfunction cleanupPresets(presetsDir: string): void {\n if (fs.existsSync(presetsDir)) {\n fs.rmSync(presetsDir, { recursive: true,\nforce: true });\n }\n}\n\nasync function replacePlaceholders(options: InitOptions) {\n const filesToProcess = [\n \"package.json\",\n \"frontend/package.json\",\n \"backend/package.json\",\n \"config/package.json\",\n \"frontend/index.html\",\n \"pnpm-workspace.yaml\",\n \"README.md\"\n ];\n\n const packageJsonPath = path.resolve(cliRoot!, \"package.json\");\n let cliVersion = \"latest\";\n if (fs.existsSync(packageJsonPath)) {\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\"));\n cliVersion = pkg.version || \"latest\";\n }\n\n const versionCache = new Map<string, string>();\n /** Packages with no release matching the CLI's own version. */\n const unreleased = new Map<string, string>();\n\n // Use npm view for registry queries — it's universal and works regardless of PM\n const viewBin = \"npm\";\n\n const getPackageVersion = async (pkgName: string) => {\n if (versionCache.has(pkgName)) return versionCache.get(pkgName)!;\n if (process.env.REBASE_E2E === \"true\") {\n versionCache.set(pkgName, cliVersion);\n return cliVersion;\n }\n let versionToUse = cliVersion;\n try {\n // First try to check if the specific cliVersion exists for this package\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${cliVersion}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // If specific version doesn't exist, try the matching tag (canary or latest)\n const tag = cliVersion.includes(\"canary\") ? \"canary\" : \"latest\";\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${tag}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // Fallback to absolute latest\n const { stdout } = await execa(viewBin, [\"view\", pkgName, \"version\"]);\n versionToUse = stdout.trim() || \"latest\";\n } catch {\n versionToUse = \"latest\";\n }\n }\n\n // The fallbacks above answer \"what can I install?\", not \"what matches\n // this CLI?\". When a package has no release at the CLI's own version,\n // they quietly pin whatever the registry last tagged — which can be a\n // prerelease from an entirely different era of the framework. Record\n // it so we can refuse rather than scaffold a mixed-version app.\n if (versionToUse !== cliVersion) {\n unreleased.set(pkgName, versionToUse);\n }\n }\n versionCache.set(pkgName, versionToUse);\n return versionToUse;\n };\n\n // First, find all unique @rebasepro packages across all files to process in parallel\n const allPackages = new Set<string>();\n const fileContents = new Map<string, string>();\n\n for (const file of filesToProcess) {\n const fullPath = path.resolve(options.targetDirectory, file);\n if (!fs.existsSync(fullPath)) continue;\n const content = fs.readFileSync(fullPath, \"utf-8\");\n fileContents.set(fullPath, content);\n\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n allPackages.add(match[1]);\n }\n }\n\n console.log(chalk.gray(\" Resolving package versions...\"));\n\n // Resolve all versions in parallel\n await Promise.all(Array.from(allPackages).map(getPackageVersion));\n\n // A stable CLI whose packages resolve only to a prerelease means those\n // packages were never released at this version — the usual cause is a rename\n // that left the new name published on the canary tag alone. Scaffolding\n // anyway mixes eras (say @rebasepro/types@0.9.0 beside a 0.0.1 canary) and\n // hands the user an app that fails at install or, worse, at runtime. Neither\n // failure names this as the cause, so stop here and say it plainly.\n const cliIsStable = cliVersion !== \"latest\" && !cliVersion.includes(\"-\");\n const prereleasePins = [...unreleased].filter(([, version]) => version === \"latest\" || version.includes(\"-\"));\n\n if (cliIsStable && prereleasePins.length > 0) {\n const lines = prereleasePins.map(([name, version]) => ` ${name} → ${version}`).join(\"\\n\");\n throw new Error(\n `Rebase ${cliVersion} is not fully published to npm.\\n\\n` +\n `These packages have no ${cliVersion} release, so the newest thing on the\\n` +\n `registry is a prerelease:\\n\\n${lines}\\n\\n` +\n `Scaffolding would pin those alongside the ${cliVersion} packages and produce\\n` +\n `an app that cannot install or run. That is a release gap in Rebase itself —\\n` +\n `not a problem with your machine, your network, or your package manager.\\n\\n` +\n `Stopped before writing dependency versions or installing anything. The\\n` +\n `project directory ${path.basename(options.targetDirectory)}/ was created and is safe to delete.\\n` +\n `Please report this with the list above.`\n );\n }\n\n // Perform replacements\n for (const [fullPath, originalContent] of fileContents.entries()) {\n let content = originalContent.replace(/\\{\\{PROJECT_NAME\\}\\}/g, options.projectName);\n\n // Replace workspace:* with the dynamically resolved version\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n const pkgName = match[1];\n const resolvedVersion = versionCache.get(pkgName) || \"latest\";\n content = content.replace(new RegExp(`\"${pkgName}\":\\\\s*\"workspace:\\\\*\"`, \"g\"), `\"${pkgName}\": \"${resolvedVersion}\"`);\n }\n\n fs.writeFileSync(fullPath, content, \"utf-8\");\n }\n}\n\n\nasync function isPortAvailable(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once(\"error\", () => {\n resolve(false);\n });\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n server.listen(port);\n });\n}\n\nasync function findAvailablePort(startPort: number): Promise<number> {\n let port = startPort;\n while (!(await isPortAvailable(port))) {\n port++;\n }\n return port;\n}\n\nexport async function configureEnvFile(targetDirectory: string, databaseUrl?: string) {\n const envExamplePath = path.join(targetDirectory, \".env.example\");\n const envPath = path.join(targetDirectory, \".env\");\n if (fs.existsSync(envExamplePath) && !fs.existsSync(envPath)) {\n // Copy .env.example → .env (keep .env.example as a reference in the repo)\n fs.copyFileSync(envExamplePath, envPath);\n\n // Generate secure random strings\n const jwtSecret = crypto.randomBytes(32).toString(\"hex\");\n const dbPassword = crypto.randomBytes(16).toString(\"hex\");\n const serviceKey = crypto.randomBytes(48).toString(\"base64\");\n\n let envContent = fs.readFileSync(envPath, \"utf-8\");\n\n envContent = envContent.replace(\n /^JWT_SECRET=.*$/m,\n `JWT_SECRET=${jwtSecret}`\n );\n\n // Ships commented out in .env.example. Left unset, the server generates\n // one on every boot and silently invalidates the previous run's tokens,\n // so write a stable one now rather than making each restart a logout.\n envContent = envContent.replace(\n /^#\\s*REBASE_SERVICE_KEY=.*$/m,\n `REBASE_SERVICE_KEY=${serviceKey}`\n );\n\n if (databaseUrl) {\n if (/[\\r\\n]/.test(databaseUrl)) {\n throw new Error(\"Invalid DATABASE_URL: multiline values are not allowed.\");\n }\n // DATABASE_PASSWORD is still written even though the URL points\n // elsewhere: docker-compose.yml interpolates it into both\n // POSTGRES_PASSWORD and the backend's own DATABASE_URL, defaulting\n // to `${DATABASE_PASSWORD:-changeme}`. Omitting it here shipped a\n // compose stack whose database password was literally \"changeme\",\n // on a service that publishes a host port by default.\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n `DATABASE_URL=${databaseUrl}\\nDATABASE_PASSWORD=${dbPassword}`\n );\n } else {\n const dbPort = await findAvailablePort(5432);\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n // sslmode=disable: the paired docker-compose Postgres has no TLS,\n // and Go-based tooling (atlas, via `rebase db push`) defaults to\n // requiring SSL when the URL doesn't say otherwise.\n `DATABASE_URL=postgresql://rebase:${dbPassword}@localhost:${dbPort}/rebase?options=-c%20search_path=public&sslmode=disable\\nDATABASE_PASSWORD=${dbPassword}`\n );\n\n // Also update docker-compose.yml with the dynamic host port if it has the default 5432 port mapping\n const dockerComposePath = path.join(targetDirectory, \"docker-compose.yml\");\n if (fs.existsSync(dockerComposePath)) {\n let dockerComposeContent = fs.readFileSync(dockerComposePath, \"utf-8\");\n dockerComposeContent = dockerComposeContent.replace(\n /-\\s*\"5432:5432\"/g,\n `- \"${dbPort}:5432\"`\n );\n fs.writeFileSync(dockerComposePath, dockerComposeContent, \"utf-8\");\n }\n }\n\n fs.writeFileSync(envPath, envContent, \"utf-8\");\n }\n}\n","/**\n * CLI command: generate-sdk\n *\n * Reads collection definitions from a specified directory (default: ./config/collections),\n * generates a typed TypeScript SDK, and writes it to the output directory (default: ./generated/sdk).\n *\n * Uses jiti for dynamic TypeScript import of collection files.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig, computeSchemaVersion, deserializeCollections } from \"@rebasepro/types\";\nimport { generateSDK, GeneratedFile } from \"@rebasepro/codegen\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { findProjectRoot } from \"../utils/project\";\nimport { readLink } from \"./cloud/context\";\n\ninterface GenerateSDKArgs {\n collectionsDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no collections — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n help?: boolean;\n}\n\n/**\n * Dynamically load collection definitions from a directory.\n *\n * Expects the directory to have an index.ts/index.js that exports a default\n * array of CollectionConfig objects (matching the app/config/collections pattern).\n */\nasync function loadCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n const absDir = path.resolve(collectionsDir);\n\n if (!fs.existsSync(absDir)) {\n throw new Error(`Collections directory not found: ${absDir}`);\n }\n\n // Try to import the index file using jiti (supports TypeScript natively)\n let jiti: (id: string, userOptions?: Record<string, unknown>) => (modulePath: string) => Record<string, unknown>;\n try {\n const jitiModule = await import(\"jiti\");\n jiti = (jitiModule.default || jitiModule) as typeof jiti;\n } catch {\n const installCmd = [...getPMCommands(detectPackageManager()).install, \"-D\", \"jiti\"].join(\" \");\n throw new Error(\n `Could not load 'jiti'. Install it with: ${installCmd}\\n` +\n \"jiti is required to dynamically import TypeScript collection definitions.\"\n );\n }\n\n const jitiInstance = jiti(absDir, {\n interopDefault: true,\n esmResolve: true\n });\n\n // Look for index file\n const indexCandidates = [\"index.ts\", \"index.js\", \"index.mjs\"];\n let indexPath: string | null = null;\n\n for (const candidate of indexCandidates) {\n const p = path.join(absDir, candidate);\n if (fs.existsSync(p)) {\n indexPath = p;\n break;\n }\n }\n\n if (!indexPath) {\n // Fallback: load each .ts/.js file individually\n console.log(chalk.yellow(\" No index file found, scanning individual collection files...\"));\n const collections: CollectionConfig[] = [];\n const files = fs.readdirSync(absDir).filter(f =>\n (f.endsWith(\".ts\") || f.endsWith(\".js\")) && !f.startsWith(\".\")\n );\n\n for (const file of files) {\n try {\n const mod = jitiInstance(path.join(absDir, file));\n const exported = mod.default || mod;\n if (exported && typeof exported === \"object\" && \"slug\" in exported) {\n collections.push(exported as CollectionConfig);\n } else if (Array.isArray(exported)) {\n collections.push(...exported);\n }\n } catch (err) {\n console.warn(chalk.yellow(` ⚠ Skipping ${file}: ${(err as Error).message}`));\n }\n }\n\n return collections;\n }\n\n // Import the index\n const mod = jitiInstance(indexPath);\n const exported = mod.default || mod;\n\n if (Array.isArray(exported)) {\n return exported as CollectionConfig[];\n } else if (typeof exported === \"object\" && exported !== null) {\n // Could be a named export like { collections: [...] }\n if (\"collections\" in exported && Array.isArray(exported.collections)) {\n return exported.collections;\n }\n // Or individual named exports\n const collections: CollectionConfig[] = [];\n for (const value of Object.values(exported)) {\n if (value && typeof value === \"object\" && \"slug\" in (value as CollectionConfig)) {\n collections.push(value as CollectionConfig);\n }\n }\n if (collections.length > 0) return collections;\n }\n\n throw new Error(\n `Could not extract collections from ${indexPath}.\\n` +\n \"Expected a default export of CollectionConfig[] or an object with named collection exports.\"\n );\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n -c, --collections-dir <dir> Local collections directory (default: ./config/collections)\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From local collections\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n`.trim());\n}\n\n/**\n * Fetch collections from a running project's contract endpoint.\n *\n * The payload replaces relation `target` functions with slug references, so it\n * has to be rehydrated before the generator sees it — the generator *calls*\n * `target()` to decide whether a foreign key is a string or a number, and a\n * missing target silently degrades that to a union rather than failing.\n */\nasync function fetchRemoteCollections(\n baseUrl: string,\n token: string | undefined\n): Promise<{ collections: CollectionConfig[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n console.log(chalk.gray(\" Pass --token, or set REBASE_SERVICE_KEY.\"));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract = await response.json() as {\n collections?: unknown[];\n schemaVersion?: string;\n };\n\n if (!Array.isArray(contract.collections)) {\n console.log(chalk.red(\" ✗ The contract response did not contain collections.\"));\n process.exit(1);\n }\n\n return {\n collections: deserializeCollections(contract.collections),\n schemaVersion: contract.schemaVersion ?? \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port this project last ran on; fall back to the literal only when the project\n * has never been started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { collectionsDir, output, cwd } = args;\n\n if (args.help) {\n printSdkHelp();\n return;\n }\n\n const resolvedCollectionsDir = path.isAbsolute(collectionsDir)\n ? collectionsDir\n : path.join(cwd, collectionsDir);\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n\n let collections: CollectionConfig[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteCollections(baseUrl, args.token || ambient);\n collections = remote.collections;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n console.log(` ${chalk.gray(\"Collections:\")} ${resolvedCollectionsDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading collection definitions...\"));\n collections = await loadCollections(resolvedCollectionsDir);\n }\n\n // Sort collections alphabetically by slug to ensure deterministic SDK generation\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n\n if (collections.length === 0) {\n console.log(chalk.red(\" ✗ No collections found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map(c => c.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n const files = generateSDK(collections);\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(collections);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\nexport const GENERATED_AT = ${JSON.stringify(new Date().toISOString())};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const exampleSlug = collections[0]?.slug || \"my_collection\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { collectionsDictionary, type Database } from '${typesImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" collections: collectionsDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.…` is the typed surface. `rebase.collection(slug)` exists\n // too, but it is generic over `Record<string, unknown>` and has no link to\n // `Database` — printing it here would advertise the one call shape that\n // throws away the types this command just generated.\n console.log(chalk.gray(` const { data } = await rebase.data.collection('${exampleSlug}').find();`));\n if (isIdentifierLike(exampleSlug)) {\n console.log(chalk.gray(` // …or in property style: rebase.data.${exampleSlug}.find()`));\n }\n console.log(\"\");\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printSchemaHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n process.exit(1);\n }\n}\n\nfunction printSchemaHelp() {\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} Path to collections directory\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n`);\n}\n","/**\n * CLI command: rebase db <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printDbHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n\nfunction printDbHelp() {\n console.log(`\n${chalk.bold(\"rebase db\")} — Database management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase db ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"push\")} Apply schema directly to database (development)\n ${chalk.blue.bold(\"generate\")} Generate migration files\n ${chalk.blue.bold(\"migrate\")} Run pending migrations\n ${chalk.blue.bold(\"branch\")} Database branching (create, list, delete, info)\n ${chalk.blue.bold(\"backup\")} Create a backup with pg_dump (--out <path|s3://…>)\n ${chalk.blue.bold(\"restore\")} Restore a backup with pg_restore (destructive; needs --yes)\n ${chalk.blue.bold(\"backups\")} List stored backups (backups list)\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.gray(\"# Quick development workflow\")}\n rebase schema generate && rebase db push\n\n ${chalk.gray(\"# Production migration workflow\")}\n rebase db generate\n rebase db migrate\n\n ${chalk.gray(\"# Create a database branch\")}\n rebase db branch create feature_auth\n\n ${chalk.gray(\"# Back up to a local directory, then to object storage\")}\n rebase db backup --out ./backups\n rebase db backup --out s3://my-private-bucket/backups\n\n ${chalk.gray(\"# Restore into a fresh database (safe: does not touch the live one)\")}\n rebase db restore ./backups/rebase-app-20260714T030000Z.dump --create-db --target-db app_restored\n`);\n}\n","/**\n * Loading, validating and synthesizing `rebase.json`.\n *\n * The manifest declares *topology*: which runtime major a project targets and\n * which apps this repository contributes. It is deliberately small — schema,\n * security rules, hooks and functions stay in TypeScript, where a type system\n * can check them.\n *\n * Two properties matter more than the file format itself:\n *\n * - **A missing manifest is never an error.** Every project that exists today\n * predates this file. One is synthesized from the conventions the template\n * already follows, so nothing breaks and nobody is forced to migrate.\n * - **Validation reports every problem at once**, with the path to each. A\n * config file that surfaces its mistakes one run at a time is a bad config\n * file.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport type {\n ManagedCompatibility,\n RebaseAppConfig,\n RebaseBackendAppConfig,\n RebaseProjectManifest\n} from \"@rebasepro/types\";\nimport { MANIFEST_FILENAME } from \"./utils/project\";\n\n/** Runtime range written into new manifests. */\nexport const CURRENT_RUNTIME_RANGE = \"^1\";\n\n/** Conventional locations, matching what `rebase init` scaffolds. */\nexport const DEFAULT_CONFIG_DIR = \"config\";\nexport const DEFAULT_FUNCTIONS_DIR = \"backend/functions\";\nexport const DEFAULT_CRONS_DIR = \"backend/crons\";\nexport const DEFAULT_SCHEMA_FILE = \"backend/src/schema.generated.ts\";\n\nexport interface ManifestValidationIssue {\n /** Dotted path to the offending value, e.g. `apps.web.output`. */\n path: string;\n message: string;\n}\n\nexport interface LoadedManifest {\n manifest: RebaseProjectManifest;\n /** Where it came from — a real file, or inferred from the directory layout. */\n source: \"file\" | \"synthesized\";\n /** Absolute path to `rebase.json`, when one exists. */\n filePath?: string;\n}\n\nexport class ManifestError extends Error {\n constructor(message: string, readonly issues: ManifestValidationIssue[] = []) {\n super(message);\n this.name = \"ManifestError\";\n }\n}\n\nconst APP_TYPES = [\"backend\", \"static\", \"admin\", \"mobile\", \"custom\"] as const;\n\n/** Reserved because they name things in URLs and CLI output. */\nconst RESERVED_APP_NAMES = new Set([\"api\", \"health\", \"metrics\", \"livez\", \"_rebase\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reject paths that escape the repository.\n *\n * A manifest is committed and reviewed, so this is not a security boundary so\n * much as a guard against `../../` typos that would otherwise have `rebase build`\n * writing outside the project.\n */\nfunction checkRelativePath(\n value: unknown,\n fieldPath: string,\n issues: ManifestValidationIssue[],\n { required }: { required: boolean }\n): string | undefined {\n if (value === undefined) {\n if (required) issues.push({ path: fieldPath,\nmessage: \"is required\" });\n return undefined;\n }\n if (typeof value !== \"string\" || value.trim() === \"\") {\n issues.push({ path: fieldPath,\nmessage: \"must be a non-empty string\" });\n return undefined;\n }\n if (path.isAbsolute(value)) {\n issues.push({ path: fieldPath,\nmessage: \"must be a relative path, not absolute\" });\n return undefined;\n }\n const normalized = path.normalize(value);\n if (normalized === \"..\" || normalized.startsWith(`..${path.sep}`)) {\n issues.push({ path: fieldPath,\nmessage: \"must stay inside the project directory\" });\n return undefined;\n }\n return value;\n}\n\nfunction validateApp(\n name: string,\n raw: unknown,\n issues: ManifestValidationIssue[]\n): RebaseAppConfig | undefined {\n const base = `apps.${name}`;\n\n if (!isRecord(raw)) {\n issues.push({ path: base,\nmessage: \"must be an object\" });\n return undefined;\n }\n\n const type = raw.type;\n if (typeof type !== \"string\" || !(APP_TYPES as readonly string[]).includes(type)) {\n issues.push({\n path: `${base}.type`,\n message: `must be one of: ${APP_TYPES.join(\", \")}`\n });\n return undefined;\n }\n\n switch (type) {\n case \"backend\": {\n checkRelativePath(raw.config, `${base}.config`, issues, { required: false });\n checkRelativePath(raw.functions, `${base}.functions`, issues, { required: false });\n checkRelativePath(raw.crons, `${base}.crons`, issues, { required: false });\n checkRelativePath(raw.schema, `${base}.schema`, issues, { required: false });\n checkRelativePath(raw.usersCollection, `${base}.usersCollection`, issues, { required: false });\n if (raw.mode !== undefined && raw.mode !== \"cms\" && raw.mode !== \"baas\") {\n issues.push({ path: `${base}.mode`,\nmessage: 'must be \"cms\" or \"baas\"' });\n }\n return raw as unknown as RebaseAppConfig;\n }\n case \"static\": {\n checkRelativePath(raw.root, `${base}.root`, issues, { required: true });\n checkRelativePath(raw.output, `${base}.output`, issues, { required: true });\n if (raw.build !== undefined && typeof raw.build !== \"string\") {\n issues.push({ path: `${base}.build`,\nmessage: \"must be a string command\" });\n }\n if (raw.spa !== undefined && typeof raw.spa !== \"boolean\") {\n issues.push({ path: `${base}.spa`,\nmessage: \"must be a boolean\" });\n }\n return raw as unknown as RebaseAppConfig;\n }\n case \"admin\": {\n const mode = raw.mode ?? \"hosted\";\n if (mode !== \"hosted\" && mode !== \"bundled\") {\n issues.push({ path: `${base}.mode`,\nmessage: 'must be \"hosted\" or \"bundled\"' });\n return undefined;\n }\n if (mode === \"bundled\") {\n // A bundled admin panel is built here, so it needs somewhere to\n // build from and somewhere to put the result. Hosted needs\n // neither, which is the entire point of it being the default.\n checkRelativePath(raw.root, `${base}.root`, issues, { required: true });\n checkRelativePath(raw.output, `${base}.output`, issues, { required: true });\n }\n return raw as unknown as RebaseAppConfig;\n }\n case \"mobile\": {\n const platform = raw.platform;\n if (platform !== \"ios\" && platform !== \"android\" && platform !== \"other\") {\n issues.push({\n path: `${base}.platform`,\n message: 'must be \"ios\", \"android\" or \"other\"'\n });\n }\n return raw as unknown as RebaseAppConfig;\n }\n case \"custom\": {\n checkRelativePath(raw.dockerfile, `${base}.dockerfile`, issues, { required: false });\n checkRelativePath(raw.context, `${base}.context`, issues, { required: false });\n if (raw.port !== undefined && (typeof raw.port !== \"number\" || !Number.isInteger(raw.port))) {\n issues.push({ path: `${base}.port`,\nmessage: \"must be an integer\" });\n }\n return raw as unknown as RebaseAppConfig;\n }\n default:\n return undefined;\n }\n}\n\n/**\n * Validate a parsed manifest, collecting every problem.\n */\nexport function validateManifest(raw: unknown): {\n manifest?: RebaseProjectManifest;\n issues: ManifestValidationIssue[];\n} {\n const issues: ManifestValidationIssue[] = [];\n\n if (!isRecord(raw)) {\n return { issues: [{ path: \"\",\nmessage: `${MANIFEST_FILENAME} must contain a JSON object` }] };\n }\n\n if (typeof raw.runtime !== \"string\" || raw.runtime.trim() === \"\") {\n issues.push({\n path: \"runtime\",\n message: `is required, e.g. \"${CURRENT_RUNTIME_RANGE}\"`\n });\n }\n\n if (!isRecord(raw.apps)) {\n issues.push({ path: \"apps\",\nmessage: \"is required and must be an object\" });\n return { issues };\n }\n\n const apps: Record<string, RebaseAppConfig> = {};\n let backendCount = 0;\n\n for (const [name, value] of Object.entries(raw.apps)) {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {\n issues.push({\n path: `apps.${name}`,\n message: \"name must be lowercase alphanumeric with dashes (it appears in URLs)\"\n });\n continue;\n }\n if (RESERVED_APP_NAMES.has(name)) {\n issues.push({ path: `apps.${name}`,\nmessage: \"name is reserved\" });\n continue;\n }\n\n const app = validateApp(name, value, issues);\n if (!app) continue;\n if (app.type === \"backend\") backendCount++;\n apps[name] = app;\n }\n\n // One backend per *project*. A repository declaring two would have two sets\n // of collections claiming the same database and the same API surface.\n if (backendCount > 1) {\n issues.push({\n path: \"apps\",\n message: \"a project may declare at most one backend app\"\n });\n }\n\n if (issues.length > 0) return { issues };\n\n return {\n manifest: {\n $schema: typeof raw.$schema === \"string\" ? raw.$schema : undefined,\n runtime: raw.runtime as string,\n apps\n },\n issues\n };\n}\n\n/**\n * Infer a manifest from a directory that does not have one.\n *\n * This mirrors exactly what the template scaffolds, which is what makes adopting\n * the manifest a no-op for existing projects: the synthesized result is what\n * they would have written by hand.\n *\n * An ejected backend — one with its own `src/index.ts` entrypoint — is reported\n * as a `custom` app rather than a `backend` app. That is not a downgrade; it is\n * an accurate description, and it is what keeps such a project deploying exactly\n * as it does today.\n */\nexport function synthesizeManifest(projectRoot: string): RebaseProjectManifest {\n const exists = (relative: string): boolean => fs.existsSync(path.join(projectRoot, relative));\n const apps: Record<string, RebaseAppConfig> = {};\n\n const hasConfig = exists(DEFAULT_CONFIG_DIR);\n const hasBackend = exists(\"backend\");\n const backendEntry = exists(\"backend/src/index.ts\");\n\n if (hasBackend && backendEntry) {\n apps.backend = {\n type: \"custom\",\n dockerfile: exists(\"backend/Dockerfile\") ? \"backend/Dockerfile\" : undefined,\n context: \".\"\n } as RebaseAppConfig;\n } else if (hasBackend || hasConfig) {\n const backend: RebaseBackendAppConfig = { type: \"backend\" };\n if (!hasConfig) backend.mode = \"baas\";\n if (exists(DEFAULT_FUNCTIONS_DIR)) backend.functions = DEFAULT_FUNCTIONS_DIR;\n if (exists(DEFAULT_CRONS_DIR)) backend.crons = DEFAULT_CRONS_DIR;\n apps.backend = backend;\n }\n\n if (exists(\"frontend\")) {\n apps.web = {\n type: \"static\",\n root: \"frontend\",\n build: \"npm run build --workspace frontend\",\n output: \"frontend/dist\",\n spa: true\n };\n }\n\n return { runtime: CURRENT_RUNTIME_RANGE,\napps };\n}\n\nexport function manifestPath(projectRoot: string): string {\n return path.join(projectRoot, MANIFEST_FILENAME);\n}\n\nexport function manifestExists(projectRoot: string): boolean {\n return fs.existsSync(manifestPath(projectRoot));\n}\n\n/**\n * Read the manifest, falling back to a synthesized one.\n *\n * A malformed manifest throws — unlike a missing one. Silently ignoring a file\n * the developer wrote, and building something else instead, is the worst\n * available behaviour.\n */\nexport function loadManifest(projectRoot: string): LoadedManifest {\n const filePath = manifestPath(projectRoot);\n\n if (!fs.existsSync(filePath)) {\n return { manifest: synthesizeManifest(projectRoot),\nsource: \"synthesized\" };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, \"utf8\"));\n } catch (err) {\n throw new ManifestError(\n `${MANIFEST_FILENAME} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n const { manifest, issues } = validateManifest(parsed);\n if (!manifest) {\n throw new ManifestError(`${MANIFEST_FILENAME} is invalid`, issues);\n }\n\n return { manifest,\nsource: \"file\",\nfilePath };\n}\n\n/** Write a manifest, with a trailing newline so it plays well with other tools. */\nexport function writeManifest(projectRoot: string, manifest: RebaseProjectManifest): string {\n const filePath = manifestPath(projectRoot);\n const ordered = {\n $schema: manifest.$schema ?? \"https://rebase.pro/schemas/rebase.json\",\n runtime: manifest.runtime,\n apps: manifest.apps\n };\n fs.writeFileSync(filePath, `${JSON.stringify(ordered, null, 4)}\\n`, \"utf8\");\n return filePath;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Queries\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Find the single backend app, if this repository declares one. */\nexport function findBackendApp(\n manifest: RebaseProjectManifest\n): { name: string; app: RebaseBackendAppConfig } | undefined {\n for (const [name, app] of Object.entries(manifest.apps)) {\n if (app.type === \"backend\") return { name,\napp: app as RebaseBackendAppConfig };\n }\n return undefined;\n}\n\n/** Apps that produce build output, in the order they should be built. */\nexport function buildableApps(\n manifest: RebaseProjectManifest\n): { name: string; app: RebaseAppConfig }[] {\n // Backend first: a static app's build may consume an SDK generated from the\n // backend's collections, so building it second is the order that works.\n const entries = Object.entries(manifest.apps).map(([name, app]) => ({ name,\napp }));\n const rank = (app: RebaseAppConfig): number => {\n if (app.type === \"backend\") return 0;\n if (app.type === \"admin\") return 1;\n if (app.type === \"static\") return 2;\n return 3;\n };\n return entries\n .filter(({ app }) => app.type !== \"mobile\")\n .sort((a, b) => rank(a.app) - rank(b.app));\n}\n\n/**\n * Decide whether a project can run on the managed runtime, and say why not.\n *\n * \"Not eligible\" is never a dead end — it selects the custom-runtime path, which\n * still deploys. The reasons exist so the answer is actionable rather than a\n * verdict.\n */\nexport function assessManagedCompatibility(\n manifest: RebaseProjectManifest\n): ManagedCompatibility {\n const reasons: string[] = [];\n\n const backend = findBackendApp(manifest);\n if (!backend) {\n const custom = Object.entries(manifest.apps).find(([, app]) => app.type === \"custom\");\n if (custom) {\n reasons.push(\n `App \"${custom[0]}\" is a custom container. The managed runtime runs the ` +\n \"platform image with your bundle, so a project that builds its own image \" +\n \"uses the custom runtime instead.\"\n );\n } else {\n reasons.push(\n \"No backend app is declared in this repository. Only the repository that \" +\n \"declares the backend selects the runtime.\"\n );\n }\n }\n\n for (const [name, app] of Object.entries(manifest.apps)) {\n if (app.type === \"custom\") {\n reasons.push(`App \"${name}\" is a custom container image.`);\n }\n }\n\n return { eligible: reasons.length === 0 && Boolean(backend),\nreasons };\n}\n\n/** Resolve a backend app's directories against the conventions it omits. */\nexport function resolveBackendPaths(app: RebaseBackendAppConfig): {\n config: string;\n functions: string;\n crons: string;\n schema: string;\n usersCollection: string;\n mode: \"cms\" | \"baas\";\n} {\n return {\n config: app.config ?? DEFAULT_CONFIG_DIR,\n functions: app.functions ?? DEFAULT_FUNCTIONS_DIR,\n crons: app.crons ?? DEFAULT_CRONS_DIR,\n schema: app.schema ?? DEFAULT_SCHEMA_FILE,\n usersCollection: app.usersCollection ?? \"collections/users\",\n mode: app.mode ?? \"cms\"\n };\n}\n","/**\n * CLI command: rebase dev\n *\n * Starts the full development environment:\n * - Backend: tsx watch with auto-reload\n * - Frontend: vite dev server\n *\n * Both processes stream output with color-coded prefixes.\n *\n * When the backend uses port-retry (i.e. the configured port is busy and it\n * binds to the next free one), the CLI detects the actual port from stdout\n * and injects VITE_API_URL into the frontend so it connects automatically.\n *\n * Each project gets a deterministic default port derived from the project\n * root path, so multiple Rebase instances never collide.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa, execaCommandSync, type ResultPromise } from \"execa\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { fileURLToPath } from \"url\";\nimport { findBackendApp, loadManifest, resolveBackendPaths } from \"../manifest\";\nimport {\n requireProjectRoot,\n findBackendDir,\n findFrontendDir,\n findEnvFile,\n resolveTsx,\n validateTsxInstallation,\n getActiveBackendPlugin,\n resolvePluginCliScript\n} from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\n/**\n * Quote a path for the shell `execa` runs the backend through.\n *\n * The dev runtime's path is absolute and therefore contains whatever the\n * developer's directories are called. Double quotes do not neutralize `$`,\n * backticks or backslashes in a POSIX shell, so a checkout under a directory\n * named `$(...)` would execute it. Single quotes disable all expansion; on\n * Windows, `cmd.exe` performs no such expansion and wants double quotes.\n */\nfunction quoteForShell(value: string): string {\n if (process.platform === \"win32\") return `\"${value.replace(/\"/g, \"\\\\\\\"\")}\"`;\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Locate the dev runtime shim shipped with the CLI.\n *\n * Published under `runtime/` in the package rather than compiled into `dist/`,\n * because tsx executes it as a file and it must exist on disk at a stable path.\n */\nfunction resolveDevRuntimeEntry(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n // Walk up from wherever this module ended up (src/ in development, dist/ in\n // a published install) until the package root with `runtime/` is found.\n let dir = here;\n for (let i = 0; i < 5; i++) {\n const candidate = path.join(dir, \"runtime\", \"dev-server.mjs\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new Error(\n \"Could not find the Rebase dev runtime (runtime/dev-server.mjs). \" +\n \"Reinstall @rebasepro/cli, or add a backend/src/index.ts to run your own entrypoint.\"\n );\n}\n\n/**\n * Tell the dev runtime where this project keeps its parts.\n *\n * Read from `rebase.json` when there is one, so a project that moved its config\n * directory is honoured; otherwise the conventional layout.\n */\nfunction devRuntimeEnv(projectRoot: string): Record<string, string> {\n const result: Record<string, string> = {\n REBASE_DEV_PROJECT_ROOT: projectRoot,\n REBASE_DEV_CONFIG: \"config\",\n REBASE_DEV_FUNCTIONS: \"backend/functions\",\n REBASE_DEV_CRONS: \"backend/crons\",\n REBASE_DEV_SCHEMA: \"backend/src/schema.generated.ts\",\n REBASE_DEV_MODE: \"cms\"\n };\n\n try {\n const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (backend) {\n const paths = resolveBackendPaths(backend.app);\n result.REBASE_DEV_CONFIG = paths.config;\n result.REBASE_DEV_FUNCTIONS = paths.functions;\n result.REBASE_DEV_CRONS = paths.crons;\n result.REBASE_DEV_SCHEMA = paths.schema;\n result.REBASE_DEV_MODE = paths.mode;\n result.REBASE_DEV_APP = backend.name;\n }\n } catch {\n // An invalid manifest is reported by `rebase build`; dev falls back to\n // the conventional layout rather than refusing to start.\n }\n\n // A project with no config package is serving an introspected database.\n if (!fs.existsSync(path.join(projectRoot, result.REBASE_DEV_CONFIG))) {\n result.REBASE_DEV_MODE = \"baas\";\n }\n\n return result;\n}\n\n/** Well-known filename the backend writes its actual port to. */\nconst DEV_PORT_FILENAME = \".rebase-dev-port\";\n\n/**\n * Compute a deterministic port from the project root path.\n * Range: 3001–3999 (avoids privileged ports and common services).\n * Two different project directories will almost always get different ports.\n */\nfunction getProjectPort(projectRoot: string): number {\n let hash = 0;\n for (let i = 0; i < projectRoot.length; i++) {\n hash = ((hash << 5) - hash + projectRoot.charCodeAt(i)) | 0;\n }\n return 3001 + (Math.abs(hash) % 999);\n}\n\n/**\n * Resolve the best starting port for this project:\n * 1. Explicit --port flag (highest priority)\n * 2. PORT env var\n * 3. Previously used port from .rebase-dev-port (port affinity across restarts)\n * 4. Deterministic hash from project path (unique per project)\n */\nfunction resolveStartPort(projectRoot: string, explicitPort?: number): number {\n // 1. Explicit flag\n if (explicitPort) return explicitPort;\n\n // 2. PORT env var\n if (process.env.PORT) return parseInt(process.env.PORT, 10);\n\n // 3. Port affinity — check if we wrote a port file from a previous run\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) {\n const saved = parseInt(fs.readFileSync(portFile, \"utf-8\").trim(), 10);\n if (saved > 0 && saved < 65536) return saved;\n }\n } catch { /* ignore */ }\n\n // 4. Deterministic hash\n return getProjectPort(projectRoot);\n}\n\nexport async function devCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--backend-only\": Boolean,\n \"--frontend-only\": Boolean,\n \"--port\": Number,\n \"--generate\": Boolean,\n \"--help\": Boolean,\n \"-b\": \"--backend-only\",\n \"-f\": \"--frontend-only\",\n \"-p\": \"--port\",\n \"-g\": \"--generate\",\n \"-h\": \"--help\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node rebase dev\"\n permissive: true\n }\n );\n\n if (args[\"--help\"]) {\n printDevHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n const frontendDir = findFrontendDir(projectRoot);\n const backendOnly = args[\"--backend-only\"] || false;\n const frontendOnly = args[\"--frontend-only\"] || false;\n const shouldGenerate = args[\"--generate\"] || process.env.REBASE_AUTO_GENERATE === \"true\" || process.env.REBASE_GENERATE === \"true\";\n\n // Resolve the port ONCE, before starting anything\n const startPort = resolveStartPort(projectRoot, args[\"--port\"]);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🚀 Rebase Dev Server\"));\n console.log(\"\");\n\n const children: ResultPromise[] = [];\n\n // --- State for printing the banner ---\n let frontendUrl = \"\";\n let backendUrl = \"\";\n let debounceSummary: NodeJS.Timeout | null = null;\n let bannerPrinted = false;\n\n /** Actual backend port, resolved once the server prints its URL. */\n let resolvedBackendPort: number | null = null;\n\n // Use regex to strip ANSI codes before matching\n // eslint-disable-next-line no-control-regex\n const stripAnsi = (str: string) => str.replace(/[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, \"\");\n\n function printSummary() {\n if (!frontendUrl || !backendUrl) return;\n if (debounceSummary) clearTimeout(debounceSummary);\n debounceSummary = setTimeout(() => {\n if (bannerPrinted) return;\n console.log(\"\");\n console.log(chalk.cyan(\"┌────────────────────────────────────────────────────────────┐\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"│ ✦ Rebase Admin App is ready! │\"));\n const cleanUrl = stripAnsi(frontendUrl);\n const paddedUrl = cleanUrl.padEnd(41);\n console.log(chalk.cyan(\"│ ➜ Frontend URL: \") + chalk.white(paddedUrl) + chalk.cyan(\"│\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"└────────────────────────────────────────────────────────────┘\"));\n console.log(\"\");\n bannerPrinted = true;\n }, 500);\n }\n\n // Handle graceful shutdown\n const cleanup = () => {\n // Clean up dev port file\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) fs.unlinkSync(portFile);\n\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(urlFile)) fs.unlinkSync(urlFile);\n } catch { /* ignore */ }\n\n children.forEach((child) => {\n if (child.pid && !child.killed) {\n try {\n if (process.platform === \"win32\") {\n execaCommandSync(`taskkill /pid ${child.pid} /T /F`);\n } else {\n process.kill(-child.pid, \"SIGKILL\");\n }\n } catch (e) {\n try {\n child.kill(\"SIGKILL\");\n } catch (err) {\n // ignore\n }\n }\n }\n });\n process.exit(0);\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n /**\n * Start the Vite frontend, optionally injecting the backend port.\n */\n function startFrontend(backendPort: number | null) {\n if (!frontendDir) return;\n\n console.log(` ${chalk.magenta(\"▶\")} Frontend: ${chalk.gray(frontendDir)}`);\n\n const frontendEnv: Record<string, string> = { ...process.env as Record<string, string> };\n\n // Inject the resolved backend URL so Vite picks it up\n if (backendPort) {\n frontendEnv.VITE_API_URL = `http://localhost:${backendPort}`;\n console.log(` ${chalk.gray(\"↳ VITE_API_URL\")} = ${chalk.white(`http://localhost:${backendPort}`)}`);\n }\n\n const pm = detectPackageManager(projectRoot);\n const pmCmds = getPMCommands(pm);\n const runDevCmd = pmCmds.run(\"dev\");\n\n const frontendChild = execa(\n runDevCmd[0],\n runDevCmd.slice(1),\n {\n cwd: frontendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: frontendEnv,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n frontendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n frontendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const urlMatch = cleanLine.match(/(http:\\/\\/(?:localhost|127\\.0\\.0\\.1):\\d+)/);\n if (cleanLine.includes(\"Local:\") && urlMatch) {\n frontendUrl = urlMatch[1];\n printSummary();\n }\n });\n });\n\n frontendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n });\n });\n\n children.push(frontendChild);\n }\n\n // Start backend\n if (!frontendOnly && backendDir) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const addCmd = [...pmCmdsLocal.install, \"-D\", \"tsx\"].join(\" \");\n console.error(chalk.red(\" ✗ Could not find tsx binary for backend.\"));\n console.error(chalk.gray(` Install it with: ${addCmd}`));\n process.exit(1);\n }\n\n // Verify the tsx installation is intact (not just the symlink)\n const tsxValidationError = validateTsxInstallation(tsxBin);\n if (tsxValidationError) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const installCmd = pmCmdsLocal.install.join(\" \");\n console.error(chalk.red(\" ✗ tsx installation appears corrupted.\"));\n console.error(chalk.gray(` ${tsxValidationError}`));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n process.exit(1);\n }\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n // Always inject PORT so the backend uses our resolved port instead of\n // its hardcoded default (3001). This prevents cross-project collisions\n // when multiple Rebase instances run simultaneously.\n env.PORT = String(startPort);\n\n console.log(` ${chalk.cyan(\"▶\")} Backend: ${chalk.gray(backendDir)}`);\n console.log(` ${chalk.gray(\"↳ PORT\")} = ${chalk.white(String(startPort))}`);\n\n // The .env's PORT / VITE_API_URL look authoritative but are overridden in\n // dev: we derive a per-project port to avoid cross-project collisions and\n // point the frontend at it. Surface that so a mismatched .env doesn't turn\n // into a silent \"connecting to the wrong port\" debugging loop.\n if (envFile) {\n try {\n const envText = fs.readFileSync(envFile, \"utf-8\");\n const readEnvKey = (key: string): string | undefined => {\n const m = envText.match(new RegExp(`^\\\\s*${key}\\\\s*=\\\\s*(.+?)\\\\s*$`, \"m\"));\n return m ? m[1].replace(/^[\"']|[\"']$/g, \"\") : undefined;\n };\n const envPort = readEnvKey(\"PORT\");\n const envApiUrl = readEnvKey(\"VITE_API_URL\");\n // Only name the keys — never echo a raw `http://localhost:<port>`\n // value, so log scrapers don't mistake it for the dev server URL.\n const overridden: string[] = [];\n if (envPort && envPort !== String(startPort)) overridden.push(\"PORT\");\n if (envApiUrl && envApiUrl !== `http://localhost:${startPort}`) overridden.push(\"VITE_API_URL\");\n if (overridden.length > 0) {\n console.log(chalk.yellow(\n ` ⚠ dev uses a derived per-project port (${startPort}); your .env ${overridden.join(\" / \")} ` +\n `${overridden.length > 1 ? \"are\" : \"is\"} ignored here (avoids cross-project collisions). ` +\n `Pass ${chalk.white(\"--port\")} to pin a port.`\n ));\n }\n } catch { /* ignore — best-effort notice */ }\n }\n\n /** Whether the frontend has been launched (we only launch it once). */\n let frontendLaunched = false;\n\n // Initial schema and SDK generation (disabled by default, enabled via --generate or env var)\n if (shouldGenerate) {\n console.log(chalk.gray(\" → Ensuring schema and SDK are generated on start...\"));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Initial schema and SDK generated successfully.\\n\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Initial schema/SDK generation failed: ${err instanceof Error ? err.message : err}\\n`));\n }\n\n // Watch collections folder for changes\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let watchDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n\n if (watchDebounce) clearTimeout(watchDebounce);\n watchDebounce = setTimeout(async () => {\n console.log(chalk.yellow(`\\n 🔄 Collection change detected (${filename}). Regenerating schema & SDK...`));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Schema & SDK regenerated successfully. Hono will reload.\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Failed to regenerate schema/SDK: ${err instanceof Error ? err.message : err}`));\n }\n }, 300);\n });\n }\n }\n\n // A project with its own `backend/src/index.ts` runs it, exactly as\n // before. Without one, dev boots the stock runtime over the project's\n // TypeScript source — the same boot path a deployment takes, so what runs\n // locally is what will run deployed. This is what makes the hand-written\n // entrypoint optional instead of something every project must carry.\n const ejectedEntry = path.join(backendDir, \"src\", \"index.ts\");\n const usesStockRuntime = !fs.existsSync(ejectedEntry);\n const entryTarget = usesStockRuntime ? resolveDevRuntimeEntry() : \"src/index.ts\";\n\n if (usesStockRuntime) {\n Object.assign(env, devRuntimeEnv(projectRoot));\n }\n\n const watchArgs = [\"watch\", \"--conditions\", \"development\", quoteForShell(entryTarget)];\n if (!shouldGenerate) {\n // When auto-generation is disabled, watch the config/collections dir directly so the dev server\n // still reloads automatically when files there are edited/updated manually.\n watchArgs.splice(1, 0, `--watch=\"${path.join(\"..\", \"config\", \"**\", \"*\")}\"`);\n\n // Watch collections folder and warn about potential schema drift\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let driftDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (_eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n if (driftDebounce) clearTimeout(driftDebounce);\n driftDebounce = setTimeout(() => {\n console.log([\n \"\",\n chalk.yellow(\" ┌──────────────────────────────────────────────────────────────┐\"),\n chalk.yellow(\" │ ⚠️ Collection file changed: \") + chalk.white(filename!.padEnd(31)) + chalk.yellow(\"│\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ Your schema may be out of sync. Run: │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase schema generate\") + chalk.yellow(\" regenerate Drizzle schema │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase db push \") + chalk.yellow(\" sync schema to database │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase doctor \") + chalk.yellow(\" check for drift │\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ TIP: Use \") + chalk.bold(\"rebase dev --generate\") + chalk.yellow(\" for auto-regeneration │\"),\n chalk.yellow(\" └──────────────────────────────────────────────────────────────┘\"),\n \"\"\n ].join(\"\\n\"));\n }, 500);\n });\n }\n }\n\n const backendChild = execa(\n tsxBin,\n watchArgs,\n {\n cwd: backendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n backendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n backendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const serverMatch = cleanLine.match(/Server running at http:\\/\\/(?:localhost|127\\.0\\.0\\.1):(\\d+)/);\n if (serverMatch) {\n resolvedBackendPort = parseInt(serverMatch[1], 10);\n backendUrl = \"started\";\n printSummary();\n\n // Save the url to a temp file for scripts to pick up\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n fs.writeFileSync(urlFile, `http://localhost:${resolvedBackendPort}`, \"utf-8\");\n\n // Save the port to .rebase-dev-port for port affinity\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n fs.writeFileSync(portFile, String(resolvedBackendPort), \"utf-8\");\n\n // Start frontend now that we know the real port\n if (!backendOnly && frontendDir && !frontendLaunched) {\n frontendLaunched = true;\n startFrontend(resolvedBackendPort);\n }\n }\n });\n });\n\n /** Whether we've already shown a corrupted-modules recovery hint. */\n let corruptedModulesWarned = false;\n\n backendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n\n // Detect corrupted node_modules at runtime\n // (covers tsx and any other dependency whose pnpm store entry is broken)\n if (!corruptedModulesWarned) {\n const cleanLine = stripAnsi(line);\n if (\n cleanLine.includes(\"Cannot find module\") &&\n cleanLine.includes(\"node_modules/.pnpm/\")\n ) {\n corruptedModulesWarned = true;\n // Delay slightly so the full Node.js error stack prints first\n setTimeout(() => {\n const pm = detectPackageManager(projectRoot);\n const installCmd = getPMCommands(pm).install.join(\" \");\n console.error(\"\");\n console.error(chalk.red(\" ✗ node_modules appears corrupted — a required file is missing.\"));\n console.error(chalk.gray(\" This usually happens when a previous install was interrupted\"));\n console.error(chalk.gray(\" or the package manager store was cleaned.\"));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, stop the dev server and run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n console.error(\"\");\n }, 200);\n }\n }\n });\n });\n\n children.push(backendChild);\n } else if (!frontendOnly && !backendDir) {\n console.warn(chalk.yellow(\" ⚠ No backend/ directory found, skipping backend.\"));\n }\n\n // Start frontend immediately if backend-only mode or no backend\n if (!backendOnly && frontendDir && (frontendOnly || !backendDir)) {\n startFrontend(null);\n } else if (!backendOnly && !frontendDir) {\n console.warn(chalk.yellow(\" ⚠ No frontend/ directory found, skipping frontend.\"));\n }\n\n if (children.length === 0) {\n console.error(chalk.red(\" ✗ Nothing to start. Check your project structure.\"));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Press Ctrl+C to stop all servers.\"));\n console.log(\"\");\n\n // Wait for all children to exit\n await Promise.all(\n children.map(\n (child) =>\n new Promise<void>((resolve) => {\n child.finally(() => resolve());\n })\n )\n );\n}\n\nfunction printDevHelp() {\n console.log(`\n${chalk.bold(\"rebase dev\")} — Start the development server\n\n${chalk.green.bold(\"Usage\")}\n rebase dev [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--backend-only, -b\")} Only start the backend server\n ${chalk.blue(\"--frontend-only, -f\")} Only start the frontend server\n ${chalk.blue(\"--port, -p\")} Backend port (default: auto-detected per project)\n ${chalk.blue(\"--generate, -g\")} Enable automatic schema and SDK generation on startup and file changes\n\n${chalk.green.bold(\"Description\")}\n Starts both the backend (tsx watch + Hono) and frontend (Vite)\n dev servers concurrently with color-coded output prefixes.\n\n Each project automatically receives a unique default port derived\n from its directory path, preventing collisions when running multiple\n Rebase instances simultaneously.\n\n If the assigned port is already in use, the server will automatically\n try the next available port. The frontend is started only after the\n backend is ready, and VITE_API_URL is injected automatically.\n\n By default, automatic schema and SDK generation is disabled on startup\n and file changes. Pass --generate (-g) or set REBASE_AUTO_GENERATE=true\n in your environment to enable it.\n`);\n}\n","/**\n * Building a project bundle.\n *\n * A bundle is the deployable form of a project: compiled collections, functions,\n * crons and schema, plus a generated manifest describing exactly what it needs\n * to run. It contains no Dockerfile and no repository — the runtime is supplied\n * separately, which is what allows a project to be moved onto a patched runtime\n * without being rebuilt.\n *\n * Compilation runs through a generated tsconfig rooted at the project directory,\n * so the output mirrors the source layout (`config/…`, `backend/functions/…`)\n * and every path in the manifest is predictable. Letting each workspace package\n * emit into its own `dist/` would have meant guessing at three different\n * layouts, since `rootDir` differs between the template flavours.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { createRequire } from \"module\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport {\n BUNDLE_FORMAT_VERSION,\n RUNTIME_CONTRACT_VERSION,\n computeSchemaVersion,\n type CollectionConfig,\n type NativeDependency,\n type RebaseBundleManifest,\n type RebaseBackendAppConfig\n} from \"@rebasepro/types\";\nimport { resolveBackendPaths } from \"./manifest\";\nimport {\n getActiveBackendPlugin,\n resolveLocalBin,\n resolvePluginCliScript,\n resolveTsx\n} from \"./utils/project\";\n\nexport const DEFAULT_BUNDLE_DIR = \"dist-bundle\";\n\nexport interface BuildBundleOptions {\n projectRoot: string;\n appName: string;\n app: RebaseBackendAppConfig;\n /** Output directory, absolute or relative to the project root. */\n outDir?: string;\n /** Runtime range from the manifest, recorded for compatibility checks. */\n runtimeRange: string;\n /** Skip type checking. Faster, and strictly worse — for iteration only. */\n skipTypeCheck?: boolean;\n /** Skip regenerating the Drizzle schema from the collections. */\n skipSchema?: boolean;\n /** Emit progress. */\n log?: (message: string) => void;\n}\n\nexport interface BuildBundleResult {\n outDir: string;\n manifest: RebaseBundleManifest;\n collectionCount: number;\n}\n\n/** Packages whose presence means the bundle cannot run on a stock runtime image. */\nconst KNOWN_NATIVE_PACKAGES = new Set([\n \"sharp\",\n \"canvas\",\n \"bcrypt\",\n \"argon2\",\n \"node-sass\",\n \"sqlite3\",\n \"better-sqlite3\",\n \"grpc\",\n \"@grpc/grpc-js-native\",\n \"re2\",\n \"sodium-native\",\n \"libpq\",\n \"pg-native\"\n]);\n\n/** Dependencies supplied by the runtime image itself, not by the bundle. */\nconst RUNTIME_PROVIDED = new Set([\n \"@rebasepro/server\",\n \"@rebasepro/types\",\n \"@rebasepro/client\",\n \"@rebasepro/common\",\n \"@rebasepro/utils\",\n \"hono\",\n \"@hono/node-server\",\n \"typescript\",\n \"tsx\"\n]);\n\nfunction log(options: BuildBundleOptions, message: string): void {\n (options.log ?? ((m: string) => console.log(m)))(message);\n}\n\n/**\n * Every `node_modules/@types` directory the project can see.\n *\n * Type roots normally resolve by walking up from the tsconfig's own directory,\n * which breaks here for two reasons: the generated config lives in `.rebase/`,\n * and a pnpm workspace puts `@types/node` inside the *package* that depends on\n * it (`config/node_modules/@types`) rather than at the project root. Listing them\n * explicitly, as absolute paths, sidesteps both.\n */\nfunction discoverTypeRoots(projectRoot: string): string[] {\n const candidates: string[] = [];\n\n for (const relative of [\".\", \"config\", \"backend\", \"frontend\"]) {\n candidates.push(path.join(projectRoot, relative, \"node_modules\", \"@types\"));\n }\n\n // Walk up as well, for a project nested inside a larger workspace.\n let dir = projectRoot;\n for (let i = 0; i < 4; i++) {\n const parent = path.dirname(dir);\n if (parent === dir) break;\n candidates.push(path.join(parent, \"node_modules\", \"@types\"));\n dir = parent;\n }\n\n return candidates.filter(candidate => fs.existsSync(candidate));\n}\n\n/**\n * Read a tsconfig's own `compilerOptions`.\n *\n * Parsed with the project's own TypeScript, because a tsconfig is not JSON: it\n * permits comments and trailing commas. Hand-rolled comment stripping gets this\n * wrong in a way that is easy to miss — a `paths` entry like\n * `\"@acme/types/*\": [\"src/*\"]` contains the character sequence that opens a\n * block comment, so a regex happily eats the rest of the file and the result\n * parses as *something*, just not the config the developer wrote.\n *\n * One level only, and only `paths` is used from it.\n */\nasync function readCompilerOptions(\n projectRoot: string,\n file: string\n): Promise<Record<string, unknown> | undefined> {\n if (!fs.existsSync(file)) return undefined;\n\n const text = fs.readFileSync(file, \"utf8\");\n\n try {\n const require = createRequire(path.join(projectRoot, \"package.json\"));\n const ts = require(\"typescript\") as {\n parseConfigFileTextToJson(fileName: string, text: string): {\n config?: { compilerOptions?: Record<string, unknown> };\n error?: unknown;\n };\n };\n const { config } = ts.parseConfigFileTextToJson(file, text);\n return config?.compilerOptions;\n } catch {\n // TypeScript is not resolvable from the project root. Fall back to\n // stripping whole-line comments only — never block comments, for the\n // reason above — and give up quietly if that still is not valid JSON.\n try {\n const parsed = JSON.parse(text.replace(/^\\s*\\/\\/.*$/gm, \"\")) as {\n compilerOptions?: Record<string, unknown>;\n };\n return parsed.compilerOptions;\n } catch {\n return undefined;\n }\n }\n}\n\n/**\n * Drop path aliases that resolve outside the project.\n *\n * A monorepo commonly aliases its workspace packages to their **source**\n * (`\"@acme/types\": [\"packages/types/src/index.ts\"]`) so editors jump to real\n * files. That is right for developing the monorepo and wrong for building a\n * bundle: it drags foreign `.ts` files into the program, none of which are under\n * the project's `rootDir`, and the compile fails on files the developer never\n * asked to build.\n *\n * A bundle is built against *installed packages*. Aliases pointing inside the\n * project are kept, because those are the project's own code.\n */\nfunction filterProjectPaths(\n baseDir: string,\n projectRoot: string,\n paths: Record<string, string[]>,\n baseUrl: string\n): { kept: Record<string, string[]>; dropped: string[] } {\n const kept: Record<string, string[]> = {};\n const dropped: string[] = [];\n\n for (const [alias, targets] of Object.entries(paths)) {\n if (!Array.isArray(targets)) continue;\n const resolved = targets.map(target => path.resolve(baseUrl, target));\n const allInside = resolved.every(target => {\n const relative = path.relative(projectRoot, target);\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n });\n if (allInside) {\n kept[alias] = resolved.map(target => {\n const relative = path.relative(baseDir, target);\n return relative.split(path.sep).join(\"/\");\n });\n } else {\n dropped.push(alias);\n }\n }\n\n return { kept,\ndropped };\n}\n\n/**\n * Compose the tsconfig used to compile the bundle.\n *\n * Extends the config package's own tsconfig when there is one, so the project's\n * choices about target, JSX and strictness are respected. It has to be `extends`\n * rather than a copy of `compilerOptions`: TypeScript resolves relative paths\n * against the file they were written in, so copying a value like\n * `baseUrl: \"../../\"` into a config in a different directory silently repoints\n * it at the wrong place.\n */\nasync function writeBundleTsconfig(\n projectRoot: string,\n outDir: string,\n includes: string[],\n skipTypeCheck: boolean\n): Promise<string> {\n // Paths written *here* resolve against this file's directory. Posix\n // separators, because tsconfig wants them on every platform.\n const tsconfigDir = path.join(projectRoot, \".rebase\");\n const fromTsconfig = (target: string): string => {\n const relative = path.relative(tsconfigDir, path.resolve(projectRoot, target));\n return relative.split(path.sep).join(\"/\");\n };\n\n const configTsconfigPath = path.join(projectRoot, \"config\", \"tsconfig.json\");\n const extendsFrom = fs.existsSync(configTsconfigPath)\n ? fromTsconfig(path.join(\"config\", \"tsconfig.json\"))\n : undefined;\n\n // Neutralize aliases that escape the project (see `filterProjectPaths`).\n let pathOverrides: Record<string, unknown> = {};\n const baseOptions = await readCompilerOptions(projectRoot, configTsconfigPath);\n if (baseOptions?.paths && typeof baseOptions.paths === \"object\") {\n const baseDir = path.dirname(configTsconfigPath);\n const baseUrl = path.resolve(\n baseDir,\n typeof baseOptions.baseUrl === \"string\" ? baseOptions.baseUrl : \".\"\n );\n const { kept, dropped } = filterProjectPaths(\n tsconfigDir,\n projectRoot,\n baseOptions.paths as Record<string, string[]>,\n baseUrl\n );\n pathOverrides = { baseUrl: fromTsconfig(\".\"),\npaths: kept };\n if (dropped.length > 0) {\n console.log(chalk.dim(\n ` ignoring ${dropped.length} path alias(es) pointing outside the project ` +\n `(${dropped.join(\", \")}) — resolving those from node_modules instead`\n ));\n }\n }\n\n const compilerOptions: Record<string, unknown> = {\n // Defaults, used when there is no project tsconfig to extend. When there\n // is one, its values win over these and are overridden only by the block\n // below.\n target: \"ES2022\",\n module: \"ESNext\",\n moduleResolution: \"bundler\",\n lib: [\"ES2022\"],\n jsx: \"react-jsx\",\n allowSyntheticDefaultImports: true,\n esModuleInterop: true,\n resolveJsonModule: true,\n forceConsistentCasingInFileNames: true,\n\n // Everything below is the bundle's contract and is not negotiable.\n rootDir: fromTsconfig(\".\"),\n outDir: fromTsconfig(path.relative(projectRoot, outDir) || \".\"),\n typeRoots: discoverTypeRoots(projectRoot),\n ...pathOverrides,\n declaration: false,\n declarationMap: false,\n sourceMap: true,\n noEmit: false,\n skipLibCheck: true,\n // The runtime imports the emitted files directly with Node's ESM loader,\n // so they stay ES modules regardless of what the project targets for its\n // own builds.\n allowJs: true,\n ...(skipTypeCheck ? { noCheck: true } : {})\n };\n\n const tsconfig = {\n ...(extendsFrom ? { extends: extendsFrom } : {}),\n compilerOptions,\n include: includes.map(fromTsconfig),\n exclude: [\n \"node_modules\",\n \"**/*.test.ts\",\n \"**/*.spec.ts\",\n \"**/dist/**\",\n DEFAULT_BUNDLE_DIR\n ].map(pattern => (pattern.startsWith(\"**\") ? pattern : fromTsconfig(pattern)))\n };\n\n fs.mkdirSync(tsconfigDir, { recursive: true });\n const tsconfigPath = path.join(tsconfigDir, \"tsconfig.bundle.json\");\n fs.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2), \"utf8\");\n return tsconfigPath;\n}\n\n/**\n * Whether the compiled config package exports a `storageAuthorize` hook.\n *\n * Recorded in the manifest so a host can refuse a deploy that would enable file\n * storage with no access model, rather than let the runtime's boot guard turn it\n * into a crash loop the developer cannot read.\n *\n * Read from the *compiled* index, deliberately: that is the exact module the\n * runtime imports and reads the export off, so this cannot disagree with what\n * actually happens at boot. It is a textual check rather than an import because\n * a freshly built bundle cannot resolve its own dependencies until it is\n * deployed — the same reason schema hashing reads source.\n *\n * Errs toward `false`: a missed detection costs a deploy rejection whose message\n * says exactly how to proceed, while a false positive would hand back the crash\n * loop this exists to prevent.\n */\nexport function detectStorageAuthorize(compiledConfigDir: string): boolean {\n const indexPath = [\".js\", \".mjs\", \".ts\"]\n .map(ext => path.join(compiledConfigDir, `index${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!indexPath) return false;\n\n let source: string;\n try {\n source = fs.readFileSync(indexPath, \"utf8\");\n } catch {\n return false;\n }\n\n // `export const/let/var/function/async function storageAuthorize`\n if (/\\bexport\\s+(?:async\\s+)?(?:const|let|var|function)\\s+storageAuthorize\\b/.test(source)) {\n return true;\n }\n // `export { storageAuthorize }` / `export { x as storageAuthorize }`,\n // including re-export forms (`export { storageAuthorize } from \"./storage\"`).\n for (const clause of source.matchAll(/\\bexport\\s*\\{([^}]*)\\}/g)) {\n const names = clause[1].split(\",\").map(entry => {\n const parts = entry.split(/\\bas\\b/);\n return parts[parts.length - 1].trim();\n });\n if (names.includes(\"storageAuthorize\")) return true;\n }\n return false;\n}\n\n/**\n * Detect native code in the dependency closure.\n *\n * Walks declared runtime dependencies breadth-first through `node_modules`,\n * flagging anything with a `binding.gyp`, a prebuilt `.node` binary, or an\n * install script that builds one. The managed runtime cannot run these: a\n * binary compiled for one image will not load in another, and finding that out\n * at deploy time is far better than in a crash loop.\n *\n * The walk is bounded. A dependency graph can be enormous, and this is a\n * heuristic gate whose false negatives are caught at deploy time anyway.\n */\nexport function detectNativeDependencies(\n projectRoot: string,\n declared: Record<string, string>,\n limit = 2000\n): NativeDependency[] {\n const found: NativeDependency[] = [];\n const seen = new Set<string>();\n const queue = Object.keys(declared);\n let visited = 0;\n\n const searchRoots = [\n path.join(projectRoot, \"node_modules\"),\n path.join(projectRoot, \"backend\", \"node_modules\"),\n path.join(projectRoot, \"config\", \"node_modules\")\n ].filter(dir => fs.existsSync(dir));\n\n while (queue.length > 0 && visited < limit) {\n const name = queue.shift()!;\n if (seen.has(name)) continue;\n seen.add(name);\n visited++;\n\n if (KNOWN_NATIVE_PACKAGES.has(name)) {\n found.push({ name,\nreason: \"known native module\" });\n continue;\n }\n\n const packageDir = searchRoots\n .map(root => path.join(root, ...name.split(\"/\")))\n .find(dir => fs.existsSync(path.join(dir, \"package.json\")));\n\n if (!packageDir) continue;\n\n let pkg: {\n dependencies?: Record<string, string>;\n scripts?: Record<string, string>;\n gypfile?: boolean;\n };\n try {\n pkg = JSON.parse(fs.readFileSync(path.join(packageDir, \"package.json\"), \"utf8\"));\n } catch {\n continue;\n }\n\n if (pkg.gypfile || fs.existsSync(path.join(packageDir, \"binding.gyp\"))) {\n found.push({ name,\nreason: \"builds a native addon (binding.gyp)\" });\n continue;\n }\n\n const install = `${pkg.scripts?.install ?? \"\"} ${pkg.scripts?.preinstall ?? \"\"} ${pkg.scripts?.postinstall ?? \"\"}`;\n if (/node-gyp|prebuild|node-pre-gyp|cmake-js/.test(install)) {\n found.push({ name,\nreason: \"install script compiles native code\" });\n continue;\n }\n\n if (hasNodeBinary(packageDir)) {\n found.push({ name,\nreason: \"ships a prebuilt .node binary\" });\n continue;\n }\n\n for (const dep of Object.keys(pkg.dependencies ?? {})) {\n if (!seen.has(dep)) queue.push(dep);\n }\n }\n\n return found;\n}\n\n/** Shallow scan for `.node` binaries — deep enough for the usual `build/Release`. */\nfunction hasNodeBinary(dir: string, depth = 0): boolean {\n if (depth > 3) return false;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return false;\n }\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith(\".node\")) return true;\n if (entry.isDirectory() && entry.name !== \"node_modules\" && entry.name !== \".bin\") {\n if (hasNodeBinary(path.join(dir, entry.name), depth + 1)) return true;\n }\n }\n return false;\n}\n\n/**\n * Whether a dependency name resolves to a package *inside this repository* — a\n * workspace package rather than a registry one.\n *\n * The bundle's declared deps are installed with `npm install` from the public\n * registry beside the bundle at boot. A workspace package is not there, so\n * declaring it guarantees a boot-time install failure. The most common case is\n * the standard `config` package: the backend depends on it by name, but it is\n * *carried in the bundle* (as `entry.config`), so it must never also be an npm\n * dependency. Projects often express this as a `workspace:` range — caught\n * separately — but a plain `\"*\"` against a workspace symlink is just as common\n * and looks like a registry range, so the symlink is what actually settles it.\n *\n * Detection: the installed `node_modules/<name>` is a symlink whose real path is\n * inside the project and not within a pnpm virtual store (`.pnpm`). That is\n * exactly a workspace link and nothing else.\n */\nfunction resolvesToWorkspacePackage(projectRoot: string, name: string): boolean {\n // Resolve the root's own symlinks too: on macOS a temp/checkout path under\n // `/var/...` realpaths to `/private/var/...`, so comparing a realpath'd link\n // target against a non-realpath'd root would never match.\n let realRoot: string;\n try {\n realRoot = fs.realpathSync(projectRoot);\n } catch {\n realRoot = projectRoot;\n }\n\n for (const base of [projectRoot, path.join(projectRoot, \"backend\"), path.join(projectRoot, \"config\")]) {\n const link = path.join(base, \"node_modules\", name);\n try {\n // A workspace link is a *symlink*; a normal (non-pnpm) registry\n // install is a real directory inside node_modules, which would also\n // sit \"inside the repo\" — so the symlink is what separates the two.\n if (!fs.lstatSync(link).isSymbolicLink()) continue;\n const real = fs.realpathSync(link);\n const insideRepo = real.startsWith(realRoot + path.sep);\n // pnpm links registry packages into its virtual store; those live\n // under node_modules/.pnpm and are not workspace packages.\n const inStore = real.includes(`${path.sep}.pnpm${path.sep}`)\n || real.includes(`${path.sep}node_modules${path.sep}`);\n if (insideRepo && !inStore) return true;\n } catch {\n // No such entry, broken link, or race: let it be declared.\n }\n }\n return false;\n}\n\n/**\n * Collect the runtime dependencies a bundle needs installed beside it.\n *\n * Packages the runtime image already provides are excluded — reinstalling a\n * second copy of the server next to the one running the process is at best\n * wasted space and at worst a version conflict. Workspace packages are excluded\n * too: they are not on the registry the runtime installs from, and the project's\n * own config package already travels inside the bundle.\n */\nexport function collectDeclaredDependencies(projectRoot: string): Record<string, string> {\n const declared: Record<string, string> = {};\n\n for (const relative of [\"backend/package.json\", \"config/package.json\", \"package.json\"]) {\n const file = path.join(projectRoot, relative);\n if (!fs.existsSync(file)) continue;\n try {\n const pkg = JSON.parse(fs.readFileSync(file, \"utf8\")) as {\n dependencies?: Record<string, string>;\n };\n for (const [name, version] of Object.entries(pkg.dependencies ?? {})) {\n if (RUNTIME_PROVIDED.has(name)) continue;\n // A workspace protocol means nothing outside this repository.\n if (typeof version === \"string\" && version.startsWith(\"workspace:\")) continue;\n // A plain range that nonetheless resolves to an in-repo workspace\n // package (e.g. `\"config\": \"*\"` symlinked to `../../config`) —\n // the runtime cannot install it from the registry.\n if (resolvesToWorkspacePackage(projectRoot, name)) continue;\n declared[name] = version;\n }\n } catch {\n // Unparseable package.json: nothing to declare from it.\n }\n }\n\n return declared;\n}\n\n/**\n * Rewrite relative import specifiers in emitted JavaScript so Node can resolve them.\n *\n * TypeScript deliberately does not touch specifiers: `moduleResolution: \"bundler\"`\n * lets a project write `from \"./posts\"` or `from \"./collections\"`, and TypeScript\n * emits them unchanged on the assumption that a bundler will finish the job.\n * Nothing bundles a Rebase bundle — the runtime imports these files directly with\n * Node's ESM loader, which requires a full path with an extension and refuses\n * directory imports outright.\n *\n * Without this, adopting the bundle would mean asking every project written in\n * the (extremely common) extensionless style to rewrite all of its imports. The\n * rewrite is mechanical and verifiable: only relative specifiers are touched, and\n * only when the target file actually exists on disk.\n */\nexport function normalizeEsmSpecifiers(outDir: string): { rewritten: number; unresolved: string[] } {\n const unresolved: string[] = [];\n let rewritten = 0;\n\n // The specifier of a static import/export, a bare side-effect import, or a\n // dynamic import. Emitted output is not minified, so these forms are stable.\n const SPECIFIER = /(\\bfrom\\s*|\\bimport\\s*\\(\\s*|\\bimport\\s+)([\"'])(\\.[^\"']*)\\2/g;\n\n const walk = (dir: string): void => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\") continue;\n walk(full);\n } else if (entry.isFile() && entry.name.endsWith(\".js\")) {\n rewriteFile(full);\n }\n }\n };\n\n const rewriteFile = (file: string): void => {\n const original = fs.readFileSync(file, \"utf8\");\n const dir = path.dirname(file);\n\n const updated = original.replace(SPECIFIER, (match, prefix, quote, specifier) => {\n // Already resolvable: has a real extension.\n if (/\\.(js|mjs|cjs|json|node)$/.test(specifier)) return match;\n\n const target = path.resolve(dir, specifier);\n\n if (fs.existsSync(`${target}.js`)) {\n rewritten++;\n return `${prefix}${quote}${specifier}.js${quote}`;\n }\n if (fs.existsSync(path.join(target, \"index.js\"))) {\n rewritten++;\n const suffix = specifier.endsWith(\"/\") ? \"index.js\" : \"/index.js\";\n return `${prefix}${quote}${specifier}${suffix}${quote}`;\n }\n\n // A `.ts` extension written explicitly in source becomes `.js` on disk.\n if (specifier.endsWith(\".ts\") && fs.existsSync(`${target.slice(0, -3)}.js`)) {\n rewritten++;\n return `${prefix}${quote}${specifier.slice(0, -3)}.js${quote}`;\n }\n\n unresolved.push(`${path.basename(file)} → ${specifier}`);\n return match;\n });\n\n if (updated !== original) {\n fs.writeFileSync(file, updated, \"utf8\");\n }\n };\n\n if (fs.existsSync(outDir)) walk(outDir);\n return { rewritten,\nunresolved };\n}\n\n/**\n * Remove a previous build so stale output cannot masquerade as current.\n *\n * The containment check matters because this is a recursive force-delete of a\n * path that came from a command-line flag: `rebase build --out ../..` would\n * otherwise erase the parent of the project. The manifest's own paths are\n * checked the same way; a flag deserves no less.\n */\nfunction cleanOutDir(projectRoot: string, outDir: string): void {\n const relative = path.relative(projectRoot, outDir);\n if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(\n `Refusing to build into \"${outDir}\": the output directory must be inside the project.`\n );\n }\n\n if (fs.existsSync(outDir)) {\n fs.rmSync(outDir, { recursive: true,\nforce: true });\n }\n fs.mkdirSync(outDir, { recursive: true });\n}\n\n/**\n * Regenerate the Drizzle schema from the collections.\n *\n * Delegated to the database driver's own CLI — the same code `rebase schema\n * generate` runs — so there is one implementation of what a schema is. When no\n * driver is resolvable the build continues with a warning rather than failing:\n * a `baas` project has no schema to generate, and a project mid-install should\n * get a clear message rather than a hard stop.\n */\nasync function regenerateSchema(\n projectRoot: string,\n configDir: string,\n options: BuildBundleOptions\n): Promise<void> {\n const backendDir = path.join(projectRoot, \"backend\");\n if (!fs.existsSync(backendDir)) return;\n\n const plugin = getActiveBackendPlugin(backendDir);\n const script = plugin ? resolvePluginCliScript(backendDir, plugin) : null;\n if (!script) {\n log(options, chalk.dim(\" (no database driver found — skipping schema generation)\"));\n return;\n }\n\n const runner = script.endsWith(\".ts\") ? resolveTsx(projectRoot) : \"node\";\n if (!runner) {\n log(options, chalk.dim(\" (tsx not installed — skipping schema generation)\"));\n return;\n }\n\n const collectionsPath = path.join(\"..\", configDir, \"collections\");\n try {\n await execa(\n runner,\n [script, \"schema\", \"generate\", \"--collections\", collectionsPath],\n { cwd: backendDir,\nstdio: \"pipe\" }\n );\n log(options, chalk.dim(\" regenerated database schema from collections\"));\n } catch (err) {\n // A schema that cannot be generated means the bundle would carry a stale\n // one, and a stale schema is how a deploy quietly writes to the wrong\n // columns. Fail rather than ship it.\n const detail = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Schema generation failed, so the bundle was not written.\\n${detail}\\n` +\n \"Run `rebase schema generate` to see the full output, or pass --skip-schema \" +\n \"if the committed schema is deliberately hand-maintained.\"\n );\n }\n}\n\n/**\n * A hand-written server entrypoint that a bundle does not use.\n *\n * `rebase dev` runs `backend/src/index.ts` whenever a project has one, so for\n * the whole of local development that file *is* the server and every route\n * written in it works. A bundle has no entrypoint of its own: the runtime boots\n * the bundle and mounts what the manifest points at — the config package,\n * functions, crons and the schema. The file is not compiled, not shipped, and\n * never imported.\n *\n * Nothing said so. A project with custom routes in its entrypoint built clean,\n * deployed green, and answered 404 on every one of them, with the file still\n * sitting in the repository looking exactly like the server.\n *\n * A project that means to keep its own entrypoint declares the app as\n * `\"type\": \"custom\"`, which builds the repository's Dockerfile instead — which\n * is what {@link synthesizeManifest} already infers for a manifest-less repo\n * carrying one. The warning names that route rather than implying the file is\n * a mistake.\n */\nexport function findUnusedServerEntry(projectRoot: string, functionsDir: string): string | undefined {\n // A project that relocated its functions keeps the entrypoint beside them,\n // so the second candidate is derived rather than only the default known.\n const candidates = [\n path.join(\"backend\", \"src\", \"index.ts\"),\n path.join(path.dirname(functionsDir), \"src\", \"index.ts\")\n ];\n\n const found = candidates.find(candidate => fs.existsSync(path.join(projectRoot, candidate)));\n return found ? found.split(path.sep).join(\"/\") : undefined;\n}\n\n/**\n * Compile and assemble a bundle.\n */\nexport async function buildBundle(options: BuildBundleOptions): Promise<BuildBundleResult> {\n const { projectRoot, app, appName } = options;\n const paths = resolveBackendPaths(app);\n const outDir = path.resolve(projectRoot, options.outDir ?? DEFAULT_BUNDLE_DIR);\n\n const includes: string[] = [];\n const addIfExists = (relative: string, pattern: string): void => {\n if (fs.existsSync(path.join(projectRoot, relative))) includes.push(pattern);\n };\n\n if (paths.mode === \"cms\") {\n addIfExists(paths.config, `${paths.config}/**/*.ts`);\n }\n addIfExists(paths.functions, `${paths.functions}/**/*.ts`);\n addIfExists(paths.crons, `${paths.crons}/**/*.ts`);\n if (fs.existsSync(path.join(projectRoot, paths.schema))) {\n includes.push(paths.schema);\n }\n\n if (includes.length === 0) {\n throw new Error(\n `Nothing to build for app \"${appName}\". Expected a config directory at ` +\n `\"${paths.config}\" or functions at \"${paths.functions}\".`\n );\n }\n\n // Regenerate the Drizzle schema from the collections first.\n //\n // The template's backend build did this, so a project moving to the bundle\n // flow would otherwise silently ship whatever `schema.generated.ts` happened\n // to be on disk — stale by exactly the edits just made.\n if (paths.mode === \"cms\" && options.skipSchema !== true) {\n await regenerateSchema(projectRoot, paths.config, options);\n }\n\n // Say out loud what this build is NOT going to include. See\n // `findUnusedServerEntry` for why silence here was expensive.\n const unusedEntry = findUnusedServerEntry(projectRoot, paths.functions);\n if (unusedEntry) {\n const parts = [\n ...(paths.mode === \"cms\" ? [`${paths.config}/`] : []),\n `${paths.functions}/`,\n \"the schema\"\n ];\n const compiled = `${parts.slice(0, -1).join(\", \")} and ${parts[parts.length - 1]}`;\n console.log(chalk.yellow(` ⚠ ${unusedEntry} is not the bundle's entry point — it is not compiled or shipped.`));\n console.log(chalk.dim(` The runtime boots the bundle itself and mounts ${compiled}.`));\n console.log(chalk.dim(` Routes defined there will not exist once deployed: move them to ${paths.functions}/,`));\n console.log(chalk.dim(` or declare this app as \"type\": \"custom\" in rebase.json to keep your own entrypoint.`));\n }\n\n log(options, chalk.dim(` compiling ${includes.length} source group(s) → ${path.relative(projectRoot, outDir)}/`));\n\n cleanOutDir(projectRoot, outDir);\n const tsconfigPath = await writeBundleTsconfig(projectRoot, outDir, includes, options.skipTypeCheck === true);\n\n const tsc = resolveLocalBin(projectRoot, \"tsc\");\n if (!tsc) {\n throw new Error(\n \"TypeScript is not installed in this project. Run your package manager's install first.\"\n );\n }\n\n try {\n await execa(tsc, [\"-p\", tsconfigPath], { cwd: projectRoot,\nstdio: \"inherit\" });\n } catch {\n throw new Error(\"TypeScript compilation failed — the bundle was not written.\");\n }\n\n // Node resolves these files directly, so their specifiers must be complete.\n const normalized = normalizeEsmSpecifiers(outDir);\n if (normalized.rewritten > 0) {\n log(options, chalk.dim(` resolved ${normalized.rewritten} relative import(s) for Node ESM`));\n }\n if (normalized.unresolved.length > 0) {\n console.log(chalk.yellow(\n ` ⚠ ${normalized.unresolved.length} import(s) could not be resolved to a file:`\n ));\n for (const item of normalized.unresolved.slice(0, 5)) {\n console.log(chalk.dim(` ${item}`));\n }\n if (normalized.unresolved.length > 5) {\n console.log(chalk.dim(` … and ${normalized.unresolved.length - 5} more`));\n }\n }\n\n // ── Inspect what was produced ────────────────────────────────────────────\n const compiledConfigDir = path.join(outDir, paths.config);\n const compiledCollectionsDir = path.join(compiledConfigDir, \"collections\");\n\n let collections: CollectionConfig[] = [];\n if (paths.mode === \"cms\") {\n collections = await loadSourceCollections(path.join(projectRoot, paths.config, \"collections\"));\n if (collections.length === 0) {\n throw new Error(\n \"No collections were found in \" +\n `${path.join(paths.config, \"collections\")}. ` +\n \"A cms-mode project must define at least one collection.\"\n );\n }\n if (!fs.existsSync(compiledCollectionsDir)) {\n throw new Error(\n \"Compilation produced no collections directory at \" +\n `${path.relative(projectRoot, compiledCollectionsDir)}.`\n );\n }\n }\n\n const declared = collectDeclaredDependencies(projectRoot);\n const nativeModules = detectNativeDependencies(projectRoot, declared);\n const declaresStorageAuthorize = detectStorageAuthorize(path.join(outDir, paths.config));\n\n const schemaOut = paths.schema.replace(/\\.ts$/, \".js\");\n const relative = (target: string): string | undefined =>\n fs.existsSync(path.join(outDir, target)) ? target : undefined;\n\n const manifest: RebaseBundleManifest = {\n bundleFormat: BUNDLE_FORMAT_VERSION,\n runtime: {\n range: options.runtimeRange,\n builtAgainst: resolveServerVersion(projectRoot),\n contract: RUNTIME_CONTRACT_VERSION\n },\n // A `baas` build genuinely does not know the schema — collections are\n // introspected from the live database at boot. Recording a version here\n // would stamp the hash of an empty list, and the runtime would then\n // serve that as the identity of whatever it actually found. Empty means\n // \"ask the runtime\", which is the honest answer.\n schemaVersion: paths.mode === \"baas\" ? \"\" : computeSchemaVersion(collections),\n app: appName,\n mode: paths.mode,\n entry: {\n config: paths.mode === \"cms\" ? relative(paths.config) : undefined,\n collections: paths.mode === \"cms\" ? relative(path.join(paths.config, \"collections\")) : undefined,\n functions: relative(paths.functions),\n crons: relative(paths.crons),\n schema: relative(schemaOut),\n usersCollection: paths.mode === \"cms\"\n ? relative(path.join(paths.config, `${paths.usersCollection}.js`))\n : undefined\n },\n collections: collections\n .map(collection => collection.slug)\n .filter((slug): slug is string => Boolean(slug))\n .sort(),\n hooks: {\n native: nativeModules.length > 0,\n nativeModules: nativeModules.length > 0 ? nativeModules : undefined\n },\n storage: { authorize: declaresStorageAuthorize },\n deps: { declared },\n build: {\n cli: resolveCliVersion(),\n node: process.versions.node.split(\".\")[0],\n createdAt: new Date().toISOString()\n }\n };\n\n fs.writeFileSync(\n path.join(outDir, \"manifest.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n \"utf8\"\n );\n\n // A package.json beside the bundle lets a deployment install exactly the\n // dependencies the project declared, with no access to the repository.\n fs.writeFileSync(\n path.join(outDir, \"package.json\"),\n `${JSON.stringify({\n name: \"rebase-bundle\",\n private: true,\n type: \"module\",\n dependencies: declared\n }, null, 2)}\\n`,\n \"utf8\"\n );\n\n return { outDir,\nmanifest,\ncollectionCount: collections.length };\n}\n\n/**\n * Package a built static app (a `static` or bundled-`admin` app) into a bundle.\n *\n * A static bundle is the counterpart to a backend bundle: the same shape, the\n * same runtime image runs it, but its manifest says `mode: \"static\"` and it\n * carries only the built assets under `static/`. That is what lets a frontend or\n * admin app be its own deployable, scalable unit rather than something baked into\n * the backend container.\n *\n * `assetsDir` is the app's built output (e.g. `frontend/dist`), already produced\n * by its own build command. This copies it into the bundle and writes the\n * manifest — no compilation, no dependency closure (a static bundle installs\n * nothing at boot).\n */\n/**\n * Fold a built static app into a backend bundle, so one runtime serves both.\n *\n * ## Why this exists\n *\n * A managed tenant runs one pod, and `bootFromBundle` on the backend path already\n * knows how to serve a SPA — it looks for `entry.static` and mounts `serveSPA`\n * last, behind `REBASE_SERVE_STATIC`. What was missing was anything putting the\n * assets there.\n *\n * The consequence was not subtle. A project whose custom image served its website\n * at `/` and its API at `/api` — the shape the scaffolded template produces — lost\n * the website the moment it moved to the managed runtime: the API answered\n * perfectly and every page 404'd. Managed could not be a drop-in replacement for\n * custom while the frontend simply vanished.\n *\n * Folding restores parity with the container it replaces, which is the only\n * honest baseline. It is deliberately the FIRST implementation and not the last:\n * a static app on its own bucket behind a CDN is better for cache behaviour and\n * lets the frontend deploy independently. But that needs infrastructure that does\n * not exist yet, and \"your site is gone\" is not an acceptable state to leave a\n * project in while it gets built.\n *\n * The trade it makes, stated plainly: frontend and backend now deploy together\n * and the bundle carries the built assets. For a project that was shipping both\n * in one image already, that is exactly what it had.\n */\nexport function foldStaticIntoBundle(options: {\n /** The backend bundle directory, already written. */\n bundleDir: string;\n /** Directory of built frontend assets (the static app's `output`). */\n assetsDir: string;\n}): { fileCount: number } {\n const { bundleDir, assetsDir } = options;\n const manifestPath = path.join(bundleDir, \"manifest.json\");\n if (!fs.existsSync(manifestPath)) {\n throw new Error(`No manifest at ${manifestPath} — build the backend bundle first.`);\n }\n if (!fs.existsSync(assetsDir)) {\n throw new Error(`No built assets at ${assetsDir}.`);\n }\n\n const staticOut = path.join(bundleDir, \"static\");\n fs.rmSync(staticOut, { recursive: true, force: true });\n fs.mkdirSync(staticOut, { recursive: true });\n fs.cpSync(assetsDir, staticOut, { recursive: true });\n\n let fileCount = 0;\n const count = (dir: string): void => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) count(path.join(dir, entry.name));\n else fileCount++;\n }\n };\n count(staticOut);\n\n // Record it, because the runtime finds the assets through the manifest —\n // not by guessing a directory name.\n const manifest = JSON.parse(fs.readFileSync(manifestPath, \"utf8\")) as RebaseBundleManifest;\n manifest.entry = { ...manifest.entry, static: \"static\" };\n fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\n\n return { fileCount };\n}\n\nexport function buildStaticBundle(options: {\n projectRoot: string;\n appName: string;\n assetsDir: string;\n outDir: string;\n runtimeRange: string;\n}): { outDir: string; manifest: RebaseBundleManifest; fileCount: number } {\n const { projectRoot, appName, assetsDir, outDir, runtimeRange } = options;\n\n cleanOutDir(projectRoot, outDir);\n\n const staticOut = path.join(outDir, \"static\");\n fs.mkdirSync(staticOut, { recursive: true });\n fs.cpSync(assetsDir, staticOut, { recursive: true });\n\n let fileCount = 0;\n const count = (dir: string): void => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) count(path.join(dir, entry.name));\n else fileCount++;\n }\n };\n count(staticOut);\n\n const manifest: RebaseBundleManifest = {\n bundleFormat: BUNDLE_FORMAT_VERSION,\n runtime: {\n range: runtimeRange,\n builtAgainst: resolveServerVersion(projectRoot),\n contract: RUNTIME_CONTRACT_VERSION\n },\n // A static app has no collections and therefore no schema contract.\n schemaVersion: \"\",\n app: appName,\n mode: \"static\",\n entry: { static: \"static\" },\n hooks: { native: false },\n // Nothing to install beside a static bundle — it is just files.\n deps: { declared: {} },\n build: {\n cli: resolveCliVersion(),\n node: process.versions.node.split(\".\")[0],\n createdAt: new Date().toISOString()\n }\n };\n\n fs.writeFileSync(\n path.join(outDir, \"manifest.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n \"utf8\"\n );\n // An empty package.json keeps the runtime's boot-time install a clean no-op.\n fs.writeFileSync(\n path.join(outDir, \"package.json\"),\n `${JSON.stringify({ name: \"rebase-bundle\", private: true, type: \"module\", dependencies: {} }, null, 2)}\\n`,\n \"utf8\"\n );\n\n return { outDir, manifest, fileCount };\n}\n\n/**\n * Which files in a collections directory are collections.\n *\n * Mirrors the runtime loader's rules exactly, and must keep mirroring them: the\n * set of files counted here decides the schema version, and the runtime decides\n * what it serves the same way. A divergence would show up as a client that is\n * permanently \"out of date\" against a server that agrees with it.\n *\n * (`._*` guards macOS AppleDouble files, which look like sources and are not.)\n */\nfunction isCollectionSourceFile(name: string): boolean {\n if (name.startsWith(\".\")) return false;\n if (name.includes(\".test.\") || name.includes(\".spec.\")) return false;\n if (name.endsWith(\".d.ts\")) return false;\n if (name === \"index.ts\" || name === \"index.js\") return false;\n return name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Load collections from **source**, for hashing and for the manifest's slug list.\n *\n * Deliberately not the compiled output. A compiled bundle imports its\n * dependencies from beside itself — that is the whole point of shipping a\n * `package.json` with it — but at build time nothing has been installed there\n * yet, and under pnpm the project's own `node_modules` lives one directory per\n * package, so the emitted files genuinely cannot resolve their imports until\n * they are deployed.\n *\n * Reading source costs nothing in fidelity: compilation erases types, it does\n * not change the values a collection module exports, so the hash is the same\n * either way.\n */\nasync function loadSourceCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n if (!fs.existsSync(collectionsDir)) return [];\n\n const { createJiti } = await import(\"jiti\") as {\n createJiti: (filename: string, options?: Record<string, unknown>) => {\n import: (id: string) => Promise<unknown>;\n };\n };\n const jiti = createJiti(path.join(collectionsDir, \"index.ts\"), {\n interopDefault: true,\n esmResolve: true\n });\n\n const files = fs.readdirSync(collectionsDir)\n .filter(isCollectionSourceFile)\n .sort();\n\n const collections: CollectionConfig[] = [];\n const failures: string[] = [];\n\n for (const file of files) {\n try {\n const mod = await jiti.import(path.join(collectionsDir, file)) as\n { default?: CollectionConfig } | CollectionConfig;\n const collection = (mod as { default?: CollectionConfig }).default\n ?? (mod as CollectionConfig);\n if (collection && typeof collection === \"object\" && \"slug\" in collection) {\n collections.push(collection);\n } else {\n failures.push(`${file}: no default-exported collection`);\n }\n } catch (err) {\n failures.push(`${file}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Could not read ${failures.length} collection file(s):\\n` +\n failures.map(f => ` • ${f}`).join(\"\\n\")\n );\n }\n\n return collections;\n}\n\n/** The `@rebasepro/server` version the project resolves — what it was built against. */\nfunction resolveServerVersion(projectRoot: string): string {\n const candidates = [\n path.join(projectRoot, \"node_modules\", \"@rebasepro\", \"server\", \"package.json\"),\n path.join(projectRoot, \"backend\", \"node_modules\", \"@rebasepro\", \"server\", \"package.json\")\n ];\n for (const candidate of candidates) {\n if (!fs.existsSync(candidate)) continue;\n try {\n return (JSON.parse(fs.readFileSync(candidate, \"utf8\")) as { version: string }).version;\n } catch {\n // fall through\n }\n }\n return \"unknown\";\n}\n\nfunction resolveCliVersion(): string {\n try {\n const here = path.dirname(new URL(import.meta.url).pathname);\n let dir = here;\n for (let i = 0; i < 5; i++) {\n const candidate = path.join(dir, \"package.json\");\n if (fs.existsSync(candidate)) {\n const pkg = JSON.parse(fs.readFileSync(candidate, \"utf8\")) as {\n name?: string;\n version?: string;\n };\n if (pkg.name === \"@rebasepro/cli\" && pkg.version) return pkg.version;\n }\n dir = path.dirname(dir);\n }\n } catch {\n // Version is informational; an unknown value must not fail a build.\n }\n return \"unknown\";\n}\n","/**\n * Folding a project's frontend into its backend bundle.\n *\n * Shared by `rebase build` and `rebase cloud deploy` deliberately. It lived in\n * the build *command* first, and `deploy` rebuilds the bundle itself — so a\n * deploy silently produced a bundle without the frontend, packed 164 KB where\n * 39 MB was expected, and the site 404'd on the managed runtime exactly as if\n * folding had never been written. Two callers building the same artefact must\n * share the step that completes it.\n *\n * Why fold at all: `bootFromBundle` already serves a SPA from `entry.static`\n * behind `REBASE_SERVE_STATIC` (default on). A managed tenant runs one pod, so\n * putting the built site in the bundle gives it the shape a custom container\n * already had — site at `/`, API at `/api` — which is the only honest baseline\n * for calling the managed runtime a drop-in replacement.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { foldStaticIntoBundle } from \"./bundle\";\n\n/** The apps section of a project manifest, as much of it as folding needs. */\nexport interface FoldableManifest {\n apps?: Record<string, { type?: string; build?: string; output?: string }>;\n}\n\nexport interface FoldOptions {\n projectRoot: string;\n manifest: FoldableManifest;\n /** The backend bundle directory, already written. */\n bundleDir: string;\n /** Skip running the app's own build command; fold what is already built. */\n skipBuild?: boolean;\n log?: (message: string) => void;\n}\n\nexport interface FoldOutcome {\n appName: string;\n fileCount: number;\n}\n\n/**\n * Which static app, if any, should be served by the backend.\n *\n * Exactly one `static` app is folded. With several, folding would have to choose,\n * and silently picking one of two websites is worse than doing nothing — so it\n * declines and names what it saw. Pure, so the decision is testable without a\n * filesystem.\n */\nexport function selectFoldableApp(manifest: FoldableManifest): {\n app?: { name: string; build?: string; output?: string };\n /** Why nothing will be folded, when that is the answer. */\n reason?: string;\n} {\n const statics = Object.entries(manifest.apps ?? {})\n .filter(([, app]) => app?.type === \"static\")\n .map(([name, app]) => ({ name, build: app?.build, output: app?.output }));\n\n if (statics.length === 0) return {};\n if (statics.length > 1) {\n return {\n reason:\n `${statics.length} static apps (${statics.map(s => s.name).join(\", \")}) — none folded in. ` +\n \"Pick one to serve from the backend, or host them separately.\"\n };\n }\n const only = statics[0];\n if (!only.output) {\n return { reason: `\"${only.name}\" declares no output directory — not folded in.` };\n }\n return { app: only };\n}\n\n/**\n * Build the project's frontend and fold it into the backend bundle.\n *\n * Throws rather than exiting, so the caller decides whether a missing frontend\n * should fail its command — a `build` may reasonably want to stop, and so should\n * a deploy, but that is not this function's call to make.\n */\nexport async function foldFrontendIntoBundle(options: FoldOptions): Promise<FoldOutcome | null> {\n const { projectRoot, manifest, bundleDir, skipBuild } = options;\n const log = options.log ?? ((m: string) => console.log(m));\n\n const { app, reason } = selectFoldableApp(manifest);\n if (reason) {\n log(chalk.yellow(` ⚠ ${reason}`));\n return null;\n }\n if (!app) return null;\n\n if (app.build && !skipBuild) {\n await execa(app.build, { cwd: projectRoot, stdio: \"inherit\", shell: true });\n }\n\n const assetsDir = path.join(projectRoot, app.output as string);\n if (!fs.existsSync(assetsDir)) {\n // Exited 0 and produced nothing where the manifest says it should.\n // Folding that ships an empty site, which from the outside is\n // indistinguishable from a broken deploy.\n throw new Error(\n `\"${app.name}\" declared output \"${app.output}\" does not exist after building — ` +\n \"the bundle would ship without a frontend.\"\n );\n }\n\n const { fileCount } = foldStaticIntoBundle({ bundleDir, assetsDir });\n return { appName: app.name, fileCount };\n}\n","/**\n * CLI command: rebase build [app...]\n *\n * Builds the apps a repository declares in `rebase.json`.\n *\n * For a `backend` app this produces a **bundle** — compiled collections,\n * functions and schema plus a manifest — which is the artifact the runtime\n * loads. For `static` and bundled `admin` apps it runs the declared build\n * command and reports where the output landed.\n *\n * A project with no manifest, or one whose backend has been ejected to its own\n * entrypoint, falls back to the previous behaviour: run every workspace's own\n * `build` script. Nothing that built before stops building.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport type { RebaseAppConfig, RebaseStaticAppConfig, RebaseAdminAppConfig } from \"@rebasepro/types\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { buildableApps, findBackendApp, loadManifest, ManifestError } from \"../manifest\";\nimport { buildBundle, buildStaticBundle, DEFAULT_BUNDLE_DIR } from \"../bundle\";\nimport { foldFrontendIntoBundle } from \"../fold-static\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase build\")} — build the apps declared in rebase.json\n\n${chalk.bold(\"Usage\")}\n rebase build [app...] Build the named apps (default: all)\n\n${chalk.bold(\"Options\")}\n --out <dir> Bundle output directory (default: ${DEFAULT_BUNDLE_DIR})\n --skip-type-check Compile without type checking (faster; use for iteration only)\n --skip-schema Do not regenerate the database schema from collections\n --legacy Run every workspace's own build script instead\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase build Build every app in this repository\n rebase build backend Build only the backend bundle\n rebase build web Build only the \"web\" static app\n`.trim());\n}\n\nexport async function buildCommand(rawArgs: string[] = []): Promise<void> {\n const args = arg(\n {\n \"--out\": String,\n \"--skip-type-check\": Boolean,\n \"--skip-schema\": Boolean,\n /* Do not fold the frontend into the backend bundle. For a project\n that publishes its frontend elsewhere and does not want the assets\n travelling with its API. */\n \"--no-static\": Boolean,\n /* Fold assets that are already built, without re-running the app's\n build command — for a CI job that built the frontend in an earlier\n step. */\n \"--skip-static-build\": Boolean,\n \"--legacy\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n },\n { argv: rawArgs.slice(3), permissive: true }\n );\n\n if (args[\"--help\"]) {\n printHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n\n if (args[\"--legacy\"]) {\n await runWorkspaceBuilds(projectRoot);\n return;\n }\n\n let loaded;\n try {\n loaded = loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.red(` ${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n\n const { manifest, source } = loaded;\n const requested = args._.filter(a => !a.startsWith(\"-\"));\n\n let targets = buildableApps(manifest);\n if (requested.length > 0) {\n const known = new Set(targets.map(t => t.name));\n const unknown = requested.filter(name => !known.has(name));\n if (unknown.length > 0) {\n console.error(chalk.red(`✗ Unknown app(s): ${unknown.join(\", \")}`));\n console.error(chalk.dim(` This repository declares: ${targets.map(t => t.name).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n targets = targets.filter(t => requested.includes(t.name));\n }\n\n if (targets.length === 0) {\n console.log(chalk.yellow(\"No buildable apps declared. Nothing to do.\"));\n return;\n }\n\n // An ejected backend owns its own build; the workspace scripts are the only\n // thing that knows how to run it.\n const backend = findBackendApp(manifest);\n if (!backend && source === \"synthesized\") {\n console.log(chalk.dim(\"No rebase.json found — building workspace packages.\\n\"));\n await runWorkspaceBuilds(projectRoot);\n return;\n }\n\n console.log(`${chalk.bold(\"Rebase\")} — building ${targets.length} app(s)\\n`);\n\n for (const { name, app } of targets) {\n console.log(chalk.cyan(`▸ ${name}`) + chalk.dim(` (${app.type})`));\n\n if (app.type === \"backend\") {\n const result = await buildBundle({\n projectRoot,\n appName: name,\n app,\n outDir: args[\"--out\"],\n runtimeRange: manifest.runtime,\n skipTypeCheck: args[\"--skip-type-check\"],\n skipSchema: args[\"--skip-schema\"]\n });\n const rel = path.relative(projectRoot, result.outDir);\n console.log(chalk.green(` ✓ bundle → ${rel}/`));\n console.log(chalk.dim(` ${result.collectionCount} collection(s), schema ${result.manifest.schemaVersion}`));\n if (result.manifest.hooks.native) {\n const names = (result.manifest.hooks.nativeModules ?? []).map(m => m.name).join(\", \");\n console.log(chalk.yellow(` ⚠ native dependencies detected: ${names}`));\n console.log(chalk.dim(\" These cannot run on the managed runtime. See `rebase doctor`.\"));\n }\n\n /* Fold the project's frontend into the backend bundle, so ONE runtime\n serves the site at `/` and the API at `/api` — the shape the\n scaffolded template produces and the shape a custom container\n already had.\n\n Without this, moving a project to the managed runtime silently\n removed its website: the API answered perfectly and every page\n 404'd, because the managed pod runs the backend bundle and nothing\n else. Parity with the container being replaced is the only honest\n baseline for calling managed a drop-in.\n\n `--no-static` opts out, for a project that publishes its frontend\n somewhere else and does not want the assets in its bundle. */\n if (!args[\"--no-static\"]) {\n const folded = await foldFrontendIntoBundle({\n projectRoot,\n manifest,\n bundleDir: result.outDir,\n skipBuild: args[\"--skip-static-build\"] === true,\n log: (m) => console.log(m)\n }).catch((err: unknown) => {\n console.error(chalk.red(` ✗ ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n });\n if (folded) {\n console.log(\n chalk.green(` ✓ ${folded.appName} folded in`) +\n chalk.dim(` (${folded.fileCount} file(s) → served at /)`)\n );\n }\n }\n } else if (app.type === \"static\" || app.type === \"admin\") {\n await buildAssetApp(projectRoot, name, app, manifest.runtime, args[\"--out\"]);\n } else if (app.type === \"custom\") {\n console.log(chalk.dim(\" custom container — built at deploy time from its Dockerfile\"));\n }\n\n console.log(\"\");\n }\n\n console.log(chalk.green(\"✓ Build complete.\"));\n}\n\n/**\n * Build a static or bundled-admin app and package it into a static bundle.\n *\n * Runs the app's own build command, checks it produced the declared output, then\n * packages that output into a `static`-mode bundle — the same deployable shape as\n * a backend bundle, so a frontend or admin app deploys through the identical\n * path and runs on the identical image, just serving files instead of an API.\n */\nasync function buildAssetApp(\n projectRoot: string,\n name: string,\n app: RebaseAppConfig,\n runtimeRange: string,\n outOverride?: string\n): Promise<void> {\n const asset = app as RebaseStaticAppConfig | RebaseAdminAppConfig;\n\n if (app.type === \"admin\" && (app as RebaseAdminAppConfig).mode !== \"bundled\") {\n console.log(chalk.dim(\" hosted admin panel — nothing to build\"));\n return;\n }\n\n if (!asset.build) {\n console.log(chalk.dim(\" no build command declared — skipping\"));\n return;\n }\n\n try {\n await execa(asset.build, {\n cwd: projectRoot,\n stdio: \"inherit\",\n shell: true\n });\n } catch {\n console.error(chalk.red(` ✗ build command failed for \"${name}\"`));\n process.exit(1);\n }\n\n if (!asset.output) {\n console.log(chalk.yellow(\" no output directory declared — built, but nothing to bundle\"));\n return;\n }\n\n const outputPath = path.join(projectRoot, asset.output);\n if (!fs.existsSync(outputPath)) {\n // The command exited 0 but produced nothing where the manifest says it\n // should. Bundling that would ship an empty site.\n console.error(chalk.red(` ✗ declared output \"${asset.output}\" does not exist after building`));\n process.exit(1);\n }\n\n // Per-app bundle directory, so a project's several static apps do not clobber\n // one another or the backend's `dist-bundle`.\n const outDir = outOverride\n ? path.resolve(process.cwd(), outOverride)\n : path.join(projectRoot, `dist-bundle-${name}`);\n const result = buildStaticBundle({ projectRoot, appName: name, assetsDir: outputPath, outDir, runtimeRange });\n const rel = path.relative(projectRoot, result.outDir);\n console.log(chalk.green(` ✓ static bundle → ${rel}/`) + chalk.dim(` (${result.fileCount} file(s))`));\n}\n\n/** The pre-manifest behaviour: build every workspace package. */\nasync function runWorkspaceBuilds(projectRoot: string): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const buildCmd = cmds.runAll(\"build\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Building all workspaces with ${chalk.cyan(pm)}...\\n`);\n\n try {\n await execa(buildCmd[0], buildCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\"\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Build failed.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase start\n *\n * Runs a built bundle through the Rebase runtime — the same path the official\n * container image takes, so what you test locally is what a deployment runs.\n *\n * When there is no bundle (an ejected backend, or a project that has not adopted\n * `rebase.json`) this falls back to the backend workspace's own `start` script,\n * which is what such a project has always used.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { DEFAULT_BUNDLE_DIR } from \"../bundle\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase start\")} — run a built bundle\n\n${chalk.bold(\"Usage\")}\n rebase start [options]\n\n${chalk.bold(\"Options\")}\n --bundle <dir> Bundle directory (default: ${DEFAULT_BUNDLE_DIR})\n --legacy Run the backend workspace's own start script\n -h, --help Show this help\n\nBuild first with ${chalk.cyan(\"rebase build\")}.\n`.trim());\n}\n\nexport async function startCommand(rawArgs: string[] = []): Promise<void> {\n const args = arg(\n {\n \"--bundle\": String,\n \"--legacy\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n },\n { argv: rawArgs.slice(3), permissive: true }\n );\n\n if (args[\"--help\"]) {\n printHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n const bundleDir = path.resolve(projectRoot, args[\"--bundle\"] ?? DEFAULT_BUNDLE_DIR);\n const hasBundle = fs.existsSync(path.join(bundleDir, \"manifest.json\"));\n\n if (args[\"--legacy\"] || !hasBundle) {\n if (!args[\"--legacy\"] && !hasBundle) {\n console.log(chalk.dim(\n `No bundle at ${path.relative(projectRoot, bundleDir)}/ — ` +\n \"starting the backend workspace instead.\\n\"\n ));\n }\n await startWorkspaceBackend(projectRoot, env);\n return;\n }\n\n ensureBundleDependencies(projectRoot, bundleDir);\n\n console.log(`${chalk.bold(\"Rebase\")} — starting runtime from ${chalk.cyan(path.relative(projectRoot, bundleDir))}/\\n`);\n\n // Loaded in-process rather than spawned: the runtime is a library here, so\n // signals, exit codes and stdio need no forwarding, and there is one less\n // process between the developer and a stack trace.\n if (envFile && fs.existsSync(envFile)) {\n const dotenv = await import(\"dotenv\");\n dotenv.config({ path: envFile });\n }\n\n process.env.REBASE_BUNDLE = bundleDir;\n\n try {\n const { runFromBundle } = await import(\"@rebasepro/server\");\n await runFromBundle({ bundleDir });\n } catch (err) {\n console.error(chalk.red(\"\\n✗ Failed to start the runtime.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Make a bundle's imports resolvable for a local run.\n *\n * Node resolves a module by walking up from the *importing file*, so compiled\n * code sitting in `dist-bundle/` no longer sees the per-package `node_modules`\n * its source could: pnpm and npm both install a workspace package's\n * dependencies inside that package, and the bundle is not inside any of them.\n *\n * A deployment solves this by installing the bundle's own `package.json` beside\n * it — that is what the generated `package.json` is for. Locally, doing a second\n * install to run code whose dependencies are already on disk would be wasteful,\n * so this links what is already there instead.\n *\n * Only ever created when absent, and only under the bundle directory, so a real\n * install always wins and nothing here is ever uploaded (`rebase build` cleans\n * the directory and never writes this).\n */\nfunction ensureBundleDependencies(projectRoot: string, bundleDir: string): void {\n const target = path.join(bundleDir, \"node_modules\");\n if (fs.existsSync(target)) return;\n\n // Later sources fill gaps left by earlier ones; the backend's tree wins\n // because it holds the server and driver the runtime itself needs.\n const sources = [\"backend/node_modules\", \"config/node_modules\", \"node_modules\"]\n .map(relative => path.join(projectRoot, relative))\n .filter(dir => fs.existsSync(dir));\n\n if (sources.length === 0) return;\n\n let linked = 0;\n fs.mkdirSync(target, { recursive: true });\n\n const linkInto = (sourceDir: string, targetDir: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(sourceDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \".bin\" || entry.name.startsWith(\".\")) continue;\n const from = path.join(sourceDir, entry.name);\n const to = path.join(targetDir, entry.name);\n\n // A scope is a directory of packages, not a package — merge into it\n // so `@a/one` from one tree and `@a/two` from another both resolve.\n if (entry.name.startsWith(\"@\") && entry.isDirectory()) {\n fs.mkdirSync(to, { recursive: true });\n linkInto(from, to);\n continue;\n }\n\n if (fs.existsSync(to)) continue;\n try {\n fs.symlinkSync(fs.realpathSync(from), to, \"junction\");\n linked++;\n } catch {\n // A package that cannot be linked simply stays unresolved, and\n // the runtime will say so by name if it actually needed it.\n }\n }\n };\n\n for (const source of sources) linkInto(source, target);\n\n if (linked > 0) {\n console.log(chalk.dim(\n ` linked ${linked} package(s) into the bundle for this local run\\n` +\n \" (a deployment installs the bundle's package.json instead)\\n\"\n ));\n }\n}\n\nasync function startWorkspaceBackend(projectRoot: string, env: Record<string, string>): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase auth <action>\n *\n * Subcommands:\n * reset-password — Reset a user's password\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { spawn } from \"child_process\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n findEnvFile,\n resolveTsx\n} from \"../utils/project\";\n\nexport async function authCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printAuthHelp();\n return;\n }\n\n switch (subcommand) {\n case \"reset-password\":\n await resetPassword(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown auth command: ${subcommand}`));\n console.log(\"\");\n printAuthHelp();\n process.exit(1);\n }\n}\n\nasync function resetPassword(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--email\": String,\n \"--password\": String,\n \"-e\": \"--email\",\n \"-p\": \"--password\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase auth reset-password\"\n permissive: true\n }\n );\n\n // Support both --email flag and positional args\n const email = args[\"--email\"] || args._[0];\n const newPassword = args[\"--password\"] || args._[1];\n\n if (!email) {\n console.error(chalk.red(\"✗ Email is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase auth reset-password <email> [new-password]\"));\n console.log(chalk.gray(\" rebase auth reset-password --email user@example.com --password NewPass123!\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n\n // 1. Try API-first reset\n let envServiceKey: string | undefined;\n const envFile = findEnvFile(projectRoot);\n if (envFile && fs.existsSync(envFile)) {\n try {\n const envContent = fs.readFileSync(envFile, \"utf8\");\n const match = envContent.match(/^\\s*REBASE_SERVICE_KEY\\s*=\\s*['\"]?(.*?)['\"]?\\s*$/m);\n if (match && match[1]) {\n envServiceKey = match[1];\n }\n } catch {\n // Ignore\n }\n }\n\n let baseUrl = process.env.REBASE_BASE_URL;\n let serviceKey = process.env.REBASE_SERVICE_KEY || envServiceKey;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as Record<string, unknown>;\n if (state && typeof state === \"object\") {\n if (typeof state.baseUrl === \"string\" && !baseUrl) {\n baseUrl = state.baseUrl;\n }\n if (typeof state.serviceKey === \"string\" && !serviceKey) {\n serviceKey = state.serviceKey;\n }\n }\n } catch {\n // Ignore\n }\n }\n\n const devUrlPath = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(devUrlPath) && !baseUrl) {\n try {\n baseUrl = fs.readFileSync(devUrlPath, \"utf8\").trim();\n } catch {\n // Ignore\n }\n }\n\n if (baseUrl && serviceKey) {\n console.log(\"Trying API-first reset via running backend...\");\n try {\n const finalPass = newPassword || \"NewPassword123!\";\n const cleanBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n const searchUrl = `${cleanBaseUrl}/api/admin/users?search=${encodeURIComponent(email)}&limit=1`;\n const searchRes = await fetch(searchUrl, {\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\"\n }\n });\n if (!searchRes.ok) {\n throw new Error(`Failed to list users: ${searchRes.statusText}`);\n }\n const searchData = await searchRes.json() as unknown;\n if (!searchData || typeof searchData !== \"object\") {\n throw new Error(\"Invalid response format from user search API.\");\n }\n \n let userId: string | undefined;\n if (Array.isArray(searchData)) {\n const firstUser = searchData[0] as unknown;\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n } else if (\"users\" in searchData && Array.isArray((searchData as { users: unknown }).users)) {\n const users = (searchData as { users: unknown[] }).users;\n const firstUser = users[0];\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n }\n\n if (!userId) {\n throw new Error(`User not found with email: ${email}`);\n }\n\n const resetUrl = `${cleanBaseUrl}/api/admin/users/${userId}/reset-password`;\n const resetRes = await fetch(resetUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({ password: finalPass })\n });\n\n if (!resetRes.ok) {\n const errText = await resetRes.text();\n throw new Error(`Password reset endpoint failed: ${errText || resetRes.statusText}`);\n }\n\n console.log(\"API reset successful.\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (via API)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n console.log(` ${chalk.gray(\"Password:\")} ${finalPass}`);\n console.log(\"\");\n return;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.warn(chalk.yellow(\"API reset failed, falling back to direct database update...\"));\n console.warn(chalk.gray(` Details: ${errMsg}`));\n }\n }\n\n // 2. Direct-DB Fallback\n const backendDir = requireBackendDir(projectRoot);\n const tsxBin = resolveTsx(projectRoot);\n\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n\n try {\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env.REBASE_RESET_EMAIL = email;\n env.REBASE_RESET_PASSWORD = newPassword || \"NewPassword123!\";\n env.REBASE_ENV_FILE_PATH = envFile || path.join(projectRoot, \".env\");\n\n const scriptContent = `\nimport { createPostgresDatabaseConnection } from \"@rebasepro/server-postgres\";\nimport { hashPassword } from \"@rebasepro/server\";\nimport { eq } from \"drizzle-orm\";\nimport * as dotenv from \"dotenv\";\nimport path from \"path\";\nimport fs from \"fs\";\n\ndotenv.config({ path: process.env.REBASE_ENV_FILE_PATH });\n\nconst email = process.env.REBASE_RESET_EMAIL!;\nconst newPassword = process.env.REBASE_RESET_PASSWORD!;\n\nasync function resetPassword() {\n const { db } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);\n const hash = await hashPassword(newPassword);\n\n let usersTable;\n try {\n const schemaPath = path.resolve(\"./src/schema.generated.ts\");\n if (fs.existsSync(schemaPath)) {\n const schema = await import(\"file://\" + schemaPath);\n usersTable = schema.users || schema.tables?.users;\n }\n } catch (e) {\n // ignore and fallback\n }\n\n if (!usersTable) {\n const pgServer = await import(\"@rebasepro/server-postgres\");\n usersTable = pgServer.users;\n }\n\n const passwordHashKey = (usersTable.passwordHash || \"passwordHash\" in usersTable) ? \"passwordHash\" : \"password_hash\";\n\n const result = await db.update(usersTable)\n .set({ [passwordHashKey]: hash })\n .where(eq(usersTable.email, email))\n .returning({\n id: usersTable.id,\n email: usersTable.email\n });\n\n if (result.length > 0) {\n console.log(\"✅ Password reset for: \" + result[0].email);\n ${!newPassword ? 'console.log(\" New password: \" + newPassword);' : \"\"}\n } else {\n console.log(\"✗ User not found: \" + email);\n }\n process.exit(0);\n}\n\nresetPassword().catch(console.error);\n`;\n\n const tmpScriptPath = path.join(backendDir, \".tmp-reset-password.ts\");\n fs.writeFileSync(tmpScriptPath, scriptContent, \"utf-8\");\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (Direct DB Fallback)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n if (newPassword) {\n console.log(` ${chalk.gray(\"Password:\")} ${\"*\".repeat(newPassword.length)}`);\n }\n console.log(\"\");\n\n const child = spawn(tsxBin, [tmpScriptPath], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n\n return new Promise((resolve) => {\n child.on(\"close\", (code) => {\n // Clean up temp script\n try { fs.unlinkSync(tmpScriptPath); } catch { /* ignore */ }\n if (code !== 0) {\n process.exit(code ?? 1);\n }\n resolve();\n });\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction printAuthHelp() {\n console.log(`\n${chalk.bold(\"rebase auth\")} — Authentication management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase auth ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"reset-password\")} Reset a user's password\n\n${chalk.green.bold(\"reset-password Options\")}\n ${chalk.blue(\"--email, -e\")} User's email address\n ${chalk.blue(\"--password, -p\")} New password (default: NewPassword123!)\n\n${chalk.green.bold(\"Examples\")}\n rebase auth reset-password user@example.com\n rebase auth reset-password --email user@example.com --password MyNewPass!\n`);\n}\n","/**\n * CLI command: rebase doctor\n *\n * Detects three-way schema drift between collection definitions,\n * the generated Drizzle schema, and the live PostgreSQL database.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function doctorCommand(rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport inquirer from \"inquirer\";\nimport { createRequire } from \"module\";\n\nconst require = createRequire(import.meta.url);\n\n/** Supported agent environments and their target directories. */\nconst AGENTS = {\n cursor: {\n label: \"Cursor\",\n detectDir: \".cursor\",\n targetDir: \".cursor/rules\",\n /** Cursor uses .mdc files (Markdown with Context). */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.mdc`,\n content\n })\n },\n claude: {\n label: \"Claude Code\",\n detectDir: \".claude\",\n targetDir: \".claude/skills\",\n /** Claude Code uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n },\n windsurf: {\n label: \"Windsurf\",\n detectDir: \".windsurf\",\n targetDir: \".windsurf/rules\",\n /** Windsurf uses plain .md files. */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.md`,\n content\n })\n },\n gemini: {\n label: \"Gemini CLI / Antigravity\",\n detectDir: \".agents\",\n targetDir: \".agents/skills\",\n /** Gemini uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n }\n} as const;\n\ntype AgentKey = keyof typeof AGENTS;\n\n/**\n * Resolve the path to the skills directory from @rebasepro/agent-skills.\n * Works in both workspace (symlink) and published (real files) layouts.\n */\nfunction getSkillsSourceDir(): string {\n const pkgJsonPath = require.resolve(\"@rebasepro/agent-skills/package.json\");\n const pkgRoot = path.dirname(pkgJsonPath);\n const skillsDir = path.join(pkgRoot, \"skills\");\n\n if (!fs.existsSync(skillsDir)) {\n throw new Error(\n `Skills directory not found at ${skillsDir}. ` +\n `Make sure @rebasepro/agent-skills is installed.`\n );\n }\n\n return skillsDir;\n}\n\n/** Read all skill directories and return their names + content. */\nfunction loadSkills(skillsDir: string): Array<{ name: string; content: string }> {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n const skills: Array<{ name: string; content: string }> = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillMdPath = path.join(skillsDir, entry.name, \"SKILL.md\");\n if (!fs.existsSync(skillMdPath)) continue;\n skills.push({\n name: entry.name,\n content: fs.readFileSync(skillMdPath, \"utf-8\")\n });\n }\n\n return skills;\n}\n\n/** Detect which agent environments already exist in the project. */\nfunction detectAgents(projectDir: string): AgentKey[] {\n const detected: AgentKey[] = [];\n for (const [key, agent] of Object.entries(AGENTS)) {\n if (fs.existsSync(path.join(projectDir, agent.detectDir))) {\n detected.push(key as AgentKey);\n }\n }\n return detected;\n}\n\n/** Install skills for a specific agent into the project directory. */\nfunction installForAgent(\n agentKey: AgentKey,\n skills: Array<{ name: string; content: string }>,\n projectDir: string\n): number {\n const agent = AGENTS[agentKey];\n const targetBase = path.join(projectDir, agent.targetDir);\n\n // Ensure the target directory exists\n fs.mkdirSync(targetBase, { recursive: true });\n\n let count = 0;\n for (const skill of skills) {\n const { fileName, content } = agent.transformFile(skill.name, skill.content);\n const targetPath = path.join(targetBase, fileName);\n\n // Ensure parent directory exists (for subdirectory-based formats)\n fs.mkdirSync(path.dirname(targetPath), { recursive: true });\n fs.writeFileSync(targetPath, content, \"utf-8\");\n count++;\n }\n\n return count;\n}\n\nexport async function skillsCommand(subcommand: string | undefined, rawArgs: string[]) {\n switch (subcommand) {\n case \"install\":\n await skillsInstall(rawArgs);\n break;\n case \"--help\":\n case undefined:\n printSkillsHelp();\n break;\n default:\n console.error(chalk.red(`Unknown skills subcommand: ${subcommand}`));\n console.log(\"\");\n printSkillsHelp();\n process.exit(1);\n }\n}\n\n/**\n * Agents named explicitly on the command line, e.g. `--agent claude --agent cursor`\n * (also accepts a comma-separated list). Returns null when none were given.\n */\nfunction parseAgentFlags(rawArgs: string[]): AgentKey[] | null {\n const requested: string[] = [];\n for (let i = 0; i < rawArgs.length; i++) {\n if (rawArgs[i] !== \"--agent\" && rawArgs[i] !== \"-a\") continue;\n const value = rawArgs[i + 1];\n if (value && !value.startsWith(\"-\")) {\n requested.push(...value.split(\",\").map(v => v.trim()).filter(Boolean));\n }\n }\n if (requested.length === 0) return null;\n\n const valid = Object.keys(AGENTS);\n const unknown = requested.filter(a => !valid.includes(a));\n if (unknown.length > 0) {\n console.error(chalk.red(`Unknown agent(s): ${unknown.join(\", \")}. Available: ${valid.join(\", \")}`));\n process.exit(1);\n }\n return requested as AgentKey[];\n}\n\nasync function skillsInstall(rawArgs: string[] = []) {\n const projectDir = process.cwd();\n\n // 1. Load skills from @rebasepro/agent-skills\n let skillsDir: string;\n try {\n skillsDir = getSkillsSourceDir();\n } catch (err) {\n console.error(`${chalk.red.bold(\"ERROR\")} ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n const skills = loadSkills(skillsDir);\n if (skills.length === 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} No skills found in ${skillsDir}`);\n process.exit(1);\n }\n\n // 2. Explicit --agent wins; otherwise detect existing agent environments\n let agents = parseAgentFlags(rawArgs) ?? detectAgents(projectDir);\n\n // 3. If none detected, ask the user\n if (agents.length === 0) {\n // A scaffolded project ships `.cursorrules` / `CLAUDE.md` files but none\n // of the *directories* detectAgents looks for, so a fresh project always\n // lands here. On a non-TTY that used to abort with a raw ExitPromptError.\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"Cannot prompt: this is a non-interactive terminal (no TTY).\"));\n console.error(chalk.yellow(` Name the agents explicitly, e.g. rebase skills install --agent ${Object.keys(AGENTS)[0]}`));\n console.error(chalk.gray(` Available: ${Object.keys(AGENTS).join(\", \")}`));\n process.exit(1);\n }\n\n const choices = Object.entries(AGENTS).map(([key, agent]) => ({\n name: agent.label,\n value: key,\n checked: false\n }));\n\n const { selectedAgents } = await inquirer.prompt([{\n type: \"checkbox\",\n name: \"selectedAgents\",\n message: \"No AI agent configuration detected. Which agents do you use?\",\n choices,\n validate: (input: string[]) => {\n if (input.length === 0) return \"Please select at least one agent.\";\n return true;\n }\n }]);\n\n agents = selectedAgents as AgentKey[];\n }\n\n // 4. Install skills for each agent\n console.log(\"\");\n console.log(chalk.gray(` Found ${chalk.white(skills.length)} Rebase skills`));\n console.log(\"\");\n\n for (const agentKey of agents) {\n const agent = AGENTS[agentKey];\n const count = installForAgent(agentKey, skills, projectDir);\n console.log(` ${chalk.green(\"✓\")} ${chalk.bold(agent.label)} — ${count} skills installed to ${chalk.gray(agent.targetDir)}`);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Skills are project-local. Commit them to share with your team.\"));\n console.log(chalk.gray(\" Re-run this command anytime to update to the latest skills.\"));\n console.log(\"\");\n}\n\nfunction printSkillsHelp() {\n console.log(`\n${chalk.bold(\"rebase skills\")} — Manage AI agent skills\n\n${chalk.green.bold(\"Usage\")}\n rebase skills ${chalk.blue(\"<subcommand>\")}\n\n${chalk.green.bold(\"Subcommands\")}\n ${chalk.blue.bold(\"install\")} Install Rebase agent skills for your AI coding assistant\n Supports: Cursor, Claude Code, Windsurf, Gemini CLI, Antigravity\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--agent, -a\")} Agent(s) to install for, skipping detection and the prompt.\n Repeat the flag or pass a comma-separated list.\n Available: ${Object.keys(AGENTS).join(\", \")}\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.cyan(\"rebase skills install\")}\n ${chalk.cyan(\"rebase skills install --agent claude\")}\n ${chalk.cyan(\"rebase skills install --agent claude,cursor\")}\n`);\n}\n","/**\n * CLI command: rebase api-keys <action>\n *\n * Subcommands:\n * list — List all API keys (masked)\n * create — Create a new API key\n * revoke — Revoke an existing API key\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireProjectRoot,\n findEnvFile\n} from \"../utils/project\";\nimport fs from \"fs\";\nimport path from \"path\";\n\n/* ═══════════════════════════════════════════════════════════════\n Env helper — reads SERVICE_KEY and PORT from .env\n ═══════════════════════════════════════════════════════════════ */\n\nfunction loadEnv(projectRoot: string): Record<string, string> {\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = {};\n if (envFile && fs.existsSync(envFile)) {\n const content = fs.readFileSync(envFile, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const idx = trimmed.indexOf(\"=\");\n if (idx > 0) {\n const key = trimmed.slice(0, idx).trim();\n let value = trimmed.slice(idx + 1).trim();\n // Strip surrounding quotes\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n env[key] = value;\n }\n }\n }\n return env;\n}\n\nfunction resolveBaseUrl(env: Record<string, string>, projectRoot?: string): string {\n // An explicit override always wins.\n if (env.REBASE_BASE_URL) return env.REBASE_BASE_URL;\n\n // `rebase dev` runs on a derived per-project port, not the .env PORT, and\n // records the URL it actually bound. Without this, these commands default to\n // :3001 and report \"Is the Rebase server running?\" while it is running.\n if (projectRoot) {\n try {\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(urlFile)) {\n const devUrl = fs.readFileSync(urlFile, \"utf-8\").trim();\n if (devUrl) return devUrl;\n }\n } catch { /* fall through to the configured port */ }\n }\n\n const port = env.PORT || env.REBASE_PORT || \"3001\";\n return `http://localhost:${port}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Entry\n ═══════════════════════════════════════════════════════════════ */\n\nexport async function apiKeysCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printApiKeysHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listKeys(rawArgs);\n break;\n case \"create\":\n await createKey(rawArgs);\n break;\n case \"revoke\":\n await revokeKey(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown api-keys command: ${subcommand}`));\n console.log(\"\");\n printApiKeysHelp();\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list\n ═══════════════════════════════════════════════════════════════ */\n\nasync function listKeys(_rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n if (!res.ok) {\n const body = await res.text();\n console.error(chalk.red(`✗ Failed to list API keys: ${res.status} ${body}`));\n process.exit(1);\n }\n\n const { keys } = await res.json() as { keys: Array<{\n id: string; name: string; key_prefix: string;\n permissions: Array<{ collection: string; operations: string[] }>;\n rate_limit: number | null; revoked_at: string | null;\n expires_at: string | null; last_used_at: string | null;\n created_at: string;\n }>};\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 API Keys\"));\n console.log(\"\");\n\n if (keys.length === 0) {\n console.log(chalk.gray(\" No API keys found.\"));\n console.log(\"\");\n return;\n }\n\n for (const key of keys) {\n const status = key.revoked_at ? chalk.red(\"revoked\")\n : (key.expires_at && new Date(key.expires_at) < new Date()) ? chalk.yellow(\"expired\")\n : chalk.green(\"active\");\n\n const perms = key.permissions.map(p =>\n `${p.collection}(${p.operations.join(\",\")})`\n ).join(\", \");\n\n console.log(` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${status}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Permissions:\")} ${perms || \"none\"}`);\n console.log(` ${chalk.gray(\"Created:\")} ${new Date(key.created_at).toLocaleDateString()}`);\n if (key.last_used_at) {\n console.log(` ${chalk.gray(\"Last used:\")} ${new Date(key.last_used_at).toLocaleDateString()}`);\n }\n console.log(\"\");\n }\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n create\n ═══════════════════════════════════════════════════════════════ */\n\nasync function createKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--permissions\": String,\n \"--full-access\": Boolean,\n \"--admin\": Boolean,\n \"--rate-limit\": Number,\n \"--expires\": String,\n \"-n\": \"--name\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys create\"\n permissive: true\n }\n );\n\n const name = args[\"--name\"] || args._[0];\n const permissionsRaw = args[\"--permissions\"];\n\n if (!name) {\n console.error(chalk.red(\"✗ Name is required.\"));\n console.log(\"\");\n console.log(chalk.gray(' Usage: rebase api-keys create --name \"My Key\" --permissions \\'[{\"collection\":\"*\",\"operations\":[\"read\"]}]\\''));\n process.exit(1);\n }\n\n let permissions: Array<{ collection: string; operations: string[] }>;\n if (permissionsRaw) {\n try {\n permissions = JSON.parse(permissionsRaw);\n } catch {\n console.error(chalk.red(\"✗ Invalid --permissions JSON.\"));\n console.log(chalk.gray(' Example: \\'[{\"collection\":\"*\",\"operations\":[\"read\",\"write\"]}]\\''));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n } else if (args[\"--full-access\"]) {\n permissions = [{ collection: \"*\", operations: [\"read\", \"write\", \"delete\"] }];\n } else {\n // No silent full-access default: a \"scoped keys\" feature should not\n // hand out read/write/delete on every collection when the flag is\n // simply forgotten. Full access must be asked for by name.\n console.error(chalk.red(\"✗ Specify what the key may access: --permissions '<json>' or --full-access.\"));\n console.log(\"\");\n console.log(chalk.gray(' Scoped: rebase api-keys create -n \"Analytics\" --permissions \\'[{\"collection\":\"events\",\"operations\":[\"read\"]}]\\''));\n console.log(chalk.gray(' Functions: add {\"collection\":\"functions/<name>\",\"operations\":[\"write\"]} to invoke a custom function'));\n console.log(chalk.gray(' Storage: add {\"collection\":\"storage\",\"operations\":[\"read\",\"write\"]} for file storage'));\n console.log(chalk.gray(' Full access: rebase api-keys create -n \"CI\" --full-access'));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n\n let expires_at: string | null = null;\n const expiresFlag = args[\"--expires\"];\n if (expiresFlag) {\n const days: Record<string, number> = { \"7d\": 7, \"30d\": 30, \"90d\": 90, \"1y\": 365 };\n if (days[expiresFlag]) {\n expires_at = new Date(Date.now() + days[expiresFlag] * 86400000).toISOString();\n } else {\n const parsed = new Date(expiresFlag);\n if (isNaN(parsed.getTime())) {\n console.error(chalk.red(\"✗ Invalid --expires value. Use 7d, 30d, 90d, 1y, or an ISO date.\"));\n process.exit(1);\n }\n expires_at = parsed.toISOString();\n }\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const body: Record<string, unknown> = {\n name,\n permissions,\n admin: args[\"--admin\"] ?? false,\n rate_limit: args[\"--rate-limit\"] ?? null,\n expires_at\n };\n\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to create API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n const { key } = await res.json() as { key: { name: string; key: string; key_prefix: string; id: string } };\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key created successfully\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Name:\")} ${key.name}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Prefix:\")} ${key.key_prefix}`);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy your key now — it won't be shown again:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(key.key)}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n revoke\n ═══════════════════════════════════════════════════════════════ */\n\nasync function revokeKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--id\": String\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys revoke\"\n permissive: true\n }\n );\n\n const id = args[\"--id\"] || args._[0];\n\n if (!id) {\n console.error(chalk.red(\"✗ Key ID is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase api-keys revoke <key-id>\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys/${encodeURIComponent(id)}`, {\n method: \"DELETE\",\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to revoke API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key revoked successfully\"));\n console.log(` ${chalk.gray(\"ID:\")} ${id}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nfunction printApiKeysHelp() {\n console.log(`\n${chalk.bold(\"rebase api-keys\")} — Manage Service API Keys\n\n${chalk.green.bold(\"Usage\")}\n rebase api-keys ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List all API keys\n ${chalk.blue.bold(\"create\")} Create a new API key\n ${chalk.blue.bold(\"revoke\")} Revoke an API key\n\n${chalk.green.bold(\"create Options\")}\n ${chalk.blue(\"--name, -n\")} Key name ${chalk.gray(\"(required)\")}\n ${chalk.blue(\"--permissions\")} JSON array of permissions ${chalk.gray(\"(required unless --full-access)\")}\n ${chalk.gray('Collections by slug; custom functions as \"functions\" or \"functions/<name>\"')}\n ${chalk.blue(\"--full-access\")} Grant read/write/delete on every collection and function\n ${chalk.blue(\"--admin\")} Grant admin role (admin routes + RLS admin policies)\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window ${chalk.gray(\"(default: 1000)\")}\n ${chalk.blue(\"--expires\")} Expiration: 7d, 30d, 90d, 1y, or ISO date\n\n${chalk.green.bold(\"revoke Options\")}\n ${chalk.blue(\"--id\")} API key ID to revoke ${chalk.gray(\"(or positional arg)\")}\n\n${chalk.green.bold(\"Examples\")}\n rebase api-keys list\n rebase api-keys create --name \"Analytics\" --permissions '[{\"collection\":\"events\",\"operations\":[\"read\"]}]'\n rebase api-keys create -n \"Full Access\" --full-access --expires 90d\n rebase api-keys revoke abc123-def456\n`);\n}\n","/**\n * `rebase cloud` auth subcommands: login, logout, whoami.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n resolveCloudUrl,\n createCloudClient,\n requireClient,\n setCurrentContext,\n setContextOrg,\n getContextOrg,\n readLink,\n success,\n fail,\n keyValues,\n reportError\n} from \"./context\";\n\nexport async function loginCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--email\": String,\n\"--password\": String,\n\"-e\": \"--email\",\n\"-p\": \"--password\" },\n { argv: rawArgs.slice(3),\npermissive: true }\n );\n const url = resolveCloudUrl(rawArgs);\n\n console.log(\"\");\n console.log(` Signing in to ${chalk.cyan(url)}`);\n console.log(\"\");\n\n // Collect any missing credentials interactively.\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--email\"]) {\n prompts.push({ type: \"input\",\nname: \"email\",\nmessage: \"Email:\" });\n }\n if (!args[\"--password\"]) {\n prompts.push({ type: \"password\",\nname: \"password\",\nmessage: \"Password:\",\nmask: \"•\" });\n }\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const email = (args[\"--email\"] || (answers as { email?: string }).email || \"\").trim();\n const password = args[\"--password\"] || (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 keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"Active org\", getContextOrg(url)]\n ]);\n console.log(\"\");\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.\");\n }\n reportError(e, \"Login failed\");\n }\n}\n\nexport async function logoutCommand(rawArgs: string[]): Promise<void> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n if (!client.auth.getSession()) {\n console.log(\"\");\n console.log(chalk.gray(` Not logged in to ${url}.`));\n console.log(\"\");\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}\n\nexport async function whoamiCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const user = await client.auth.getUser();\n if (!user) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const link = readLink();\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 [\"Linked project\", link ? `${link.projectName ?? \"\"} (${link.projectId})`.trim() : undefined]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch session\");\n }\n}\n","/**\n * `rebase cloud` context subcommands: link, unlink, use, open.\n *\n * `link` associates the current directory with a cloud project by writing\n * `.rebase/cloud.json`; deploy/logs/status then operate on it with no flags.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n resolveCloudUrl,\n writeLink,\n removeLink,\n readLink,\n projectLinkPath,\n setContextOrg,\n getContextOrg,\n openUrl,\n success,\n fail,\n reportError\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.`);\n return;\n }\n\n if (base.protocol !== \"http:\" && base.protocol !== \"https:\") {\n fail(\"A project URL must be http or https.\");\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 console.log(chalk.yellow(`⚠ Could not reach ${probe}${detail ? ` (${detail})` : \"\"}.`));\n console.log(chalk.dim(\" Linking anyway — the server may not be running yet.\"));\n console.log(chalk.dim(\" It must be a Rebase backend of version 0.11 or newer.\"));\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 console.log(chalk.dim(` Written to ${projectLinkPath()}`));\n console.log(\"\");\n console.log(`Next: ${chalk.cyan(\"rebase generate-sdk --from link\")}`);\n void rawArgs;\n}\n\nexport async function linkCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(3),\npermissive: true });\n\n // A positional URL means \"this exact backend\", which needs no login and no\n // control plane. `rebase link https://api.example.com`\n const positional = args._.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 unknown as ProjectRow | undefined;\n if (!project) fail(`Project ${args[\"--project\"]} not found.`);\n } else {\n const org = getContextOrg(url);\n const projects = (await client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n limit: 100\n })).data as unknown as ProjectRow[];\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 );\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 unknown as Parameters<typeof inquirer.prompt>[0]);\n project = picked as ProjectRow;\n }\n\n if (!project) fail(\"No project selected.\");\n\n writeLink({\n url,\n projectId: String(project.id),\n slug: project.subdomain,\n projectName: project.name,\n orgId: project.organization !== undefined ? String(project.organization) : undefined\n });\n\n success(`Linked to ${chalk.bold(project.name ?? project.subdomain ?? \"\")}`);\n console.log(chalk.gray(` Wrote ${projectLinkPath()}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to link project\");\n }\n}\n\nexport function unlinkCommand(): void {\n const link = readLink();\n if (!link) {\n console.log(\"\");\n console.log(chalk.gray(\" This directory is not linked to a cloud project.\"));\n console.log(\"\");\n return;\n }\n removeLink();\n success(\"Unlinked from cloud project\");\n}\n\nexport async function selectOrgCommand(rawArgs: string[]): Promise<void> {\n // positionals after \"cloud\" are [use, <org>]; take the token after \"use\".\n const target = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\n const { client, url } = await requireClient(rawArgs);\n\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n slug?: string;\n }>;\n\n if (orgs.length === 0) fail(\"You are not a member of any organization.\");\n\n let chosen = target\n ? orgs.find((o) => String(o.id) === target || o.slug === target)\n : undefined;\n\n if (!chosen && !target) {\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 unknown as Parameters<typeof inquirer.prompt>[0]);\n chosen = picked;\n }\n\n if (!chosen) fail(`Organization \"${target}\" not found.`);\n\n setContextOrg(url, String(chosen.id));\n success(`Active organization set to ${chalk.bold(chosen.name ?? chosen.id)}`);\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 const url = resolveCloudUrl(rawArgs);\n const link = readLink();\n const target = link ? `${url}/projects/${link.projectId}` : url;\n openUrl(target);\n}\n","/**\n * `rebase cloud projects` — list / create / info / delete.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n getContextOrg,\n readLink,\n writeLink,\n colorStatus,\n keyValues,\n fetchTenantBaseDomain,\n projectHost,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\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 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) => res.data as unknown as ProjectRow[]),\n fetchTenantBaseDomain(client, url)\n ]);\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(chalk.gray(\" No projects yet. Create one with `rebase cloud projects create`.\"));\n console.log(\"\");\n return;\n }\n\n const linkedId = readLink()?.projectId;\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 } catch (e) {\n reportError(e, \"Failed to list projects\");\n }\n}\n\n/* ─── create ───────────────────────────────────────────────────── */\n\n/** Default region + VM size per provider (both are required on create). */\nfunction providerDefaults(provider: string): { region: string; vmSize: string } {\n switch (provider) {\n case \"gcp\":\n return { region: \"europe-west1\",\nvmSize: \"e2-small\" };\n case \"aws\":\n return { region: \"us-east-1\",\nvmSize: \"t3.small\" };\n default:\n return { region: \"nbg1\",\nvmSize: \"cx21\" };\n }\n}\n\nexport async function createProject(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--provider\": String,\n \"--region\": String,\n \"--vm-size\": String,\n \"--org\": String,\n \"--link\": Boolean,\n \"-n\": \"--name\"\n },\n { argv: rawArgs.slice(4),\npermissive: true }\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 );\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<Record<string, unknown>> = [];\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 as unknown as Parameters<typeof inquirer.prompt>[0])\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 provider = (args[\"--provider\"] || a.provider || \"hetzner\").trim();\n // region + vmSize are required by the control plane; default sensibly per\n // provider so a headless `projects create` needs only name + subdomain.\n const defaults = providerDefaults(provider);\n const region = (args[\"--region\"] || defaults.region).trim();\n const vmSize = (args[\"--vm-size\"] || defaults.vmSize).trim();\n\n if (!name || !subdomain) {\n fail(\"Name and subdomain are required.\");\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 );\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) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const created = (await client.data.collection(\"projects\").create({\n name,\n subdomain,\n gitRepoUrl,\n gitBranch,\n provider,\n region,\n vmSize,\n organization: org,\n createdById: user.uid,\n status: \"provisioning\"\n })) as unknown as ProjectRow;\n\n success(`Created project ${chalk.bold(name)}`);\n keyValues([\n [\"Slug\", String(created.subdomain ?? \"\")],\n [\"URL\", projectHost(created, await fetchTenantBaseDomain(client, url))],\n [\"Provider\", provider],\n [\"Branch\", gitBranch]\n ]);\n\n if (args[\"--link\"]) {\n writeLink({ url,\nprojectId: String(created.id),\nslug: created.subdomain,\nprojectName: name,\norgId: String(org) });\n console.log(chalk.gray(\" Linked this directory to the new project.\"));\n }\n console.log(\"\");\n console.log(chalk.gray(` Deploy it with: ${chalk.bold(`rebase cloud deploy --project ${created.subdomain ?? created.id}`)}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to create project\");\n }\n}\n\n/* ─── info ─────────────────────────────────────────────────────── */\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 unknown as ProjectRow | undefined;\n if (!p) fail(`Project ${projectRef} not found.`);\n\n const [db, lastDeploy, baseDomain] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url)\n ]);\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 [\"Last deploy\", lastDeploy ? `${colorStatus(lastDeploy.status)} · ${fmtDate(lastDeploy.createdAt)}` : \"never\"]\n ]);\n console.log(\"\");\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 args = arg({ \"--yes\": Boolean,\n\"-y\": \"--yes\" }, { argv: rawArgs.slice(2),\npermissive: true });\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.`);\n\n if (!args[\"--yes\"]) {\n const { confirmed } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirmed\",\n default: false,\n message: `Permanently delete project \"${p.name ?? projectRef}\" (${p.subdomain ?? projectRef})? This tears down its deployment.`\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n return;\n }\n }\n\n try {\n await client.data.collection(\"projects\").delete(projectId);\n success(`Deleted project ${chalk.bold(p.name ?? projectId)}`);\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 } from \"child_process\";\nimport type { RebaseBundleManifest } from \"@rebasepro/types\";\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 * Tar a built bundle into a gzipped archive.\n *\n * `node_modules` is excluded on purpose: the bundle ships a `package.json`, and\n * the managed runtime installs the declared dependencies at boot. Uploading an\n * installed `node_modules` would bloat the archive and could carry a\n * platform-specific build that will not run on the runtime image.\n */\nexport function packBundle(bundleDir: string, outPath: string): 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\", \"--exclude\", \"node_modules\", \"-C\", bundleDir, \".\"],\n { stdio: \"inherit\", env: { ...process.env, COPYFILE_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 * 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 */\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}): 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 };\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 .map(([name, value]) => ({ name, type: String(value?.type ?? \"custom\") }));\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}`, \"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 * `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 { spawn } from \"child_process\";\nimport {\n requireClient,\n resolveProjectRef,\n colorStatus,\n emit,\n isJsonMode,\n printJson,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\nimport { latestDeployment, fmtDate } from \"./projects\";\nimport { readBundleManifest, packBundle, uploadBundle, bundleDeployBody, declaredAppsFrom } from \"./bundle-deploy\";\nimport { buildBundle } from \"../../bundle\";\nimport { foldFrontendIntoBundle } from \"../../fold-static\";\nimport { loadManifest, findBackendApp } from \"../../manifest\";\nimport { requireProjectRoot } from \"../../utils/project\";\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 /** Whether the blocking deployment was triggered by THIS user. */\n mine?: boolean;\n}\n\nconst POLL_INTERVAL_MS = 1500;\nconst POLL_TIMEOUT_MS = 15 * 60 * 1000; // 15 min hard stop\n\n// Keep in sync with the control plane's build-context cap (deploy/upload\n// MAX_BYTES and the backend's maxBodySize). Checked before uploading so an\n// oversized context fails in milliseconds with a hint, not after the upload\n// with a bare 413.\nconst MAX_SOURCE_UPLOAD_BYTES = 100 * 1024 * 1024;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction run(cmd: string, cmdArgs: string[], cwd?: string, env?: NodeJS.ProcessEnv): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, cmdArgs, { cwd,\nenv: env ? { ...process.env, ...env } : undefined,\nstdio: [\"ignore\", \"ignore\", \"pipe\"] });\n let stderr = \"\";\n child.stderr.on(\"data\", (d) => (stderr += d.toString()));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => (code === 0 ? resolve() : reject(new Error(stderr || `${cmd} exited ${code}`))));\n });\n}\n\n/**\n * Package `sourceDir` into a gzipped tarball, honoring `.gitignore`/`.rebaseignore`\n * and always excluding `.git` and `node_modules`. Returns the temp archive path.\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 const tarArgs = [\"-czf\", tarPath, \"--exclude=.git\", \"--exclude=node_modules\"];\n for (const ignore of [\".gitignore\", \".rebaseignore\"]) {\n if (fs.existsSync(path.join(dir, ignore))) tarArgs.push(`--exclude-from=${ignore}`);\n }\n tarArgs.push(\".\");\n\n try {\n // COPYFILE_DISABLE: macOS bsdtar otherwise emits an AppleDouble sidecar\n // (`._foo.ts`) for every file carrying an xattr — and macOS stamps the\n // SIP-protected `com.apple.provenance` xattr routinely, so a stock\n // checkout ships `._*` binary junk that crashes schema generation in\n // the builder. GNU tar ignores the variable, so this is safe everywhere.\n await run(\"tar\", tarArgs, dir, { COPYFILE_DISABLE: \"1\" });\n } catch (e) {\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/** 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 console.log(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 without `node_modules`, uploads it, and triggers a\n * deploy carrying the manifest so the control plane 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 /** Compile without type checking, exactly as `rebase build` does. */\n skipTypeCheck?: boolean;\n}): Promise<void> {\n const { client, url, projectId, projectRef } = opts;\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 const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (!backend) {\n fail(\n \"This repository declares no backend app to deploy as a bundle.\",\n \"A managed deploy runs the backend; declare one in rebase.json, or deploy from the backend's repository.\"\n );\n }\n console.log(chalk.gray(\" Building bundle...\"));\n const result = await buildBundle({\n projectRoot,\n appName: backend!.name,\n app: backend!.app,\n runtimeRange: loaded.manifest.runtime,\n skipTypeCheck: opts.skipTypeCheck,\n log: (m: string) => console.log(chalk.gray(m))\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. */\n try {\n const folded = await foldFrontendIntoBundle({\n projectRoot,\n manifest: loaded.manifest as never,\n bundleDir,\n log: (m: string) => console.log(m)\n });\n if (folded) {\n console.log(chalk.gray(` folded ${folded.appName} in (${folded.fileCount} file(s), served at /)`));\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 const manifest = readBundleManifest(bundleDir);\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 const token = client.auth.getSession()?.accessToken;\n if (!token) fail(\"Not authenticated.\", \"Run `rebase cloud login`.\");\n\n let bundleId: string;\n try {\n await packBundle(bundleDir, tarPath);\n const sizeMb = (fs.statSync(tarPath).size / 1024 / 1024).toFixed(1);\n console.log(chalk.gray(` Uploading bundle (${sizeMb} MB)...`));\n bundleId = await uploadBundle(url, token!, 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 console.log(\"\");\n console.log(` 🚀 Triggering managed deployment for ${chalk.bold(projectRef)} (schema ${manifest.schemaVersion})...`);\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 declaredApps: ReturnType<typeof declaredAppsFrom> = [];\n try {\n declaredApps = declaredAppsFrom(loadManifest(process.cwd()).manifest as never);\n } catch {\n // A project with no readable rebase.json still deploys; it just cannot\n // describe its other apps.\n }\n\n const body = bundleDeployBody({ projectId, bundleId, manifest, message: opts.message, declaredApps });\n\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string | number };\n managed?: boolean;\n }>(\"deploy\", body);\n if (!res?.deployment?.id) fail(\"Control plane did not return a deployment id.\");\n if (isJsonMode()) {\n printJson({ success: true, deploymentId: String(res.deployment.id), managed: res.managed === true });\n } else {\n console.log(chalk.green(` ✓ Managed deploy started (deployment ${res.deployment.id}).`));\n console.log(chalk.gray(\" Track it with `rebase cloud logs` or in the console.\"));\n }\n } catch (e) {\n reportError(e, \"Managed deploy failed to start\");\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 `--force`\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/** What a `deploy` with nothing attached will build, in the words to print. */\nexport function planBareDeploy(\n project: DeployProjectRow | undefined,\n latest: DeploySourceRow | undefined,\n now: Date\n): BareDeployPlan {\n const projectRow = project as Record<string, unknown> | undefined;\n const deploymentRow = latest as Record<string, unknown> | undefined;\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, source: \"git\", lines: [`Building from git: ${repo}${branch ? ` (${branch})` : \"\"}.`] };\n }\n\n if (pick(deploymentRow, \"sourceRef\", \"source_ref\")) {\n const age = timeAgo((latest?.createdAt ?? latest?.created_at) as string | Date | undefined, now);\n return {\n managed,\n source: \"snapshot\",\n lines: [\n `Rebuilding the stored source archive${latest?.id !== undefined ? ` from deployment ${latest.id}` : \"\"}` +\n `${age ? `, uploaded ${age}` : \"\"}.`,\n \"This directory is NOT uploaded — pass `--source .` to build what is on disk.\"\n ]\n };\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/** The one sentence that says a source build undoes `runtimeMode: managed`. */\nfunction ejectWarning(projectRef: string): string {\n return `⚠ ${projectRef} runs on the managed runtime — a source build ejects it to a custom container.`;\n}\n\n/**\n * Read the two rows the preflight needs.\n *\n * Best effort by construction: a preflight that cannot read is a preflight that\n * says nothing, never a deploy that fails. The managed refusal rides on the same\n * read, so an unreadable project falls through to the old behaviour rather than\n * blocking a deploy on a lookup.\n */\nasync function readDeployContext(\n client: CloudClient,\n projectId: string\n): Promise<{ project?: DeployProjectRow; latest?: DeploySourceRow }> {\n try {\n const [project, latest] = await Promise.all([\n client.data.collection(\"projects\").findById(projectId),\n latestDeployment(client, projectId)\n ]);\n return {\n project: project as unknown as DeployProjectRow | undefined,\n latest: latest as unknown as DeploySourceRow | undefined\n };\n } catch {\n return {};\n }\n}\n\nexport async function deployCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--no-follow\": Boolean,\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/* Deploy a source build even for a project that runs on the managed\n runtime — an eject, done deliberately. See the refusal below. */\n\"--force\": Boolean,\n\"-m\": \"--message\" },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n // Managed bundle deploy: `deploy --bundle`. Builds the project into a bundle,\n // uploads it, and lets the control plane run the platform runtime with it —\n // the managed path. Mutually exclusive with `--source` (one is a source\n // build, the other is not).\n if (args[\"--bundle\"]) {\n if (args[\"--source\"]) {\n fail(\"--bundle and --source cannot be combined: one is a managed bundle, the other a source build.\");\n }\n await deployBundle({\n client,\n url,\n projectId,\n projectRef,\n bundleDir: args[\"--bundle-dir\"],\n message: args[\"--message\"],\n skipTypeCheck: args[\"--skip-type-check\"] === true\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, latest } = await readDeployContext(client, projectId);\n const plan = planBareDeploy(project, latest, new Date());\n\n if (!args[\"--source\"]) {\n if (plan.managed && args[\"--force\"] !== true) {\n fail(\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 \"Redeploy it with `rebase cloud deploy --bundle`. To eject on purpose, pass `--source .` \" +\n \"to build this directory, or `--force` to build what the control plane holds.\",\n \"managed_project\"\n );\n }\n if (!isJsonMode()) {\n console.log(\"\");\n if (plan.managed) console.log(chalk.yellow(` ${ejectWarning(projectRef)}`));\n for (const line of plan.lines) console.log(chalk.gray(` ${line}`));\n }\n } else if (plan.managed && !isJsonMode()) {\n // Explicit `--source` is a deliberate build, so it proceeds — but a\n // successful one rewrites `runtimeMode` to `custom` server-side, and\n // that is not something to discover from a runtime version going blank.\n console.log(\"\");\n console.log(chalk.yellow(` ${ejectWarning(projectRef)}`));\n console.log(chalk.gray(\" Use `rebase cloud deploy --bundle` to stay on managed.\"));\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 const token = client.auth.getSession()?.accessToken;\n if (!token) fail(\"Not authenticated.\", \"Run `rebase cloud login`.\");\n source = await uploadSource(url, token, projectId, tarPath);\n } finally {\n fs.rmSync(tarPath, { force: true });\n }\n }\n\n console.log(\"\");\n console.log(` 🚀 Triggering deployment for project ${chalk.bold(projectRef)}${source ? \" from uploaded source\" : \"\"}...`);\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 };\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string | number };\n deduplicated?: boolean;\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 };\n } catch (e) {\n triggered = resolveTriggerFailure(e);\n }\n const { deploymentId, deduplicated } = 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 },\n { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: false }\n );\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 const status = await streamBuildLogs(client, deploymentId, { quiet: isJsonMode() });\n emit(\n () => {},\n { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: true,\nstatus }\n );\n}\n\n/**\n * Turn a failed trigger into either a deployment to follow, or an exit.\n *\n * The 409 is the interesting one. A deploy trigger can reach the control plane\n * twice without anybody asking twice — the SDK transport replays a request once\n * after refreshing an expired token, and any lost response has the same effect\n * — so \"a deployment is already in progress\" was routinely describing the\n * deployment this very command had just created. With no id in the message the\n * only available reading was \"someone else is deploying, back off\", and the\n * build stream was lost either way.\n *\n * So: if the control plane says the blocking deployment is ours, we attach to\n * it. If it is not ours, we still name it, because \"which one, since when, from\n * where\" is the difference between an actionable refusal and a dead end.\n */\nfunction resolveTriggerFailure(e: unknown): { deploymentId: string; deduplicated: boolean } {\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 if (blocking?.id && blocking.mine) {\n return { deploymentId: String(blocking.id),\ndeduplicated: true };\n }\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` +\n `${blocking.triggerSource && blocking.triggerSource !== \"unknown\" ? `, triggered from the ${blocking.triggerSource}` : \"\"}` +\n `${blocking.createdAt ? ` at ${fmtDate(blocking.createdAt)}` : \"\"}.`\n : \"A deployment is already in progress for this project.\",\n blocking?.id\n ? `Follow it with \\`rebase cloud logs -f\\`, or stop it with \\`rebase cloud cancel ${blocking.id}\\`.`\n : \"Follow it with `rebase cloud logs -f`.\",\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 reportError(e, \"Failed to trigger deployment\");\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 */\nasync function streamBuildLogs(\n client: CloudClient,\n deploymentId: string,\n opts: { quiet?: boolean } = {}\n): Promise<string> {\n const quiet = opts.quiet === true;\n let printed = 0;\n const started = Date.now();\n\n for (;;) {\n let dep: Deployment | undefined;\n try {\n dep = (await client.data.collection(\"deployments\").findById(deploymentId)) as unknown as Deployment | undefined;\n } catch (e) {\n reportError(e, \"Failed to read deployment status\");\n }\n if (!dep) fail(`Deployment ${deploymentId} disappeared.`, undefined, \"not_found\");\n\n const logs = dep.logs ?? \"\";\n if (!quiet && logs.length > printed) {\n process.stdout.write(logs.slice(printed));\n }\n printed = logs.length;\n\n if (dep.status && dep.status !== \"deploying\") {\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\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 console.log(\"\");\n }\n return dep.status;\n }\n\n if (Date.now() - started > POLL_TIMEOUT_MS) {\n if (!quiet) console.log(\"\");\n fail(\n \"Timed out waiting for the build to finish.\",\n \"The deployment may still be running — check `rebase cloud logs`.\",\n \"timeout\"\n );\n }\n\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nexport async function logsCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--runtime\": Boolean,\n\"--follow\": Boolean,\n\"-f\": \"--follow\" },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client } = 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 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 } 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 try {\n const dep = (await latestDeployment(client, projectId)) as unknown as Deployment | undefined;\n if (!dep) {\n console.log(\"\");\n console.log(chalk.gray(\" No deployments yet for this project.\"));\n console.log(\"\");\n return;\n }\n\n console.log(\"\");\n console.log(chalk.bold(` 📄 Build logs — deployment ${dep.id}`) + ` ${colorStatus(dep.status)}`);\n console.log(\"\");\n\n if (args[\"--follow\"] && dep.status === \"deploying\") {\n // Hand off to the streamer, which prints from the top and tails live.\n await streamBuildLogs(client, String(dep.id));\n } else {\n console.log(dep.logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to fetch build logs\");\n }\n}\n","/**\n * `rebase cloud orgs` — list / create / members.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n getContextOrg,\n setContextOrg,\n colorStatus,\n success,\n fail,\n reportError\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}`);\n }\n}\n\nasync function listOrgs(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as OrgRow[];\n const active = getContextOrg(url);\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 console.log(chalk.gray(\" ● = active organization. Switch with `rebase cloud use <id>`.\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list organizations\");\n }\n}\n\nasync function createOrg(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--name\": String,\n\"--slug\": String,\n\"-n\": \"--name\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--name\"]) prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Organization name:\" });\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const name = (args[\"--name\"] || (answers as { name?: string }).name || \"\").trim();\n if (!name) fail(\"Organization name is required.\");\n const slug = (args[\"--slug\"] || slugify(name)).trim();\n\n try {\n const created = (await client.data.collection(\"organizations\").create({\n name,\n slug,\n createdAt: new Date().toISOString()\n })) as unknown as OrgRow;\n setContextOrg(url, String(created.id));\n success(`Created organization ${chalk.bold(name)} and set it active`);\n } catch (e) {\n reportError(e, \"Failed to create organization\");\n }\n}\n\nasync function listMembers(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n\n try {\n const members = (await client.data.collection(\"organization-members\").find({\n where: { organization: [\"==\", org] },\n limit: 200\n })).data as unknown as Array<{ id: string | number; userId?: string; role?: string }>;\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 } 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\nfunction printOrgsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud orgs\")} — Manage organizations\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List organizations you belong to\n ${chalk.blue.bold(\"create\")} Create a new organization ${chalk.gray(\"(--name, --slug)\")}\n ${chalk.blue.bold(\"members\")} List members of the active organization\n`);\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 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 displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface DatabaseRow {\n id: string | number;\n type?: string;\n connectionStatus?: string;\n useSshTunnel?: boolean;\n pitrEnabled?: boolean;\n}\n\ninterface BackupRow {\n filename: string;\n size?: number;\n createdAt?: string;\n type?: string;\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 \"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}`);\n }\n}\n\nasync function listDatabases(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const dbs = (await client.data.collection(\"databases\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data as unknown as DatabaseRow[];\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 } catch (e) {\n reportError(e, \"Failed to list databases\");\n }\n}\n\nasync function createDatabase(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--type\": String,\n\"--connection-string\": String,\n\"--project\": String,\n\"-p\": \"--project\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n let type = args[\"--type\"];\n if (!type) {\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 unknown 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 const { cs } = await inquirer.prompt([\n { type: \"input\",\nname: \"cs\",\nmessage: \"PostgreSQL connection string:\" }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n connectionString = (cs as string)?.trim();\n if (!connectionString) fail(\"A connection string is required for bring-your-own databases.\");\n }\n\n try {\n const created = (await client.data.collection(\"databases\").create({\n project: projectId,\n type,\n connectionString: type === \"byodb\" ? connectionString : undefined,\n connectionStatus: \"untested\"\n })) as unknown as DatabaseRow;\n success(`Attached ${type} database to project ${projectRef}`);\n keyValues([[\"ID\", String(created.id)]]);\n if (type === \"byodb\") {\n console.log(chalk.gray(\" Verify it with `rebase cloud db test`.\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to attach database\");\n }\n}\n\nasync function testDatabase(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n console.log(\"\");\n console.log(` Testing database connectivity for project ${chalk.bold(projectId)}...`);\n try {\n const res = await client.functions.invoke<{ success: boolean; logs?: string }>(\"db-test\", { projectId });\n console.log(\"\");\n if (res.logs) console.log(res.logs);\n if (res.success) success(\"Database connection succeeded\");\n else fail(\"Database connection failed. See logs above.\");\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 portForward: { namespace: string; service: string; localPort: number; remotePort: number } | 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 const args = arg({ \"--reveal\": Boolean, \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\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\", path: 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.portForward) {\n const pf = info.portForward;\n console.log(\"\");\n console.log(chalk.gray(` Port-forward: kubectl -n ${pf.namespace} port-forward svc/${pf.service} ${pf.localPort}:${pf.remotePort}`));\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 portForward: info.portForward,\n unavailableReason: info.unavailableReason,\n // Only present when explicitly revealed.\n ...(args[\"--reveal\"] ? { password, connectionString } : {})\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load database info\");\n }\n}\n\n/* ─── backups ──────────────────────────────────────────────────── */\n\nasync function backupCommand(rawArgs: string[]): Promise<void> {\n // `rebase cloud db backup <action>` — action is the 4th positional token.\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2] || \"list\";\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2), permissive: true });\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: ${res.backup?.filename ?? \"(unknown)\"}`),\n { success: true, backup: res.backup ?? null }\n );\n return;\n }\n\n if (action === \"restore\") {\n const filename = cloudPositionals(rawArgs).slice(3)[0];\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, message: 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 = cloudPositionals(rawArgs).slice(3)[0];\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, size: res.size, url: res.url }\n );\n return;\n }\n\n // default: list\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 size = b.size !== undefined ? `${(b.size / 1024 / 1024).toFixed(1)} MB` : \"\";\n console.log(` ${chalk.bold(b.filename)} ${chalk.gray(`${b.type ?? \"\"} ${size}`.trim())}`);\n }\n console.log(\"\");\n },\n { projectId, backups: 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 const args = arg(\n { \"--target\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const action = cloudPositionals(rawArgs).slice(2)[0] || \"status\";\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, targetTime: target, acknowledgeNoCutover: 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 fail(`Unknown pitr command: ${action}`, \"Try status | restore | cutover | discard.\", \"usage\");\n } catch (e) {\n reportError(e, \"PITR operation failed\");\n }\n}\n\nfunction printDbHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud db\")} — Database & backups\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List databases attached to the project\n ${chalk.blue.bold(\"create\")} Attach a managed or bring-your-own database\n ${chalk.blue.bold(\"info\")} ${chalk.gray(\"[--reveal]\")} Connection details ${chalk.gray(\"(password only with --reveal)\")}\n ${chalk.blue.bold(\"test\")} Test database connectivity\n ${chalk.blue.bold(\"backup list\")} List backups\n ${chalk.blue.bold(\"backup create\")} Create a manual backup\n ${chalk.blue.bold(\"backup restore\")} ${chalk.gray(\"<file>\")} Restore a backup\n ${chalk.blue.bold(\"backup status\")} Automated-backup health\n ${chalk.blue.bold(\"backup download\")} ${chalk.gray(\"<file>\")} Signed URL for a backup\n ${chalk.blue.bold(\"pitr status\")} Point-in-time recovery window\n ${chalk.blue.bold(\"pitr restore\")} ${chalk.gray(\"--target <ISO>\")} Stage a recovery ${chalk.gray(\"(does not repoint)\")}\n ${chalk.blue.bold(\"pitr cutover\")} ${chalk.gray(\"-y\")} Repoint the app at the staged recovery\n ${chalk.blue.bold(\"pitr discard\")} ${chalk.gray(\"-y\")} Delete a staged recovery\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n ${chalk.blue(\"--reveal\")} Include the DB password ${chalk.gray(\"(info)\")}\n ${chalk.blue(\"--type\")} managed | byodb ${chalk.gray(\"(create)\")}\n ${chalk.blue(\"--connection-string\")} External DB URL ${chalk.gray(\"(byodb)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\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 arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n isJsonMode,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\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);\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}`, \"Try `rebase cloud env --help`.\");\n }\n}\n\n/** A short human hint about redeploy state (the JSON carries `pendingRedeploy`). */\nfunction pendingHint(pending: boolean | null): string | undefined {\n if (pending === true) return chalk.yellow(\"A variable changed since the last deploy — run `rebase cloud deploy` to apply it.\");\n if (pending === null) return chalk.gray(\"Redeploy state is unknown (deployment history unavailable).\");\n return undefined;\n}\n\nasync function listEnv(rawArgs: string[]): Promise<void> {\n const { 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(), value: first.slice(eq + 1) };\n }\n // `set KEY VALUE` form — VALUE is the next operand (may be absent ⇒ empty).\n return { key: first.trim(), value: 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\nasync function setEnv(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--secret\": Boolean, \"--force\": Boolean, \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const operands = cloudPositionals(rawArgs).slice(2); // after `env set`\n const parsed = parseEnvAssignment(operands);\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 `Put ${buildTimePrefix}* variables in the source you deploy (a committed .env, or your build ` +\n `config), then \\`rebase cloud deploy\\`. 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, value: 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\nasync function unsetEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env unset KEY\", undefined, \"usage\");\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, key, pendingRedeploy: 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 { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env reveal KEY\", undefined, \"usage\");\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 if (!found) fail(`No variable named ${key} in project ${projectRef}.`, undefined, \"not_found\");\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, key },\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, value: res.value }\n );\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n}\n\nasync function pullEnv(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--out\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const outPath = path.resolve(args[\"--out\"] || \".env\");\n\n try {\n const list = await fetchEnvVars(client, projectId);\n\n if (fs.existsSync(outPath)) {\n await confirmDestructive({ yes: Boolean(args[\"--yes\"]), prompt: `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, reason: \"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, key: v.key },\n { path: \"reveal\" }\n );\n // Quote values that contain whitespace or a hash so a dotenv reader\n // keeps them intact.\n const needsQuote = /[\\s#'\"]/.test(revealed.value);\n lines.push(`${v.key}=${needsQuote ? JSON.stringify(revealed.value) : revealed.value}`);\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 console.log(chalk.gray(` Skipped ${skipped.length} secret variable(s): ${skipped.map((s) => s.key).join(\", \")}`));\n console.log(\"\");\n }\n },\n { success: true, path: outPath, written, skipped }\n );\n } catch (e) {\n reportError(e, \"Failed to pull environment variables\");\n }\n}\n\nfunction printEnvHelp(): void {\n if (isJsonMode()) {\n printEnvHelpJson();\n return;\n }\n console.log(`\n${chalk.bold(\"rebase cloud env\")} — Environment variables\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List keys ${chalk.gray(\"(values are never printed)\")}\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"KEY=VALUE [--secret]\")} Create or replace a variable\n ${chalk.blue.bold(\"unset\")} ${chalk.gray(\"KEY\")} Remove a variable\n ${chalk.blue.bold(\"reveal\")} ${chalk.gray(\"KEY\")} Print one non-secret value\n ${chalk.blue.bold(\"pull\")} ${chalk.gray(\"[--out .env] [-y]\")} Write revealable values to a dotenv file\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--secret\")} Mark a variable write-only ${chalk.gray(\"(set)\")}\n ${chalk.blue(\"--force\")} Set a build-time key anyway ${chalk.gray(\"(set)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n\n${chalk.gray(\"Values are encrypted at rest (AES-256-GCM) and only decrypted at deploy time.\")}\n${chalk.gray(\"VITE_* / NEXT_PUBLIC_* / PUBLIC_* / REACT_APP_* are read by your bundler at BUILD time;\")}\n${chalk.gray(\"these are applied at rollout, after the image is built, so they never reach the bundle.\")}\n`);\n}\n\nfunction printEnvHelpJson(): void {\n process.stdout.write(\n JSON.stringify({\n command: \"env\",\n actions: [\"list\", \"set\", \"unset\", \"reveal\", \"pull\"]\n }) + \"\\n\"\n );\n}\n","/**\n * `rebase cloud domains` — a project's custom domain.\n *\n * domains list Current domain + the DNS records it needs\n * domains add <domain> Register a domain (starts, does not finish, setup)\n * domains verify Check the published DNS now; live only if it passes\n * domains remove Detach the custom domain\n *\n * The DNS record set comes from the server (`verify-domain`), never composed\n * here: whether to publish an A or a CNAME depends on apex-vs-subdomain and on\n * the ingress address behind the tenant host, which the CLI cannot know. Adding\n * a domain only registers it — it is unverified until the records are published\n * and `verify` passes.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n keyValues,\n success,\n fail,\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 DomainSetup {\n domain: string | null;\n status: \"none\" | \"pending\" | \"verified\";\n isApex?: boolean;\n tenantHost?: string;\n verifiedAt?: string | null;\n instructions?: {\n pointing?: DomainRecord;\n ownership: DomainRecord;\n };\n}\n\ninterface DomainCheck {\n ok: boolean;\n expected: string[];\n observed: string[];\n error?: string;\n}\n\ninterface VerifyResult extends DomainSetup {\n verified: boolean;\n checks: { ownership: DomainCheck; pointing: DomainCheck };\n}\n\nasync function fetchDomainSetup(client: CloudClient, projectId: string): Promise<DomainSetup> {\n return client.functions.invoke<DomainSetup>(\"verify-domain\", undefined, { method: \"GET\", path: projectId });\n}\n\nfunction printRecords(setup: DomainSetup): void {\n const recs = [setup.instructions?.pointing, setup.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 verifyDomains(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}`, \"Try `rebase cloud domains --help`.\");\n }\n}\n\nasync function listDomains(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🌐 Custom domain — project ${projectRef}`));\n console.log(\"\");\n if (!setup.domain) {\n console.log(chalk.gray(\" No custom domain. Add one with `rebase cloud domains add <domain>`.\"));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Domain\", setup.domain],\n [\"Status\", setup.status === \"verified\" ? chalk.green(setup.status) : chalk.yellow(setup.status)],\n [\"Apex\", setup.isApex === undefined ? undefined : setup.isApex ? \"yes\" : \"no\"],\n [\"Tenant host\", setup.tenantHost],\n [\"Verified at\", setup.verifiedAt ?? undefined]\n ]);\n console.log(\"\");\n if (setup.status !== \"verified\") printRecords(setup);\n },\n { projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to load custom domain\");\n }\n}\n\nasync function addDomain(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const domain = cloudPositionals(rawArgs).slice(2)[0];\n if (!domain) fail(\"Usage: rebase cloud domains add <domain>\", undefined, \"usage\");\n\n try {\n // Registering the domain is a project update; the DNS records to publish\n // then come from the server's setup endpoint.\n await client.data.collection(\"projects\").update(projectId, { customDomain: domain });\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n success(`Registered ${chalk.bold(domain!)} — not yet verified`);\n printRecords(setup);\n console.log(chalk.gray(\" Publish the records above, then run `rebase cloud domains verify`.\"));\n console.log(\"\");\n },\n { success: true, projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to register domain\");\n }\n}\n\nasync function verifyDomains(rawArgs: string[]): Promise<void> {\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<VerifyResult>(\"verify-domain\", {}, { path: projectId });\n emit(\n () => {\n console.log(\"\");\n if (res.verified) success(`${res.domain} is verified and live`);\n else {\n console.log(chalk.yellow(` ⚠ ${res.domain ?? \"domain\"} 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);\n }\n },\n { projectId, verified: res.verified, status: res.status, domain: res.domain, checks: res.checks, instructions: res.instructions }\n );\n if (!res.verified) process.exit(1);\n } catch (e) {\n reportError(e, \"Failed to verify domain\");\n }\n}\n\nasync function removeDomain(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\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: `Remove the custom domain from project ${projectRef}?`\n });\n\n try {\n await client.data.collection(\"projects\").update(projectId, { customDomain: \"\" });\n emit(\n () => success(`Removed the custom domain from project ${projectRef}`),\n { success: true, projectId }\n );\n } catch (e) {\n reportError(e, \"Failed to remove domain\");\n }\n}\n\nfunction printDomainsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud domains\")} — Custom domain\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} Show the domain + DNS records\n ${chalk.blue.bold(\"add\")} ${chalk.gray(\"<domain>\")} Register a custom domain\n ${chalk.blue.bold(\"verify\")} Check DNS and go live\n ${chalk.blue.bold(\"remove\")} ${chalk.gray(\"[-y]\")} Detach the custom domain\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\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 arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\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}`, \"Try `rebase cloud extensions --help`.\");\n }\n}\n\nasync function listExtensions(rawArgs: string[]): Promise<void> {\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, databaseType: res.databaseType, reason: res.reason, source: res.source, extensions: res.extensions }\n );\n } catch (e) {\n reportError(e, \"Failed to list extensions\");\n }\n}\n\nasync function enableExtension(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions enable <name>\", undefined, \"usage\");\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, extensionName: 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 args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions disable <name>\", undefined, \"usage\");\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, extensionName: 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\nfunction printExtensionsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud extensions\")} — Postgres extensions\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List extensions and their state\n ${chalk.blue.bold(\"enable\")} ${chalk.gray(\"<name> [-y]\")} Enable one ${chalk.gray(\"(pgvector alias ⇒ vector)\")}\n ${chalk.blue.bold(\"disable\")} ${chalk.gray(\"<name>\")} Disable one\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--yes, -y\")} Confirm a DB-restarting change\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\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\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 arg from \"arg\";\nimport chalk from \"chalk\";\nimport { requireClient, requireProject, displayProjectRef, emit, 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}\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}`, \"Try `rebase cloud settings --help`.\");\n }\n}\n\nasync function showSettings(rawArgs: string[]): Promise<void> {\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 unknown 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 ]);\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 }\n );\n } catch (e) {\n reportError(e, \"Failed to load settings\");\n }\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}): Record<string, string> {\n const patch: Record<string, string> = {};\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 return patch;\n}\n\nasync function setSettings(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--project\": String,\n \"-p\": \"--project\"\n },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const patch = buildSettingsPatch({\n name: args[\"--name\"],\n subdomain: args[\"--subdomain\"],\n repo: args[\"--repo\"],\n branch: args[\"--branch\"]\n });\n if (Object.keys(patch).length === 0) {\n fail(\"Nothing to update.\", \"Pass --name, --subdomain, --repo, or --branch.\", \"usage\");\n }\n\n try {\n if (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, projectId, updated: patch }\n );\n } catch (e) {\n reportError(e, \"Failed to update settings\");\n }\n}\n\nfunction printSettingsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud settings\")} — Project configuration\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"show\")} Show current settings\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"[flags]\")} Update settings\n\n${chalk.green.bold(\"Set flags\")}\n ${chalk.blue(\"--name\")} ${chalk.gray(\"<name>\")}\n ${chalk.blue(\"--subdomain\")} ${chalk.gray(\"<sub>\")}\n ${chalk.blue(\"--repo\")} ${chalk.gray(\"<git url>\")}\n ${chalk.blue(\"--branch\")} ${chalk.gray(\"<branch>\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\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 image (`status === \"success\" && imageUrl`);\n * anything else 409s `deploy_not_rollbackable` server-side. So this module never\n * offers — and refuses to invoke — a rollback the server would reject, exactly\n * mirroring the console's `isRollbackable`.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\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 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 backend's rule EXACTLY: a rollback is honoured only for a successful\n * deploy that recorded an image. Any other row 409s `deploy_not_rollbackable`.\n */\nexport function isRollbackable(dep: DeploymentRow): boolean {\n return dep.status === \"success\" && deploymentImage(dep) !== null;\n}\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, source, userId: 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 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 version the\n // bundle resolved. 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 message: str(dep, \"deployMessage\", \"deploy_message\"),\n frameworkVersion: str(dep, \"frameworkVersion\", \"framework_version\"),\n commit: {\n hash: str(dep, \"gitCommitHash\", \"gitCommitHash\"),\n message: str(dep, \"gitCommitMessage\", \"gitCommitMessage\")\n }\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 res.data as unknown as DeploymentRow[];\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 const args = arg(\n { \"--limit\": Number, \"--all\": Boolean, \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\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 framework version are what make one row\n // distinguishable from the next; indented under it so the\n // status line stays scannable when they are absent.\n const label = [v.message, v.frameworkVersion ? `@rebasepro/* ${v.frameworkVersion}` : 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, limit, truncated, deployments: views }\n );\n } catch (e) {\n reportError(e, \"Failed to list deployments\");\n }\n}\n\nexport async function rollbackCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // `rollback [deploymentId]` — the id, when given, is the first operand after\n // the `rollback` group token.\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\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 target = rows!.find((d) => String(d.id) === explicitId);\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 (needs a successful deploy that recorded an image).`,\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 (needs a successful deploy that recorded an image).\",\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 imageUrl: string;\n }>(\"deploy\", { projectId, deploymentId: String(target!.id), client: \"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 [\"Image\", res.imageUrl]\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\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 args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\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<{ success: boolean; deploymentId: string; buildJobDeleted: boolean }>(\n \"deploy\",\n explicitId ? { projectId, deploymentId: explicitId } : { projectId },\n { path: \"cancel\" }\n );\n emit(\n () => {\n success(`Cancelled deployment ${chalk.bold(res.deploymentId)}`);\n if (res.buildJobDeleted) console.log(chalk.gray(\" The build job was deleted.\"));\n console.log(\"\");\n },\n { success: true, deploymentId: res.deploymentId, buildJobDeleted: res.buildJobDeleted }\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 arg from \"arg\";\nimport { requireClient, requireProject, displayProjectRef, 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 const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\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, projectId, status: \"stopped\" });\n } else if (action === \"start\") {\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Started project ${projectRef}`), { success: true, projectId, status: \"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, projectId, status: \"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 {\n requireClient,\n requireProject,\n displayProjectRef,\n fetchTenantBaseDomain,\n projectHost,\n colorStatus,\n keyValues,\n emit,\n isJsonMode,\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\", meaning: `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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"auth is mounted and rejected the empty body, as it should\" };\n }\n if (status === 401 || status === 403) {\n return { verdict: \"ok\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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, pod: null, text: line };\n return { ts: m[1] ?? null, pod: m[2] ?? null, text: 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\ninterface RuntimeLogsResponse {\n logs?: string;\n pods?: Array<{ pod: string; state: string; lines: number; message: string | null; hint: string | null }>;\n ordering?: string;\n truncated?: boolean;\n state?: string;\n message?: string | null;\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 if (res.truncated) console.log(chalk.gray(\" (output truncated — narrow the window with --since)\"));\n}\n\n/** Resolve the public origin a project is served at. */\nasync 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), permissive: 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 const parsed = arg(\n { \"--collection\": String, \"--function\": String },\n { argv: rawArgs.slice(3), permissive: true }\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, overall, probes: 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\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. */\n defaultSinceSeconds: number;\n /** Max lines rendered. */\n limit: number;\n title: string;\n}\n\nasync function logView(rawArgs: string[], view: LogViewOptions): Promise<void> {\n const parsed = arg(\n { \"--since\": String, \"--tail\": Number, \"--previous\": Boolean },\n { argv: rawArgs.slice(3), permissive: true }\n );\n\n const sinceArg = parsed[\"--since\"];\n if (sinceArg !== undefined && parseSince(sinceArg) === null) {\n fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n }\n const sinceSeconds = parseSince(sinceArg) ?? view.defaultSinceSeconds;\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,\n tailLines: parsed[\"--tail\"] ?? 500,\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\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` ${view.title} — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` last ${formatDuration(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" (nothing matched in this window)\"));\n console.log(\"\");\n return;\n }\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 {\n sinceSeconds,\n state: res.state ?? null,\n pods: res.pods ?? [],\n truncated: Boolean(res.truncated),\n matched: kept.length,\n lines: shown\n }\n );\n}\n\nasync function requestsCommand(rawArgs: string[]): Promise<void> {\n const parsed = arg({ \"--since\": String, \"--tail\": Number }, { argv: rawArgs.slice(3), permissive: true });\n const sinceArg = parsed[\"--since\"];\n if (sinceArg !== undefined && parseSince(sinceArg) === null) {\n fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n }\n const sinceSeconds = parseSince(sinceArg) ?? 900;\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, tailLines: parsed[\"--tail\"] ?? 1000 });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const entries = (res.logs ?? \"\")\n .split(\"\\n\")\n .filter((l) => l !== \"\")\n .map((l) => parseRequestLine(parseLogLine(l).text))\n .filter((e): e is RequestLogEntry => e !== null);\n const shown = entries.slice(-40);\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 🌐 Requests — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` last ${formatDuration(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" No structured request lines in this window.\"));\n console.log(chalk.gray(\" (this view needs the server's request logging; try `debug logs`)\"));\n console.log(\"\");\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 },\n { sinceSeconds, requests: shown }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: pod\n ═══════════════════════════════════════════════════════════════ */\n\nasync function podCommand(rawArgs: string[]): Promise<void> {\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, placement: p }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: db\n ═══════════════════════════════════════════════════════════════ */\n\nasync function dbDebugCommand(rawArgs: string[]): Promise<void> {\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 portForward?: { namespace: string; service: string; localPort: number; remotePort: number } | null;\n }\n\n let info: DbInfo;\n try {\n info = await client.functions.invoke<DbInfo>(\"db-info\", undefined, { method: \"GET\", path: projectId });\n } catch (e) {\n reportError(e, \"Failed to read database connection info\");\n }\n\n const pf = info.portForward;\n const forwardCmd = pf\n ? `kubectl port-forward -n ${pf.namespace} svc/${pf.service} ${pf.localPort}:${pf.remotePort}`\n : null;\n const psqlCmd =\n pf && info.username && info.database\n ? `psql -h 127.0.0.1 -p ${pf.localPort} -U ${info.username} -d ${info.database}`\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 (forwardCmd) {\n // Printed rather than run. Opening a tunnel and a superuser shell\n // is not something a command called `debug` should do implicitly.\n console.log(chalk.gray(\" A managed database is only reachable inside its cluster. To connect:\"));\n console.log(\"\");\n console.log(` ${forwardCmd}`);\n if (psqlCmd) console.log(` ${psqlCmd}`);\n console.log(\"\");\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 portForwardCommand: forwardCmd,\n psqlCommand: psqlCmd\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\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 await logView(rawArgs, { defaultSinceSeconds: 900, limit: 200, title: \"📄 Logs\" });\n break;\n case \"errors\":\n await logView(rawArgs, {\n filter: isErrorLine,\n defaultSinceSeconds: 3600,\n limit: 40,\n title: \"🔥 Errors\"\n });\n break;\n case \"boot\":\n await logView(rawArgs, {\n filter: isBootLine,\n // The whole log, not a window: startup happened when the pod\n // started, which may have been days ago.\n defaultSinceSeconds: 7 * 24 * 3600,\n limit: 25,\n title: \"🚀 Boot\"\n });\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 if (isJsonMode()) fail(`Unknown debug command: ${action}`, undefined, \"unknown_command\");\n console.error(chalk.red(`Unknown debug command: ${action}`));\n console.log(\"\");\n printDebugHelp();\n process.exit(1);\n }\n}\n\nfunction printDebugHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud debug\")} — Find out why a deployed project is misbehaving\n\n${chalk.green.bold(\"Usage\")}\n rebase cloud debug ${chalk.blue(\"<subcommand>\")} [options]\n\n${chalk.green.bold(\"End-to-end\")}\n ${chalk.blue.bold(\"health\")} Probe the live URL and explain every status code ${chalk.gray(\"(default)\")}\n\n${chalk.green.bold(\"Runtime\")}\n ${chalk.blue.bold(\"logs\")} ${chalk.gray(\"[--since 15m]\")} Recent application logs\n ${chalk.blue.bold(\"errors\")} ${chalk.gray(\"[--since 1h]\")} Error and warning lines only\n ${chalk.blue.bold(\"requests\")} ${chalk.gray(\"[--since 15m]\")} HTTP requests the server logged ${chalk.gray(\"(status, path, latency)\")}\n ${chalk.blue.bold(\"boot\")} What the server decided at startup ${chalk.gray(\"(storage, functions, auth)\")}\n ${chalk.blue.bold(\"pod\")} Replicas, image, namespace, cluster placement\n\n${chalk.green.bold(\"Data\")}\n ${chalk.blue.bold(\"db\")} Connection shape + the port-forward recipe ${chalk.gray(\"(no password)\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--since <dur>\")} Lookback window: ${chalk.gray(\"90s, 15m, 2h, 1d\")}\n ${chalk.blue(\"--tail <n>\")} Lines to read per pod ${chalk.gray(\"(default 500)\")}\n ${chalk.blue(\"--previous\")} Read the CRASHED container instance ${chalk.gray(\"(where the reason lives)\")}\n ${chalk.blue(\"--host <hostname>\")} Probe this address instead of the project's own\n ${chalk.blue(\"--collection <name>\")} Collection for the unauth-read probe ${chalk.gray(\"(default: users)\")}\n ${chalk.blue(\"--function <name>\")} Also assert this function loaded ${chalk.gray(\"(checked against the listing)\")}\n ${chalk.blue(\"--project, -p <slug>\")} Operate on a project without linking\n\n${chalk.gray(\"Everything here is read-only. `health` exits non-zero when a check fails,\")}\n${chalk.gray(\"so it works in a deploy script. To restart a workload, use `rebase cloud restart`.\")}\n`);\n}\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 keyValues,\n fetchTenantBaseDomain,\n projectHost,\n openUrl,\n success,\n fail,\n reportError\n} from \"./context\";\nimport { firstRow, latestDeployment, fmtDate } from \"./projects\";\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/**\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 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 // 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(` · framework ${framework}`) : \"\";\n return `managed ${version}${frameworkPart}${pin}`;\n}\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\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\", path: 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\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 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 url: projectHost(project, baseDomain) ?? null,\n branch: project.gitBranch ?? null,\n lastDeploy: deploy ? { id: String(deploy.id), status: deploy.status ?? null, createdAt: deploy.createdAt ?? null } : null,\n runtime: {\n mode: project.runtimeMode ?? \"custom\",\n version: project.runtimeVersion ?? null,\n frameworkVersion: 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, connectionStatus: 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\nexport async function metricsCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const m = await client.functions.invoke<{\n status?: string;\n cpu?: string;\n memory?: string;\n memoryPercent?: string;\n disk?: string;\n }>(\"metrics\", undefined, { method: \"GET\",\npath: projectId });\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 [\"CPU\", m.cpu],\n [\"Memory\", m.memory ? `${m.memory}${m.memoryPercent ? ` (${m.memoryPercent})` : \"\"}` : undefined],\n [\"Disk\", m.disk]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch metrics\");\n }\n}\n\n/* ─── webhooks ─────────────────────────────────────────────────── */\n\nexport async function webhooksCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n if (subcommand === \"create\") {\n const args = arg(\n { \"--name\": String,\n\"--table\": String,\n\"--url\": String,\n\"--events\": String },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const name = args[\"--name\"] || fail(\"--name is required.\");\n const table = args[\"--table\"] || fail(\"--table is required.\");\n const url = args[\"--url\"] || fail(\"--url (endpoint) is required.\");\n const events = (args[\"--events\"] || \"insert,update,delete\").split(\",\").map((s) => s.trim());\n\n const created = (await client.data.collection(\"webhooks\").create({\n project: projectId,\n name,\n table,\n url,\n events,\n enabled: true\n })) as unknown as { id: string | number };\n success(`Created webhook ${chalk.bold(name)} [${created.id}]`);\n return;\n }\n\n if (subcommand === \"delete\") {\n const id = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2];\n if (!id) fail(\"Usage: rebase cloud webhooks delete <id>\");\n await client.data.collection(\"webhooks\").delete(id);\n success(`Deleted webhook ${id}`);\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 unknown as Array<{ id: string | number; name?: string; table?: string; url?: string; enabled?: boolean; events?: string[] }>;\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 } catch (e) {\n reportError(e, \"Webhook operation failed\");\n }\n}\n\n/* ─── storage ──────────────────────────────────────────────────── */\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\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 unknown as Array<{ id: string | number; type?: string; provider?: string; bucketName?: string; status?: string }>;\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 console.log(` ${chalk.bold(s.bucketName ?? s.type ?? \"bucket\")} ${chalk.gray(`[${s.id}]`)} ${colorStatus(s.status)}`);\n keyValues([[\"Provider\", s.provider], [\"Type\", s.type]]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list storage\");\n }\n}\n\nfunction printStorageHelp(): void {\n console.log(\"\");\n console.log(chalk.bold(\" rebase cloud storage\"));\n console.log(\"\");\n console.log(\" \" + chalk.blue.bold(\"storage\") + \" List this project's storage\");\n console.log(\" \" + chalk.blue.bold(\"storage create\") + \" Provision platform-managed storage\");\n console.log(\" \" + chalk.blue.bold(\"storage attach\") + \" Attach your own S3-compatible bucket\");\n console.log(\"\");\n console.log(chalk.gray(\" attach options:\"));\n console.log(chalk.gray(\" --bucket <name> Bucket name (required)\"));\n console.log(chalk.gray(\" --access-key-id <id> Access key ID (required)\"));\n console.log(chalk.gray(\" --secret-access-key <s> Secret access key (required)\"));\n console.log(chalk.gray(\" --endpoint <url> S3 endpoint; omit for AWS\"));\n console.log(chalk.gray(\" --region <region> Region\"));\n console.log(chalk.gray(\" --force-path-style Required by MinIO and some gateways\"));\n console.log(\"\");\n console.log(chalk.gray(\" Without either, file storage stays off: uploads are refused with\"));\n console.log(chalk.gray(\" 501 STORAGE_NOT_CONFIGURED rather than written to a container\"));\n console.log(chalk.gray(\" filesystem that is erased on the next restart.\"));\n console.log(\"\");\n}\n\n/* ─── storage create: platform-managed ─────────────────────────── */\n\nasync function storageCreateCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n console.log(\"\");\n console.log(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 }>(`storage-provision/${encodeURIComponent(projectId)}`, undefined, { method: \"POST\" });\n\n const info = (res as unknown as { data?: typeof res.data }).data ?? res.data;\n\n success(`Managed storage provisioned for ${displayProjectRef(rawArgs)}.`);\n keyValues([\n [\"Bucket\", info.bucketName],\n [\"Region\", info.region],\n [\"Endpoint\", info.endpoint],\n [\"Access key\", info.accessKeyId]\n ]);\n console.log(\"\");\n // The secret is never returned by the endpoint — it goes to the row and\n // to the tenant's environment. Say so, or the absence reads as a bug.\n console.log(chalk.gray(\" The secret key is stored encrypted and injected at deploy time; it is not displayed.\"));\n console.log(chalk.gray(\" Redeploy for the tenant to pick it up: \") + chalk.bold(\"rebase cloud deploy\"));\n console.log(\"\");\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 const parsed = arg(\n {\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 },\n { argv: rawArgs.slice(3), permissive: true }\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 );\n }\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n const existing = (await client.data.collection(\"storages\").find({\n where: { project: [\"==\", projectId] },\n limit: 1\n })).data[0] as { id?: string | number } | undefined;\n\n const row: Record<string, unknown> = {\n project: projectId,\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 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 keyValues([\n [\"Bucket\", bucket],\n [\"Endpoint\", parsed[\"--endpoint\"] ?? \"AWS S3\"],\n [\"Region\", parsed[\"--region\"] ?? \"(default)\"]\n ]);\n console.log(\"\");\n console.log(chalk.gray(\" Redeploy for the tenant to pick it up: \") + chalk.bold(\"rebase cloud deploy\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to attach storage\");\n }\n}\n\n/* ─── clusters ─────────────────────────────────────────────────── */\n\nexport async function clustersCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n try {\n const clusters = (await client.data.collection(\"clusters\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n provider?: string;\n region?: string;\n status?: string;\n }>;\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 } catch (e) {\n reportError(e, \"Failed to list clusters\");\n }\n}\n\n/* ─── billing ──────────────────────────────────────────────────── */\n\nexport async function billingCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\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.\");\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.\");\n openUrl(res.url, \"Add a payment method in your browser:\");\n if (res.simulated) {\n console.log(chalk.gray(\" (dev mode — Stripe not configured; complete setup from the console)\"));\n console.log(\"\");\n } else {\n console.log(chalk.gray(\" Once you've added a card, `rebase cloud deploy` runs without further prompts.\"));\n console.log(\"\");\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.\");\n console.log(\"\");\n console.log(\" Complete checkout in your browser:\");\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\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.\");\n try {\n const orgRow = (await client.data.collection(\"organizations\").findById(org)) as\n | { billing_account_id?: string | number; billingAccount?: string | number }\n | undefined;\n const billingId = orgRow?.billing_account_id ?? orgRow?.billingAccount;\n if (!billingId) {\n console.log(\"\");\n console.log(chalk.gray(` Organization ${org} has no billing account yet.`));\n console.log(\"\");\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: show which plan the linked/`--project` project is on.\n // BYO-cluster projects pay a flat platform fee; the rest pay managed compute.\n let plan: 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 | { cluster_id?: string | number; cluster?: unknown; provider?: string; vmSize?: string }\n | undefined;\n const hasCluster = proj?.cluster_id != null || proj?.cluster != null;\n plan = hasCluster ? \"platform fee (own cluster)\" : \"managed compute\";\n\n // Best-effort: append the resolved monthly amount from Stripe (via\n // the control plane's /api/functions/pricing). Keep working if the\n // endpoint is unreachable — the label alone is still useful.\n try {\n const pricing = await client.functions.invoke<{\n items: Array<{ lookupKey: string; amountEur: number }>;\n }>(\"pricing\", undefined, { method: \"GET\" });\n const key = hasCluster\n ? \"platform_byo\"\n : `compute_${proj?.provider || \"hetzner\"}_${proj?.vmSize || \"cx21\"}`;\n const item = pricing.items?.find((i) => i.lookupKey === key);\n if (item) plan = `${plan} — €${item.amountEur.toFixed(2)}/mo`;\n } catch {\n // pricing endpoint unreachable — keep the plan label without an amount\n }\n }\n } catch {\n // no linked/resolvable project — skip the Plan line\n }\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 [\"Plan\", plan],\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 } catch (e) {\n reportError(e, \"Failed to load billing\");\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 { linkCommand, unlinkCommand, selectOrgCommand, openCommand } from \"./link\";\nimport { listProjects, createProject, projectInfo, deleteProject } from \"./projects\";\nimport { deployCommand, logsCommand } from \"./deploy\";\nimport { orgsCommand } from \"./orgs\";\nimport { dbCommand } from \"./databases\";\nimport { envCommand } from \"./env\";\nimport { domainsCommand } from \"./domains\";\nimport { extensionsCommand } from \"./extensions\";\nimport { settingsCommand } from \"./settings\";\nimport { deploymentsListCommand, rollbackCommand, cancelCommand } from \"./deployments\";\nimport { powerCommand } from \"./power\";\nimport { debugCommand } from \"./debug\";\nimport {\n statusCommand,\n metricsCommand,\n webhooksCommand,\n storageCommand,\n clustersCommand,\n billingCommand\n} from \"./resources\";\nimport { requireProjectRef, initOutputMode } from \"./context\";\n\n/** Positional tokens after `rebase cloud` (group, action, …). */\nfunction positionals(rawArgs: string[]): string[] {\n return arg({}, { argv: rawArgs.slice(3),\npermissive: true })._;\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 const group = subcommand && subcommand !== \"--help\" ? subcommand : pos[0];\n const action = pos[1];\n\n if (!group || subcommand === \"--help\") {\n 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\n /* context / link */\n case \"link\":\n await linkCommand(rawArgs);\n break;\n case \"unlink\":\n unlinkCommand();\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\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 \"clusters\":\n await clustersCommand(rawArgs);\n break;\n case \"billing\":\n await billingCommand(rawArgs);\n break;\n\n default:\n console.error(chalk.red(`Unknown cloud command: ${group}`));\n console.log(\"\");\n printCloudHelp();\n process.exit(1);\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 case \"info\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await projectInfo(rawArgs, id);\n break;\n }\n case \"delete\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await deleteProject(rawArgs, id);\n break;\n }\n case \"--help\":\n printCloudHelp();\n break;\n default:\n console.error(chalk.red(`Unknown projects command: ${action}`));\n process.exit(1);\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 console.error(chalk.red(`Unknown deployments command: ${action}`));\n process.exit(1);\n }\n}\n\nfunction printCloudHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud\")} — Manage your apps on Rebase Cloud\n\n${chalk.green.bold(\"Usage\")}\n rebase cloud ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"login\")} Sign in to the control plane\n ${chalk.blue.bold(\"logout\")} Sign out\n ${chalk.blue.bold(\"whoami\")} Show the current session\n\n${chalk.green.bold(\"Project link\")}\n ${chalk.blue.bold(\"link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"unlink\")} Remove the link\n ${chalk.blue.bold(\"use\")} ${chalk.gray(\"[org]\")} Select the active organization\n ${chalk.blue.bold(\"open\")} Open the dashboard in a browser\n\n${chalk.green.bold(\"Projects\")}\n ${chalk.blue.bold(\"projects list\")} List projects\n ${chalk.blue.bold(\"projects create\")} Create a project ${chalk.gray(\"(--link to link it)\")}\n ${chalk.blue.bold(\"projects info\")} ${chalk.gray(\"[id]\")} Show project details\n ${chalk.blue.bold(\"projects delete\")} ${chalk.gray(\"[id]\")} Delete a project\n\n${chalk.green.bold(\"Deploy & observe\")}\n ${chalk.blue.bold(\"deploy\")} ${chalk.gray(\"[--bundle|--source .]\")} Deploy the linked project + stream build logs\n ${chalk.blue.bold(\"logs\")} ${chalk.gray(\"[--runtime] [-f]\")} Show build (or runtime) logs\n ${chalk.blue.bold(\"deployments list\")} ${chalk.gray(\"[--limit N|--all]\")} Deployment history ${chalk.gray(\"(status, duration, trigger)\")}\n ${chalk.blue.bold(\"rollback\")} ${chalk.gray(\"[id] [-y]\")} Roll back to a successful deploy\n ${chalk.blue.bold(\"cancel\")} ${chalk.gray(\"[-y]\")} Cancel the in-flight build\n ${chalk.blue.bold(\"start|stop|restart\")} ${chalk.gray(\"[-y]\")} Power ops ${chalk.gray(\"(stop/restart need -y)\")}\n ${chalk.blue.bold(\"status\")} One-glance project status\n ${chalk.blue.bold(\"metrics\")} Live CPU / memory / disk\n ${chalk.blue.bold(\"debug\")} ${chalk.gray(\"[health|logs|…]\")} Diagnose a misbehaving deployment ${chalk.gray(\"(read-only)\")}\n\n${chalk.green.bold(\"Config\")}\n ${chalk.blue.bold(\"env list|set|unset|reveal|pull\")}\n ${chalk.blue.bold(\"domains list|add|verify|remove\")}\n ${chalk.blue.bold(\"extensions list|enable|disable\")}\n ${chalk.blue.bold(\"settings show|set\")} Name / branch / repo / subdomain\n\n${chalk.green.bold(\"Organizations\")}\n ${chalk.blue.bold(\"orgs list|create|members\")}\n\n${chalk.green.bold(\"Databases\")}\n ${chalk.blue.bold(\"db list|create|info|test\")}\n ${chalk.blue.bold(\"db backup list|create|restore|status|download\")}\n ${chalk.blue.bold(\"db pitr status|restore|cutover|discard\")}\n\n${chalk.green.bold(\"Other resources\")}\n ${chalk.blue.bold(\"webhooks list|create|delete\")}\n ${chalk.blue.bold(\"storage\")} List storage buckets\n ${chalk.blue.bold(\"storage create\")} Provision platform-managed storage\n ${chalk.blue.bold(\"storage attach\")} Attach your own S3-compatible bucket\n ${chalk.blue.bold(\"clusters\")} List compute clusters\n ${chalk.blue.bold(\"billing setup\")} Attach a card to the org ${chalk.gray(\"(one-time, opens browser)\")}\n ${chalk.blue.bold(\"billing\")} Show billing account + card on file\n\n${chalk.green.bold(\"Global options\")}\n ${chalk.blue(\"--json\")} Machine-readable output ${chalk.gray(\"(also when piped, or REBASE_JSON=1)\")}\n ${chalk.blue(\"--url <origin>\")} Target a specific control plane ${chalk.gray(\"(or REBASE_CLOUD_URL)\")}\n ${chalk.blue(\"--project, -p <id>\")} Operate on a project without linking\n\n${chalk.gray(\"Most commands act on the linked project (.rebase/cloud.json) unless --project is given.\")}\n${chalk.gray(\"Docs: https://rebase.pro/docs\")}\n`);\n}\n","/**\n * CLI command: rebase apps\n *\n * Inspect the apps this repository contributes to a project, adopt a\n * `rebase.json` for a project that predates it, and print the client bootstrap\n * an app needs to reach its backend.\n *\n * The distinction that runs through all of this: a *repository* declares apps,\n * a *project* owns them. Two repositories can contribute to the same project and\n * never know about each other, which is what makes a separate frontend repo — or\n * a mobile app with no repo relationship at all — an ordinary thing rather than\n * a special case.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport type { RebaseAppConfig } from \"@rebasepro/types\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport {\n assessManagedCompatibility,\n loadManifest,\n ManifestError,\n manifestExists,\n synthesizeManifest,\n writeManifest\n} from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase apps\")} — the apps this repository contributes\n\n${chalk.bold(\"Usage\")}\n rebase apps list List declared apps and their build outputs\n rebase apps init Write a rebase.json inferred from this project\n rebase apps config <app> Print the client configuration for an app\n\n${chalk.bold(\"Options\")}\n --json Machine-readable output\n --force Overwrite an existing rebase.json (apps init)\n -h, --help Show this help\n`.trim());\n}\n\nexport async function appsCommand(subcommand: string | undefined, rawArgs: string[] = []): Promise<void> {\n const args = arg(\n {\n \"--json\": Boolean,\n \"--force\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n },\n { argv: rawArgs.slice(3),\npermissive: true }\n );\n\n if (args[\"--help\"] || !subcommand || subcommand === \"--help\") {\n printHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listApps(Boolean(args[\"--json\"]));\n break;\n case \"init\":\n await initManifest(Boolean(args[\"--force\"]));\n break;\n case \"config\":\n await printAppConfig(args._[1], Boolean(args[\"--json\"]));\n break;\n default:\n console.error(chalk.red(`Unknown subcommand: ${subcommand}`));\n console.log(\"\");\n printHelp();\n process.exit(1);\n }\n}\n\nfunction describeApp(app: RebaseAppConfig): string {\n switch (app.type) {\n case \"backend\":\n return `config: ${app.config ?? \"config\"}, mode: ${app.mode ?? \"cms\"}`;\n case \"static\":\n return `${app.root} → ${app.output}`;\n case \"admin\":\n return app.mode === \"bundled\" ? `bundled → ${app.output ?? \"?\"}` : \"hosted by the platform\";\n case \"mobile\":\n return app.platform;\n case \"custom\":\n return app.dockerfile ?? \"Dockerfile\";\n default:\n return \"\";\n }\n}\n\nasync function listApps(asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot);\n const compatibility = assessManagedCompatibility(loaded.manifest);\n\n if (asJson) {\n console.log(JSON.stringify(\n {\n source: loaded.source,\n runtime: loaded.manifest.runtime,\n apps: loaded.manifest.apps,\n managed: compatibility\n },\n null,\n 2\n ));\n return;\n }\n\n if (loaded.source === \"synthesized\") {\n console.log(chalk.dim(\"No rebase.json — showing the layout inferred from this project.\"));\n console.log(chalk.dim(`Run ${chalk.cyan(\"rebase apps init\")} to write it down.\\n`));\n }\n\n console.log(chalk.bold(`Runtime ${loaded.manifest.runtime}`));\n console.log(\"\");\n\n const entries = Object.entries(loaded.manifest.apps);\n if (entries.length === 0) {\n console.log(chalk.yellow(\"No apps declared.\"));\n return;\n }\n\n const width = Math.max(...entries.map(([name]) => name.length));\n for (const [name, app] of entries) {\n console.log(\n ` ${chalk.cyan(name.padEnd(width))} ${chalk.dim(app.type.padEnd(8))} ${describeApp(app)}`\n );\n }\n\n console.log(\"\");\n if (compatibility.eligible) {\n console.log(chalk.green(\"✓ Eligible for the managed runtime.\"));\n } else {\n console.log(chalk.yellow(\"• Uses the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\nasync function initManifest(force: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n\n if (manifestExists(projectRoot) && !force) {\n console.error(chalk.red(\"✗ rebase.json already exists.\"));\n console.error(chalk.dim(\" Pass --force to overwrite it.\"));\n process.exit(1);\n }\n\n const manifest = synthesizeManifest(projectRoot);\n const filePath = writeManifest(projectRoot, manifest);\n\n console.log(chalk.green(`✓ Wrote ${path.relative(projectRoot, filePath)}`));\n console.log(\"\");\n for (const [name, app] of Object.entries(manifest.apps)) {\n console.log(` ${chalk.cyan(name)} ${chalk.dim(`(${app.type})`)}`);\n }\n\n const compatibility = assessManagedCompatibility(manifest);\n if (!compatibility.eligible) {\n console.log(\"\");\n console.log(chalk.yellow(\"This project will use the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/**\n * Print what a client needs to reach this project.\n *\n * Never prints a secret. The API URL and an app's publishable identity are meant\n * to ship inside a client bundle; anything that is not safe there does not belong\n * in output that will inevitably be pasted into a `.env` that gets committed.\n */\nasync function printAppConfig(appName: string | undefined, asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot);\n\n if (!appName) {\n console.error(chalk.red(\"✗ Which app? Usage: rebase apps config <app>\"));\n process.exit(1);\n }\n\n const app = loaded.manifest.apps[appName];\n if (!app) {\n console.error(chalk.red(`✗ No app named \"${appName}\" in rebase.json.`));\n console.error(chalk.dim(` Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n\n const link = readLink(projectRoot);\n const apiUrl = resolveApiUrl(projectRoot, link);\n\n const config = {\n app: appName,\n type: app.type,\n apiUrl: apiUrl ?? null,\n project: link?.projectId ?? link?.slug ?? null\n };\n\n if (asJson) {\n console.log(JSON.stringify(config, null, 2));\n return;\n }\n\n if (!apiUrl) {\n console.log(chalk.yellow(\"This checkout is not linked to a project yet.\"));\n console.log(chalk.dim(` Run ${chalk.cyan(\"rebase link\")} (cloud) or ${chalk.cyan(\"rebase link <url>\")} (self-hosted).`));\n console.log(\"\");\n }\n\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n console.log(`VITE_API_URL=${apiUrl ?? \"http://localhost:3001\"}`);\n console.log(\"\");\n console.log(chalk.dim(\"Then, in the app:\"));\n console.log(chalk.dim(\" const rebase = createRebaseClient({ baseUrl: import.meta.env.VITE_API_URL });\"));\n}\n\n/**\n * Work out the API base URL for this checkout.\n *\n * Prefers an explicit link, then the dev server's own record of where it bound.\n * The dev port is chosen dynamically, so a hardcoded default would be wrong on\n * any machine running more than one project.\n */\nfunction resolveApiUrl(projectRoot: string, link: ReturnType<typeof readLink>): string | undefined {\n if (link?.apiUrl) return link.apiUrl;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as { baseUrl?: string };\n if (state.baseUrl) return state.baseUrl;\n } catch {\n // Stale or partially written state file: fall through.\n }\n }\n\n return undefined;\n}\n\nfunction loadManifestOrExit(projectRoot: string): ReturnType<typeof loadManifest> {\n try {\n return loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.red(` ${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n}\n","import chalk from \"chalk\";\nimport arg from \"arg\";\nimport { createRebaseApp } from \"./commands/init\";\nimport { generateSdkCommand } from \"./commands/generate_sdk\";\nimport { schemaCommand } from \"./commands/schema\";\nimport { dbCommand } from \"./commands/db\";\nimport { devCommand } from \"./commands/dev\";\nimport { buildCommand } from \"./commands/build\";\nimport { startCommand } from \"./commands/start\";\nimport { authCommand } from \"./commands/auth\";\nimport { doctorCommand } from \"./commands/doctor\";\nimport { skillsCommand } from \"./commands/skills\";\nimport { apiKeysCommand } from \"./commands/api-keys\";\nimport { cloudCommand } from \"./commands/cloud\";\nimport { appsCommand } from \"./commands/apps\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction getVersion(): string {\n try {\n // Try to read version from package.json\n const pkgPath = path.resolve(__dirname, \"../package.json\");\n if (fs.existsSync(pkgPath)) {\n return JSON.parse(fs.readFileSync(pkgPath, \"utf-8\")).version;\n }\n } catch {\n // ignore\n }\n return \"unknown\";\n}\n\nexport async function entry(args: string[]) {\n const parsedArgs = arg(\n {\n \"--version\": Boolean,\n \"--help\": Boolean,\n \"-v\": \"--version\",\n \"-h\": \"--help\"\n },\n {\n argv: args.slice(2),\n permissive: true\n }\n );\n\n if (parsedArgs[\"--version\"]) {\n console.log(getVersion());\n return;\n }\n\n const command = parsedArgs._[0];\n const subcommand = parsedArgs._[1];\n\n // Show global help only when no command given, or --help with no recognized command\n const namespacedCommands = [\"init\", \"schema\", \"db\", \"dev\", \"build\", \"start\", \"auth\", \"doctor\", \"skills\", \"api-keys\", \"cloud\", \"apps\", \"generate-sdk\"];\n if (!command || (parsedArgs[\"--help\"] && !namespacedCommands.includes(command))) {\n printHelp();\n return;\n }\n\n // For namespaced commands with --help, pass it through as subcommand\n const effectiveSubcommand = parsedArgs[\"--help\"] ? \"--help\" : subcommand;\n\n switch (command) {\n case \"init\":\n await createRebaseApp(args);\n break;\n\n case \"generate-sdk\": {\n const sdkArgs = arg(\n {\n \"--collections-dir\": String,\n \"--output\": String,\n \"--from\": String,\n \"--token\": String,\n \"--help\": Boolean,\n \"-c\": \"--collections-dir\",\n \"-o\": \"--output\",\n \"-h\": \"--help\"\n },\n {\n argv: args.slice(3),\n permissive: true\n }\n );\n await generateSdkCommand({\n collectionsDir: sdkArgs[\"--collections-dir\"] || \"./config/collections\",\n output: sdkArgs[\"--output\"] || \"./generated/sdk\",\n from: sdkArgs[\"--from\"],\n token: sdkArgs[\"--token\"],\n help: sdkArgs[\"--help\"],\n cwd: process.cwd()\n });\n break;\n }\n\n case \"schema\":\n await schemaCommand(effectiveSubcommand, args);\n break;\n\n case \"db\":\n await dbCommand(effectiveSubcommand, args);\n break;\n\n case \"dev\":\n await devCommand(args);\n break;\n\n case \"build\":\n await buildCommand(args);\n break;\n\n case \"start\":\n await startCommand(args);\n break;\n\n case \"apps\":\n await appsCommand(effectiveSubcommand, args);\n break;\n\n case \"auth\":\n await authCommand(effectiveSubcommand, args);\n break;\n\n case \"doctor\":\n await doctorCommand(args);\n break;\n\n case \"skills\":\n await skillsCommand(effectiveSubcommand, args);\n break;\n\n case \"api-keys\":\n await apiKeysCommand(effectiveSubcommand, args);\n break;\n\n case \"cloud\":\n await cloudCommand(effectiveSubcommand, args);\n break;\n\n default:\n console.error(chalk.red(`Unknown command: ${command}`));\n console.log(\"\");\n printHelp();\n // A mistyped command must not look like success to a shell or CI.\n process.exit(1);\n }\n}\n\nfunction printHelp() {\n console.log(`\n${chalk.bold(\"Rebase CLI\")} — Developer tools for Rebase projects\n\n${chalk.green.bold(\"Usage\")}\n rebase ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"init\")} Create a new Rebase project\n ${chalk.blue.bold(\"dev\")} Start the development server\n ${chalk.blue.bold(\"build\")} Build all workspace packages\n ${chalk.blue.bold(\"start\")} Start the backend server ${chalk.gray(\"(production)\")}\n\n${chalk.green.bold(\"Schema\")}\n ${chalk.blue.bold(\"schema generate\")} Generate Drizzle schema from collections\n ${chalk.blue.bold(\"schema introspect\")} Introspect database → Rebase collections\n ${chalk.blue.bold(\"schema\")} ${chalk.gray(\"--help\")} Show schema command help\n\n${chalk.green.bold(\"Database\")}\n ${chalk.blue.bold(\"db push\")} Apply schema directly to database ${chalk.gray(\"(dev)\")}\n ${chalk.blue.bold(\"db generate\")} Generate SQL migration files\n ${chalk.blue.bold(\"db migrate\")} Run pending migrations\n ${chalk.blue.bold(\"db\")} ${chalk.gray(\"--help\")} Show database command help\n\n${chalk.green.bold(\"SDK\")}\n ${chalk.blue.bold(\"generate-sdk\")} Generate a typed TypeScript SDK from collections\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"auth reset-password\")} Reset a user's password\n ${chalk.blue.bold(\"auth\")} ${chalk.gray(\"--help\")} Show auth command help\n\n${chalk.green.bold(\"Diagnostics\")}\n ${chalk.blue.bold(\"doctor\")} Detect schema drift between collections, schema, and DB\n\n${chalk.green.bold(\"AI Agent Skills\")}\n ${chalk.blue.bold(\"skills install\")} Install Rebase agent skills for your AI coding assistant\n\n${chalk.green.bold(\"API Keys\")}\n ${chalk.blue.bold(\"api-keys list\")} List all service API keys\n ${chalk.blue.bold(\"api-keys create\")} Create a new scoped API key\n ${chalk.blue.bold(\"api-keys revoke\")} Revoke an existing API key\n ${chalk.blue.bold(\"api-keys\")} ${chalk.gray(\"--help\")} Show API key command help\n\n${chalk.green.bold(\"Rebase Cloud\")}\n ${chalk.blue.bold(\"cloud login\")} Sign in to the hosted control plane\n ${chalk.blue.bold(\"cloud link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"cloud deploy\")} Deploy the linked project + stream logs\n ${chalk.blue.bold(\"cloud\")} ${chalk.gray(\"--help\")} Show all cloud commands\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--version, -v\")} Show version number\n ${chalk.blue(\"--help, -h\")} Show this help message\n\n${chalk.gray(\"Documentation: https://rebase.pro/docs\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;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,KAAK,aAAa,EAAE;IAC9B,MAAM,KAAK,KAAK,QAAQ,EAAE;;EAE5B,MAAM,MAAM,KAAK,iBAAiB,EAAE;IAClC,MAAM,KAAK,KAAK,gBAAgB,EAAE;;EAEpC,MAAM,MAAM,KAAK,UAAU,EAAE;IAC3B,MAAM,KAAK,KAAK,eAAe,EAAE;IACjC,MAAM,KAAK,KAAK,iBAAiB,EAAE;IACnC,MAAM,KAAK,KAAK,iBAAiB,EAAE;IACnC,MAAM,KAAK,KAAK,UAAU,EAAE,GAAG,MAAM,KAAK,QAAQ,EAAE;;EAEtD,MAAM,MAAM,KAAK,cAAc,EAAE;IAC/B,MAAM,KAAK,KAAK,aAAa,EAAE;IAC/B,MAAM,KAAK,KAAK,YAAY,EAAE;IAC9B,MAAM,KAAK,KAAK,cAAc,EAAE;IAChC,MAAM,KAAK,KAAK,OAAO,EAAE,GAAG,MAAM,KAAK,QAAQ,EAAE;;EAEnD,MAAM,MAAM,KAAK,SAAS,EAAE;IAC1B,MAAM,KAAK,eAAe,EAAE;IAC5B,MAAM,KAAK,YAAY,EAAE;;EAE3B,MAAM,KAAK,wCAAwC,EAAE;CACtD;AACD"}
|
|
1
|
+
{"version":3,"file":"index.es.js","names":[],"sources":["../src/utils/package-manager.ts","../src/utils/project.ts","../src/commands/cloud/context.ts","../src/commands/init.ts","../src/commands/generate_sdk.ts","../src/commands/schema.ts","../src/commands/db.ts","../src/manifest.ts","../src/commands/dev.ts","../src/bundle.ts","../src/fold-static.ts","../src/commands/build.ts","../src/commands/eject.ts","../src/commands/start.ts","../src/commands/auth.ts","../src/commands/doctor.ts","../src/commands/skills.ts","../src/commands/api-keys.ts","../src/commands/cloud/auth.ts","../src/commands/cloud/link.ts","../src/commands/cloud/projects.ts","../src/commands/cloud/bundle-deploy.ts","../src/commands/cloud/deploy.ts","../src/commands/cloud/orgs.ts","../src/commands/cloud/databases.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/resources.ts","../src/commands/cloud/index.ts","../src/commands/apps.ts","../src/cli.ts"],"sourcesContent":["/**\n * Package manager detection and command abstraction.\n *\n * Detects whether the user is running pnpm or npm and provides\n * a unified interface for common package-manager operations so\n * the rest of the CLI never has to hardcode a specific PM.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { spawnSync } from \"child_process\";\n\nexport type PackageManager = \"pnpm\" | \"npm\";\n\nexport interface PMCommands {\n /** The binary name (\"pnpm\" | \"npm\"). */\n name: PackageManager;\n /** Install all dependencies — e.g. `pnpm install` / `npm install`. */\n install: string[];\n /** Run a script — e.g. `pnpm run dev` / `npm run dev`. */\n run: (script: string) => string[];\n /** Execute a local bin — e.g. `pnpm exec rebase ...` / `npx rebase ...`. */\n exec: (bin: string, args: string[]) => string[];\n /** Query the registry — e.g. `pnpm view <pkg> version` / `npm view <pkg> version`. */\n view: (pkg: string, field: string) => string[];\n /** Run all workspace scripts — e.g. `pnpm -r run build` / `npm run build --workspaces`. */\n runAll: (script: string) => string[];\n /** Run a script in a specific workspace — e.g. `pnpm --filter \"*-backend\" start` / `npm run start -w backend`. */\n runWorkspace: (workspace: string, script: string) => string[];\n /** Execute a one-off package — e.g. `pnpm dlx skills ...` / `npx -y skills ...`. */\n dlx: (pkg: string, args: string[]) => string[];\n /** The workspace dependency protocol: `\"workspace:*\"` for pnpm, `\"*\"` for npm. */\n workspaceProtocol: string;\n}\n\n/**\n * How long to wait for `pnpm --version` before giving up on the probe.\n *\n * `pnpm --version` is a cold Node start, and on a machine that is busy — a\n * parallel install, a full test run — it routinely takes seconds. Measured at\n * 630ms, 990ms and 4293ms on three consecutive runs of one developer laptop\n * under load, so the previous 3s budget was inside the normal spread rather\n * than safely outside it.\n */\nconst PNPM_PROBE_TIMEOUT_MS = 5000;\n\n/** Memoised result of the probe. pnpm cannot appear or vanish mid-process. */\nlet cachedPnpmAvailable: boolean | undefined;\n\n/**\n * Decide availability from a `spawnSync` outcome.\n *\n * Split out from the spawn itself so the decision is testable without starting\n * a process — which is what made the old test load-sensitive and occasionally\n * red for reasons that had nothing to do with the code under test.\n *\n * The three outcomes are distinguishable, and the old code conflated two of\n * them by asking only `status === 0`:\n *\n * not installed status null, signal null, error.code ENOENT\n * timed out status null, signal SIGTERM, error.code ETIMEDOUT\n * broken install status non-zero, no error\n */\nexport function pnpmAvailabilityFromProbe(res: {\n status: number | null;\n signal?: NodeJS.Signals | null;\n error?: { code?: string } | Error;\n}): boolean {\n const code = (res.error as { code?: string } | undefined)?.code;\n\n // The binary is not on PATH. Genuinely absent.\n if (code === \"ENOENT\") return false;\n\n // We killed it for taking too long. That means it WAS found and did start,\n // so pnpm is installed — it was merely slow, which on a loaded machine is\n // routine rather than exceptional. Reporting \"absent\" here is what silently\n // scaffolded npm projects for developers who had pnpm all along.\n //\n // The trade-off, stated plainly: a pnpm that hangs forever (a misbehaving\n // corepack shim) now resolves to pnpm instead of falling back to npm. That\n // is the rarer and more visible failure — the user sees their next command\n // hang — whereas the case this fixes was silent and produced a project\n // pinned to the wrong package manager. The timeout still bounds how long\n // detection itself waits, which was always its real job.\n if (code === \"ETIMEDOUT\" || res.signal) return true;\n\n // Any other spawn error: treat as unavailable rather than guess.\n if (res.error) return false;\n\n return res.status === 0;\n}\n\n/**\n * Whether pnpm is runnable on this machine.\n *\n * Used to decide whether a fresh project can be scaffolded with pnpm. Kept\n * cheap and non-interactive (bounded timeout, output discarded) so it never\n * hangs detection if a corepack shim misbehaves, and memoised so that repeated\n * detection in one CLI run costs one process rather than one per call.\n */\nexport function isPnpmAvailable(): boolean {\n if (cachedPnpmAvailable !== undefined) return cachedPnpmAvailable;\n try {\n const res = spawnSync(\"pnpm\", [\"--version\"], {\n stdio: \"ignore\",\n timeout: PNPM_PROBE_TIMEOUT_MS\n });\n cachedPnpmAvailable = pnpmAvailabilityFromProbe(res);\n } catch {\n cachedPnpmAvailable = false;\n }\n return cachedPnpmAvailable;\n}\n\n/** Forget the memoised probe. For tests; nothing in a CLI run needs it. */\nexport function resetPnpmAvailabilityCache(): void {\n cachedPnpmAvailable = undefined;\n}\n\n/**\n * Detect the package manager for a Rebase project.\n *\n * Rebase recommends pnpm, so detection prefers it. Crucially, *how the CLI was\n * invoked* (`npx` vs `pnpm dlx`, i.e. `npm_config_user_agent`) is deliberately\n * ignored: running `npx @rebasepro/cli init` says nothing about how the user\n * wants to manage the project they're creating, and letting it pin the scaffold\n * to npm is what made every `npx`-invoked project an npm project.\n *\n * Detection order:\n * 1. An existing lock file — an explicit choice we always respect\n * (`pnpm-lock.yaml` wins over `package-lock.json` when both are present).\n * 2. pnpm, whenever it is installed.\n * 3. npm, only as a fallback when pnpm is genuinely unavailable.\n */\nexport function detectPackageManager(targetDir?: string): PackageManager {\n // 1. Respect an existing project's lock file.\n const dirs = [targetDir, process.cwd()].filter((d): d is string => !!d);\n for (const dir of dirs) {\n if (fs.existsSync(path.join(dir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (fs.existsSync(path.join(dir, \"package-lock.json\"))) return \"npm\";\n }\n\n // 2. Prefer pnpm whenever it's installed.\n if (isPnpmAvailable()) return \"pnpm\";\n\n // 3. Fall back to npm only when pnpm is genuinely unavailable.\n return \"npm\";\n}\n\n/** Build the command helpers for a given package manager. */\nexport function getPMCommands(pm: PackageManager): PMCommands {\n if (pm === \"npm\") {\n return {\n name: \"npm\",\n install: [\"npm\", \"install\"],\n run: (script) => [\"npm\", \"run\", script],\n exec: (bin, args) => [\"npx\", bin, ...args],\n view: (pkg, field) => [\"npm\", \"view\", pkg, field],\n runAll: (script) => [\"npm\", \"run\", script, \"--workspaces\", \"--if-present\"],\n runWorkspace: (workspace, script) => [\"npm\", \"run\", script, \"-w\", workspace],\n dlx: (pkg, args) => [\"npx\", \"-y\", pkg, ...args],\n workspaceProtocol: \"*\"\n };\n }\n\n return {\n name: \"pnpm\",\n install: [\"pnpm\", \"install\"],\n run: (script) => [\"pnpm\", \"run\", script],\n exec: (bin, args) => [\"pnpm\", \"exec\", bin, ...args],\n view: (pkg, field) => [\"pnpm\", \"view\", pkg, field],\n runAll: (script) => [\"pnpm\", \"-r\", \"run\", script],\n // Filter by directory (`./backend`), not name: pnpm's `--filter` matches\n // the package *name* (e.g. `my-app-backend`), so a bare `backend` matches\n // nothing. npm's `-w` is path-based, which is why this only bites pnpm.\n runWorkspace: (workspace, script) => [\"pnpm\", \"--filter\", `./${workspace}`, \"run\", script],\n dlx: (pkg, args) => [\"pnpm\", \"dlx\", pkg, ...args],\n workspaceProtocol: \"workspace:*\"\n };\n}\n","/**\n * Project discovery utilities for the Rebase CLI.\n *\n * These helpers locate the project root, backend directory, .env file,\n * and local binaries — used by all CLI command modules.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\nimport chalk from \"chalk\";\n\n/** The authored project manifest. Its presence alone marks a project root. */\nexport const MANIFEST_FILENAME = \"rebase.json\";\n\n/**\n * Walk up from `startDir` to find the Rebase project root.\n *\n * A directory is the root when it holds a `rebase.json`, or when it holds a\n * `package.json` that either lists `backend` as a workspace or sits beside both\n * `backend/` and `config/`.\n *\n * `rebase.json` is checked first and needs no `package.json` beside it, because\n * the conventions below all describe a repository that *contains the backend*.\n * A repository holding only a frontend — the normal shape once a project's apps\n * live in separate repositories — matches none of them, so without this the\n * tooling could not run there at all.\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n if (fs.existsSync(path.join(dir, MANIFEST_FILENAME))) {\n return dir;\n }\n\n const pkgPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n // Check for workspace-based project (monorepo root)\n if (pkg.workspaces && Array.isArray(pkg.workspaces)) {\n const hasBackend = pkg.workspaces.some((w: string) =>\n w === \"backend\"\n );\n if (hasBackend) return dir;\n }\n } catch {\n // ignore parse errors\n }\n\n // Check for sibling backend directory\n if (fs.existsSync(path.join(dir, \"backend\")) && fs.existsSync(path.join(dir, \"config\"))) {\n return dir;\n }\n }\n\n dir = path.dirname(dir);\n }\n\n return null;\n}\n\n/**\n * Locate the backend directory within the project root.\n */\nexport function findBackendDir(projectRoot: string): string | null {\n const backendDir = path.join(projectRoot, \"backend\");\n return fs.existsSync(backendDir) ? backendDir : null;\n}\n\n/**\n * Detect the active backend plugin (e.g. @rebasepro/server-postgres) from the backend's package.json.\n */\nexport function getActiveBackendPlugin(backendDir: string): string | null {\n const pkgPath = path.join(backendDir, \"package.json\");\n if (!fs.existsSync(pkgPath)) return null;\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const deps = { ...pkg.dependencies,\n...pkg.devDependencies };\n\n // Collect all @rebasepro/server-* driver plugins (exclude server itself)\n const candidates = Object.keys(deps).filter(\n dep => dep.startsWith(\"@rebasepro/server-\") && dep !== \"@rebasepro/server\"\n );\n\n if (candidates.length === 0) return null;\n\n // Prefer server-postgres — it's the primary supported driver\n if (candidates.includes(\"@rebasepro/server-postgres\")) {\n return \"@rebasepro/server-postgres\";\n }\n\n // Fallback: return the first candidate that actually has a CLI entry point\n for (const candidate of candidates) {\n if (resolvePluginCliScript(backendDir, candidate)) {\n return candidate;\n }\n }\n\n // Last resort: return whatever we found\n return candidates[0];\n } catch {\n // Ignore parse errors\n }\n return null;\n}\n\n/**\n * Resolve the active plugin's CLI script.\n */\nexport function resolvePluginCliScript(backendDir: string, pluginName: string): string | null {\n const candidates: string[] = [];\n\n // Walk up from the backend dir: pnpm links the plugin into\n // backend/node_modules, while npm workspaces hoist it to the project (or an\n // enclosing monorepo) root.\n let dir = path.resolve(backendDir);\n const fsRoot = path.parse(dir).root;\n while (dir !== fsRoot) {\n candidates.push(\n path.join(dir, \"node_modules\", pluginName, \"src\", \"cli.ts\"),\n path.join(dir, \"node_modules\", pluginName, \"dist\", \"cli.js\")\n );\n dir = path.dirname(dir);\n }\n\n candidates.push(\n // For monorepo dev mode:\n path.resolve(backendDir, \"..\", \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\")\n );\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Locate the frontend directory within the project root.\n */\nexport function findFrontendDir(projectRoot: string): string | null {\n const frontendDir = path.join(projectRoot, \"frontend\");\n return fs.existsSync(frontendDir) ? frontendDir : null;\n}\n\n/**\n * Find the .env file. Checks the project root first, then backend.\n */\nexport function findEnvFile(projectRoot: string): string | null {\n const candidates = [\n path.join(projectRoot, \".env\"),\n path.join(projectRoot, \"backend\", \".env\")\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n return null;\n}\n\n/**\n * Resolve a binary from the project's node_modules/.bin.\n * Checks backend, root, parent monorepo root, then falls back to PATH.\n */\nexport function resolveLocalBin(projectRoot: string, binName: string): string | null {\n const candidates = [\n path.join(projectRoot, \"backend\", \"node_modules\", \".bin\", binName),\n path.join(projectRoot, \"node_modules\", \".bin\", binName)\n ];\n\n // Also check parent directories (for monorepo setups where app/ is nested)\n let parent = path.dirname(projectRoot);\n const rootDir = path.parse(parent).root;\n while (parent !== rootDir) {\n candidates.push(path.join(parent, \"node_modules\", \".bin\", binName));\n parent = path.dirname(parent);\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n // Fall back to globally installed binary via which\n try {\n const globalPath = execSync(`which ${binName}`, { encoding: \"utf-8\" }).trim();\n if (globalPath && fs.existsSync(globalPath)) return globalPath;\n } catch {\n // not found globally\n }\n\n return null;\n}\n\n/**\n * Resolve the tsx binary. Checks backend node_modules first, then root.\n */\nexport function resolveTsx(projectRoot: string): string | null {\n return resolveLocalBin(projectRoot, \"tsx\");\n}\n\n/**\n * Validate that a resolved tsx binary actually has an intact installation.\n *\n * `resolveLocalBin` only checks whether `node_modules/.bin/tsx` (a symlink)\n * exists. If the pnpm content-addressable store was cleaned or a previous\n * install was interrupted, the symlink can exist while critical files inside\n * the tsx package (e.g. `dist/preflight.cjs`) are missing — causing a\n * confusing MODULE_NOT_FOUND error at runtime.\n *\n * This function follows the symlink, walks up to find the tsx package root\n * (`package.json` with `name: \"tsx\"`), and verifies that `dist/preflight.cjs`\n * is present. Returns `null` when the installation looks healthy, or an\n * error description string when it appears corrupted.\n */\nexport function validateTsxInstallation(tsxBinPath: string): string | null {\n try {\n // Follow the symlink chain to the real tsx entry script\n const realPath = fs.realpathSync(tsxBinPath);\n\n // Walk up from the real binary to locate the tsx package root\n let dir = path.dirname(realPath);\n const fsRoot = path.parse(dir).root;\n for (let depth = 0; depth < 10 && dir !== fsRoot; depth++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg.name === \"tsx\") {\n // Found the tsx package root — verify critical preload file\n const preflightPath = path.join(dir, \"dist\", \"preflight.cjs\");\n if (!fs.existsSync(preflightPath)) {\n return `tsx package at ${dir} is missing dist/preflight.cjs`;\n }\n return null; // Installation looks healthy\n }\n } catch {\n // Malformed package.json — keep walking\n }\n }\n dir = path.dirname(dir);\n }\n\n // Could not determine tsx root — don't block, assume valid\n return null;\n } catch (err) {\n // realpathSync throws if the symlink target is completely gone\n return `tsx binary symlink is broken: ${err instanceof Error ? err.message : String(err)}`;\n }\n}\n\n/**\n * Require the project root or exit with a helpful error.\n */\nexport function requireProjectRoot(): string {\n const root = findProjectRoot();\n if (!root) {\n console.error(chalk.red(\"✗ Could not find a Rebase project root.\"));\n console.error(chalk.gray(\" Make sure you are inside a Rebase project directory\"));\n console.error(chalk.gray(\" (one with backend/, frontend/, and config/ directories).\"));\n process.exit(1);\n }\n return root;\n}\n\n/**\n * Require the backend directory or exit with a helpful error.\n */\nexport function requireBackendDir(projectRoot: string): string {\n const backendDir = findBackendDir(projectRoot);\n if (!backendDir) {\n console.error(chalk.red(\"✗ Could not find a backend/ directory.\"));\n console.error(chalk.gray(` Expected at: ${path.join(projectRoot, \"backend\")}`));\n process.exit(1);\n }\n return backendDir;\n}\n","/**\n * Shared foundation for the `rebase cloud` command family.\n *\n * Everything cloud subcommands need in common lives here:\n * - credential storage (~/.rebase/credentials.json, keyed per control-plane host)\n * - project link file (.rebase/cloud.json in the project dir)\n * - control-plane URL resolution\n * - an authenticated `@rebasepro/client` instance (createCloudClient / requireClient)\n * - small output helpers shared across subcommands\n *\n * The control plane is itself a Rebase app, so we reuse the same SDK the web\n * console uses (`@rebasepro/client`). Auth, token refresh, the data REST client\n * and function invocation all come from the SDK — the CLI only supplies a\n * file-backed AuthStorage so a login persists across invocations.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { spawn } from \"child_process\";\nimport chalk from \"chalk\";\nimport arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport { createRebaseClient, type AuthStorage } from \"@rebasepro/client\";\nimport { findProjectRoot } from \"../../utils/project\";\n\n/* ═══════════════════════════════════════════════════════════════\n Constants & paths\n ═══════════════════════════════════════════════════════════════ */\n\n/** Default hosted control plane (the Rebase Cloud console origin). */\nconst DEFAULT_CLOUD_URL = \"https://app.rebase.pro\";\n\n/** The storage key the SDK's auth module reads/writes the session under. */\nconst SDK_SESSION_KEY = \"rebase_auth\";\n\n/** ~/.rebase/credentials.json — one file, many hosts. */\nfunction credentialsPath(): string {\n return path.join(os.homedir(), \".rebase\", \"credentials.json\");\n}\n\n/** Project-local link file: <project>/.rebase/cloud.json */\nexport function projectLinkPath(cwd: string = process.cwd()): string {\n const root = findProjectRoot(cwd) || cwd;\n return path.join(root, \".rebase\", \"cloud.json\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Credentials file model\n ═══════════════════════════════════════════════════════════════\n\n {\n \"current\": \"https://app.rebase.pro\",\n \"contexts\": {\n \"https://app.rebase.pro\": { \"auth\": \"<sdk session json>\", \"org\": \"42\" }\n }\n }\n*/\n\ninterface CloudContextEntry {\n /** Raw JSON blob the SDK auth module persists (the RebaseSession). */\n auth?: string;\n /** Active organization id for this host, if the user selected one. */\n org?: string;\n}\n\ninterface CredentialsFile {\n current?: string;\n contexts: Record<string, CloudContextEntry>;\n}\n\nfunction readCredentials(): CredentialsFile {\n try {\n const raw = fs.readFileSync(credentialsPath(), \"utf-8\");\n const parsed = JSON.parse(raw) as CredentialsFile;\n if (!parsed.contexts) parsed.contexts = {};\n return parsed;\n } catch {\n return { contexts: {} };\n }\n}\n\nfunction writeCredentials(data: CredentialsFile): void {\n const file = credentialsPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n // Written with private perms — this file holds refresh tokens.\n fs.writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 });\n try {\n fs.chmodSync(file, 0o600);\n } catch {\n // best effort on platforms without chmod semantics\n }\n}\n\n/** Host that a bare `rebase cloud` command should target, if any. */\nfunction currentContextUrl(): string | undefined {\n return readCredentials().current;\n}\n\n/** Persist the active organization id for a host. */\nexport function setContextOrg(url: string, org: string | undefined): void {\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n if (org) entry.org = org;\n else delete entry.org;\n creds.contexts[url] = entry;\n writeCredentials(creds);\n}\n\nexport function getContextOrg(url: string): string | undefined {\n return readCredentials().contexts[url]?.org;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n File-backed AuthStorage (per host)\n ═══════════════════════════════════════════════════════════════ */\n\nfunction createFileAuthStorage(url: string): AuthStorage {\n return {\n getItem(key) {\n if (key !== SDK_SESSION_KEY) return null;\n return readCredentials().contexts[url]?.auth ?? null;\n },\n setItem(key, value) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n entry.auth = value;\n creds.contexts[url] = entry;\n if (!creds.current) creds.current = url;\n writeCredentials(creds);\n },\n removeItem(key) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n if (creds.contexts[url]) {\n delete creds.contexts[url].auth;\n delete creds.contexts[url].org;\n }\n writeCredentials(creds);\n }\n };\n}\n\n/** Mark a host as the active context (called on login). */\nexport function setCurrentContext(url: string): void {\n const creds = readCredentials();\n creds.current = url;\n if (!creds.contexts[url]) creds.contexts[url] = {};\n writeCredentials(creds);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n URL resolution\n ═══════════════════════════════════════════════════════════════\n\n Priority: --url flag > REBASE_CLOUD_URL env > linked project's url\n > stored current context > default hosted URL.\n*/\n\nexport function resolveCloudUrl(rawArgs: string[]): string {\n const parsed = arg({ \"--url\": String }, { argv: rawArgs.slice(2),\npermissive: true });\n const explicit = parsed[\"--url\"] || process.env.REBASE_CLOUD_URL;\n if (explicit) return normalizeUrl(explicit);\n\n const link = readLink();\n if (link?.url) return normalizeUrl(link.url);\n\n const current = currentContextUrl();\n if (current) return normalizeUrl(current);\n\n return DEFAULT_CLOUD_URL;\n}\n\nfunction normalizeUrl(url: string): string {\n let u = url.trim().replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(u)) u = `https://${u}`;\n return u;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Rebase client factory + auth guard\n ═══════════════════════════════════════════════════════════════ */\n\nexport type CloudClient = ReturnType<typeof createRebaseClient>;\n\n/**\n * Build an SDK client bound to a control-plane host, backed by the on-disk\n * credential store. `autoRefresh` is disabled so we never leave a dangling\n * setTimeout that keeps the CLI process alive; token refresh is done on demand\n * by `requireClient`.\n */\nexport function createCloudClient(url: string): CloudClient {\n return createRebaseClient({\n baseUrl: url,\n // Empty string disables the realtime socket — a short-lived CLI has no\n // use for it, and leaving it on opens a connection (and noisy errors)\n // on every invocation.\n websocketUrl: \"\",\n auth: {\n storage: createFileAuthStorage(url),\n persistSession: true,\n autoRefresh: false\n }\n });\n}\n\n/** Two minutes of head-room before a token is treated as expired. */\nconst EXPIRY_BUFFER_MS = 120_000;\n\n/**\n * Return an authenticated client for the resolved host, refreshing the access\n * token if it is close to expiry. Exits with a helpful message when there is no\n * usable session (never logged in, or the refresh token was revoked).\n */\nexport async function requireClient(rawArgs: string[]): Promise<{ client: CloudClient; url: string }> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n const session = client.auth.getSession();\n\n if (!session || !session.accessToken) {\n fail(\n `Not logged in to ${chalk.cyan(url)}.`,\n `Run ${chalk.bold(\"rebase cloud login\")} first.`\n );\n }\n\n if (session.expiresAt <= Date.now() + EXPIRY_BUFFER_MS) {\n try {\n await client.auth.refreshSession();\n } catch {\n fail(\n `Your session for ${chalk.cyan(url)} has expired.`,\n `Run ${chalk.bold(\"rebase cloud login\")} to sign in again.`\n );\n }\n }\n\n return { client,\nurl };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Tenant hostnames\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The base domain tenant projects are served at, as reported by the control\n * plane (`platform-config`, which derives it from the same TENANT_BASE_DOMAIN\n * the ingress and the console read — see saas/backend/src/utils/tenant-domain.ts).\n *\n * The CLI cannot know this value: it is per-deployment configuration (production\n * serves tenants at `apps.rebase.pro`, a dev control plane at `localhost`). It\n * used to be hardcoded to `rebase.pro`, so `cloud projects create` congratulated\n * the user with a URL that resolves nowhere near their app.\n *\n * Cached per host for the process: it is fixed for a control plane's lifetime,\n * and `projects list` formats one host per row off a single fetch.\n *\n * @returns the base domain, or `undefined` if the control plane doesn't serve\n * `platform-config` (an older deployment) or the request failed. A failure is\n * cached too — the caller renders a subdomain either way, and a short-lived\n * CLI should not retry once per row.\n */\nconst tenantBaseDomainCache = new Map<string, Promise<string | undefined>>();\n\nexport function fetchTenantBaseDomain(client: CloudClient, url: string): Promise<string | undefined> {\n let pending = tenantBaseDomainCache.get(url);\n if (!pending) {\n pending = client.functions\n .invoke<{ tenantBaseDomain?: string }>(\"platform-config\", undefined, { method: \"GET\" })\n .then((cfg) => cfg?.tenantBaseDomain?.trim() || undefined)\n .catch(() => undefined);\n tenantBaseDomainCache.set(url, pending);\n }\n return pending;\n}\n\n/**\n * Public host for a project — `<subdomain>.<base>`, or the bare subdomain when\n * the base domain is unknown.\n *\n * It deliberately never falls back to a guessed domain. The user copies this\n * string into a browser, so a plausible-but-wrong hostname is worse than an\n * obviously incomplete one: `acme.rebase.pro` looks reachable and isn't, while\n * `acme` reads as \"the subdomain is acme\" and prompts no wasted debugging.\n */\nexport function formatTenantHost(\n subdomain: string | undefined,\n baseDomain: string | undefined\n): string | undefined {\n if (!subdomain) return undefined;\n return baseDomain ? `${subdomain}.${baseDomain}` : subdomain;\n}\n\n/** The fields of a project row this module needs to render a host. */\nexport interface HostableProject {\n subdomain?: string;\n /** Resolved server-side; absent on control planes older than the host hook. */\n host?: string;\n}\n\n/**\n * The host to display for a project.\n *\n * Prefers `host` off the record: the control plane resolves it through the same\n * `tenantHost()` the ingress uses, so it accounts for the project's *cluster*\n * base domain. The CLI cannot compute that itself — `clusters` is admin-only\n * under RLS, so a normal user's token cannot read `baseDomain`, and a project on\n * a second cluster is served somewhere the platform default does not name.\n *\n * `baseDomain` (from `platform-config`) remains the fallback for a control plane\n * that predates the hook — right for the single-cluster case, which is every\n * project today.\n */\nexport function projectHost(\n project: HostableProject,\n baseDomain: string | undefined\n): string | undefined {\n return project.host || formatTenantHost(project.subdomain, baseDomain);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Project link file (.rebase/cloud.json)\n ═══════════════════════════════════════════════════════════════ */\n\nexport interface ProjectLink {\n url: string;\n projectId: string;\n /** The project's subdomain — the slug users see in console URLs and type into --project. */\n slug?: string;\n projectName?: string;\n orgId?: string;\n /**\n * Base URL of the project's own API.\n *\n * For a cloud project this is a convenience derived from the subdomain. For\n * a **self-hosted** project it is the entire link: there is no control plane\n * to look anything up in, so `projectId` is empty and this is what commands\n * resolve against.\n *\n * Keeping both kinds of link in one file is deliberate. A second link file\n * for self-hosting would fork every command that reads one, and the tooling\n * would drift into being cloud-only by accident.\n */\n apiUrl?: string;\n /**\n * How this checkout is linked. Absent means `cloud` — which is every link\n * written before this field existed.\n */\n mode?: \"cloud\" | \"direct\";\n}\n\nexport function readLink(cwd: string = process.cwd()): ProjectLink | null {\n try {\n return JSON.parse(fs.readFileSync(projectLinkPath(cwd), \"utf-8\")) as ProjectLink;\n } catch {\n return null;\n }\n}\n\nexport function writeLink(link: ProjectLink, cwd: string = process.cwd()): void {\n const file = projectLinkPath(cwd);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, JSON.stringify(link, null, 2));\n}\n\nexport function removeLink(cwd: string = process.cwd()): boolean {\n const file = projectLinkPath(cwd);\n if (fs.existsSync(file)) {\n fs.rmSync(file);\n return true;\n }\n return false;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * The raw project reference to operate on: explicit `--project` flag wins,\n * otherwise the linked project. Exits with guidance when neither is present.\n * The value is a slug (the project's subdomain, as shown in console URLs) or,\n * for old scripts and link files, a raw project UUID.\n */\nexport function requireProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n if (link?.projectId) return link.projectId;\n fail(\n \"No project specified and this directory is not linked.\",\n `Pass ${chalk.bold(\"--project <slug>\")} or run ${chalk.bold(\"rebase cloud link\")}.`\n );\n}\n\n/**\n * Resolve a project reference — slug or UUID — to the internal id the API\n * takes, or undefined when no such project is visible. Slugs cost one lookup;\n * UUIDs pass through untouched so linked directories and old scripts skip the\n * round-trip.\n */\nexport async function lookupProjectId(ref: string, client: CloudClient): Promise<string | undefined> {\n if (UUID_RE.test(ref)) return ref;\n const res = await client.data.collection(\"projects\").find({\n where: { subdomain: [\"==\", ref] },\n limit: 1\n });\n const row = res.data[0] as { id?: string | number } | undefined;\n return row?.id === undefined ? undefined : String(row.id);\n}\n\n/** Like `lookupProjectId`, but exits with guidance when the ref matches nothing. */\nexport async function resolveProjectRef(ref: string, client: CloudClient): Promise<string> {\n const id = await lookupProjectId(ref, client);\n if (id === undefined) {\n fail(\n `No project with slug ${chalk.bold(ref)}.`,\n `List yours with ${chalk.bold(\"rebase cloud projects\")}.`\n );\n }\n return id;\n}\n\n/** `requireProjectRef` + `resolveProjectRef` in one step. */\nexport async function requireProject(rawArgs: string[], client: CloudClient): Promise<string> {\n return resolveProjectRef(requireProjectRef(rawArgs), client);\n}\n\n/**\n * The project reference to SHOW: the slug the user typed or the linked slug.\n * Never resolves — for human output only. Old link files predate `slug` and\n * fall back to the stored id.\n */\nexport function displayProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n return link?.slug || link?.projectId || \"\";\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Machine-readable output mode\n ═══════════════════════════════════════════════════════════════\n\n Rebase is built for agents, and the CLI is their primary interface. An agent\n must never scrape a colorized table, so every cloud command can emit a single\n JSON value instead of human output.\n\n JSON mode is on when ANY of these hold:\n • `--json` was passed,\n • `REBASE_JSON=1` is set, or\n • stdout is not a TTY (piped/redirected — i.e. a program is reading it).\n\n In JSON mode a command prints exactly one JSON value to stdout and nothing\n else; errors print `{\"error\":{...}}` and exit non-zero. The mode is a\n process-global set once, at dispatch, by `initOutputMode` — every helper here\n (fail, reportError, emit) reads it so the whole family is consistent.\n*/\n\nlet JSON_MODE = false;\n\n/**\n * Resolve and latch the output mode for this invocation. Call once at the top of\n * `cloudCommand`, before anything can print or `fail`. Returns the resolved mode\n * (handy for tests, which otherwise leave it at its `false` default).\n */\nexport function initOutputMode(rawArgs: string[]): boolean {\n const parsed = arg({ \"--json\": Boolean }, { argv: rawArgs.slice(2), permissive: true });\n JSON_MODE =\n Boolean(parsed[\"--json\"]) ||\n process.env.REBASE_JSON === \"1\" ||\n process.stdout.isTTY !== true;\n return JSON_MODE;\n}\n\n/** Whether the current invocation is emitting machine-readable JSON. */\nexport function isJsonMode(): boolean {\n return JSON_MODE;\n}\n\n/** Force the mode (tests only — production latches it via `initOutputMode`). */\nexport function setJsonModeForTest(value: boolean): void {\n JSON_MODE = value;\n}\n\n/** Strip ANSI colour codes — JSON output must never carry terminal escapes. */\n// eslint-disable-next-line no-control-regex\nconst ANSI_RE = /\u001b\\[[0-9;]*m/g;\nfunction stripAnsi(s: string): string {\n return s.replace(ANSI_RE, \"\");\n}\n\n/**\n * Write one JSON value to stdout, followed by a newline.\n *\n * Indented, because the overwhelmingly common reader is a person or an agent\n * looking at a terminal — JSON mode is entered automatically whenever stdout is\n * not a TTY, so `rebase cloud deployments list` piped anywhere at all produced\n * a project's entire deployment history as one unwrapped line. `JSON.parse`\n * does not care about the whitespace; everything else does.\n */\nexport function printJson(value: unknown): void {\n process.stdout.write(JSON.stringify(value, null, 2) + \"\\n\");\n}\n\n/**\n * The one output primitive every new command uses: in JSON mode emit `json`\n * (and nothing else); otherwise run `human`. Keeping the two behind a single\n * call is what guarantees a command can never print a table AND a JSON blob.\n */\nexport function emit(human: () => void, json: unknown): void {\n if (JSON_MODE) printJson(json);\n else human();\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Output helpers\n ═══════════════════════════════════════════════════════════════ */\n\n/** Print an error (+ optional hint) and exit non-zero. Never returns. */\nexport function fail(message: string, hint?: string, code?: string): never {\n if (JSON_MODE) {\n printJson({ error: { message: stripAnsi(message), code: code ?? null, hint: hint ? stripAnsi(hint) : undefined } });\n process.exit(1);\n }\n console.error(\"\");\n console.error(chalk.red(` ✗ ${message}`));\n if (hint) console.error(chalk.gray(` ${hint}`));\n console.error(\"\");\n process.exit(1);\n}\n\n/**\n * Confirm a destructive/irreversible action, respecting non-interactive use.\n *\n * With `--yes`/`-y` it proceeds silently. In JSON mode or a non-TTY it REFUSES\n * to prompt — a prompt that can hang is a known repo landmine — and fails,\n * telling the caller to pass `--yes`. Only an interactive terminal gets a real\n * confirm prompt; declining there aborts cleanly (exit 0).\n */\nexport async function confirmDestructive(opts: { yes: boolean; prompt: string }): Promise<void> {\n if (opts.yes) return;\n if (JSON_MODE || process.stdin.isTTY !== true) {\n fail(\n \"This action is destructive and needs confirmation.\",\n `Re-run with ${chalk.bold(\"--yes\")} to proceed.`,\n \"confirmation_required\"\n );\n }\n const { confirmed } = (await inquirer.prompt([\n { type: \"confirm\", name: \"confirmed\", default: false, message: opts.prompt }\n ] as unknown as Parameters<typeof inquirer.prompt>[0])) as { confirmed: boolean };\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n process.exit(0);\n }\n}\n\n/**\n * Positional tokens after `rebase cloud` — `[group, action, arg1, …]`.\n *\n * Deliberately NOT `arg({}, { permissive: true })._`: in permissive mode `arg`\n * pushes UNKNOWN FLAGS onto `_` too, so `rollback --yes --json` would report\n * `--yes` as the deployment id. Operand extraction must see operands only, so\n * anything starting with `-` is dropped — the same filter the db backup handler\n * has always used.\n */\nexport function cloudPositionals(rawArgs: string[]): string[] {\n return rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"));\n}\n\nexport function success(message: string): void {\n console.log(\"\");\n console.log(chalk.bold.green(` ✓ ${message}`));\n console.log(\"\");\n}\n\n/** Colorize a deployment / resource status token. */\nexport function colorStatus(status: string | undefined): string {\n switch (status) {\n case \"active\":\n case \"success\":\n case \"connected\":\n return chalk.green(status);\n case \"deploying\":\n case \"provisioning\":\n case \"pending_billing\":\n case \"untested\":\n return chalk.yellow(status ?? \"\");\n case \"failed\":\n return chalk.red(status);\n case \"stopped\":\n return chalk.gray(status);\n default:\n return chalk.gray(status ?? \"unknown\");\n }\n}\n\n/**\n * Render a two-column key/value block with aligned keys. Empty rows are skipped\n * — including `null`, which the API sends for an unset column and which used to\n * print the literal string \"null\" (e.g. `Custom domain: null`).\n */\nexport function keyValues(rows: Array<[string, string | null | undefined]>): void {\n const width = Math.max(...rows.map(([k]) => k.length));\n for (const [k, v] of rows) {\n if (v === undefined || v === null || v === \"\") continue;\n console.log(` ${chalk.gray(`${k}:`.padEnd(width + 1))} ${v}`);\n }\n}\n\n/**\n * Surface an SDK/HTTP error consistently. The SDK throws RebaseApiError with\n * a `.status` and `.message`; anything else falls back to its string form.\n */\nexport function reportError(e: unknown, context: string): never {\n const err = e as { status?: number; message?: string; code?: string };\n if (JSON_MODE) {\n printJson({\n error: {\n message: err?.message ? stripAnsi(err.message) : String(e),\n code: err?.code ?? null,\n status: err?.status ?? null,\n context\n }\n });\n process.exit(1);\n }\n const status = err?.status ? ` (${err.status})` : \"\";\n fail(`${context}${status}: ${err?.message ?? String(e)}`);\n}\n\n/**\n * Open a URL in the user's default browser (best effort). Always prints the URL\n * first so it stays usable over SSH or when no browser is available.\n */\nexport function openUrl(target: string, label = \"Opening\"): void {\n console.log(\"\");\n console.log(` ${label} ${chalk.cyan(target)}`);\n console.log(\"\");\n const opener =\n process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n try {\n const child = spawn(opener, [target], {\n stdio: \"ignore\",\n detached: true,\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", () => {\n /* URL already printed for manual copy */\n });\n child.unref();\n } catch {\n /* URL already printed */\n }\n}\n","import arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport { promisify } from \"util\";\nimport { execa } from \"execa\";\nimport { cp } from \"fs/promises\";\nimport { fileURLToPath } from \"url\";\nimport crypto from \"crypto\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { resolveCloudUrl, writeLink } from \"./cloud/context\";\nimport type { PackageManager, PMCommands } from \"../utils/package-manager\";\n\nconst access = promisify(fs.access);\n\n\n// Resolve template path relative to this file\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction findParentDir(currentDir: string, targetName: string): string | null {\n const root = path.parse(currentDir).root;\n while (currentDir && currentDir !== root) {\n if (path.basename(currentDir) === targetName) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nconst cliRoot = findParentDir(__dirname, \"cli\");\n\nconst PROJECT_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;\n\n/**\n * Every scaffolded file that carries a `{{PLACEHOLDER}}`.\n *\n * Exported because it is the single source of truth: `init.test.ts` reads it and\n * asserts that every template file containing `{{` appears here. It used to be a\n * local, with the test harness keeping a *second* copy — so the two drifted, and\n * a test built on the copy could not observe the production list at all.\n *\n * The drift shipped: `docker-compose.yml` arrived with the self-host work\n * (26fd5259c) and was added to neither, so every scaffolded project got a literal\n * `name: {{PROJECT_NAME}}`. In YAML `{{...}}` is a map, not a string, so the\n * documented `docker compose up` path failed on the file before doing anything:\n *\n * yaml: unmarshal errors: line 28: cannot unmarshal !!map into string\n */\nexport const TEMPLATE_PLACEHOLDER_FILES = [\n \"package.json\",\n \"frontend/package.json\",\n \"backend/package.json\",\n \"config/package.json\",\n \"frontend/index.html\",\n \"pnpm-workspace.yaml\",\n \"docker-compose.yml\",\n \"README.md\"\n];\n\n/** Returns an error message, or null when the name is a valid package name. */\nexport function validateProjectName(name: string): string | null {\n if (!name.trim()) return \"Project name is required\";\n if (!PROJECT_NAME_RE.test(name)) {\n return \"Project name must start with a lowercase letter or number and contain only lowercase letters, numbers, hyphens, dots, or underscores\";\n }\n return null;\n}\n\nexport type TemplatePreset = \"blog\" | \"ecommerce\" | \"blank\";\n\n/**\n * Whether to scaffold the admin panel alongside the backend.\n *\n * A boolean, not a named pair. It was `--flavor cms|baas`, and neither word\n * survived what they described: \"cms\" is a product category rather than a thing\n * this tool builds, and \"baas\" was the same value that used to appear as\n * `backend.mode` — which is now derived from whether collections are declared.\n * What is left is one question: does this project get an admin UI?\n */\nconst HEADLESS_CHOICES: Array<{ name: string; value: boolean; short: string }> = [\n { name: \"Backend + admin — API plus an admin UI, driven by collections you define (like Payload/Directus)\",\nvalue: false,\nshort: \"Backend + admin\" },\n { name: \"Backend only — headless API over your database. No collections, no UI (like Supabase)\",\nvalue: true,\nshort: \"Backend only\" }\n];\n\nconst PRESET_CHOICES: Array<{ name: string; value: TemplatePreset; short: string }> = [\n { name: \"Blog — Posts, Authors, Tags (with markdown editor)\",\nvalue: \"blog\",\nshort: \"Blog\" },\n { name: \"E-commerce — Products, Categories, Orders\",\nvalue: \"ecommerce\",\nshort: \"E-commerce\" },\n { name: \"Blank — Empty project, just authentication\",\nvalue: \"blank\",\nshort: \"Blank\" }\n];\n\nexport interface InitOptions {\n projectName: string;\n git: boolean;\n installDeps: boolean;\n targetDirectory: string;\n templateDirectory: string;\n databaseUrl?: string;\n introspect?: boolean;\n /** Starter template preset. */\n preset: TemplatePreset;\n /** Whether `preset` came from an explicit --template rather than the default. */\n explicitPreset?: boolean;\n /** Scaffold the backend alone, with no admin panel and no collections. */\n headless: boolean;\n /** Detected package manager (pnpm or npm). */\n pm: PackageManager;\n /** Command helpers for the detected PM. */\n pmCommands: PMCommands;\n /** Cloud project slug (its subdomain) to link the scaffold to. */\n cloudProject?: string;\n /** One-time setup key that authenticates the cloud link. */\n setupKey?: string;\n /** Control-plane URL the setup key is redeemed against. */\n cloudUrl?: string;\n}\n\nexport interface BuildQuestionsParams {\n nameArg?: string;\n templateArg?: TemplatePreset;\n headlessArg?: boolean;\n hasGitFlag: boolean;\n hasInstallFlag: boolean;\n pm: PackageManager;\n}\n\n/**\n * Builds the interactive prompt questions for `rebase init`.\n * Exported for testability — all prompt `type` values must match\n * types registered by the installed version of inquirer.\n */\nexport function buildInitQuestions(params: BuildQuestionsParams): Record<string, unknown>[] {\n const { nameArg, templateArg, headlessArg, hasGitFlag, hasInstallFlag, pm } = params;\n const questions: Record<string, unknown>[] = [];\n\n if (!nameArg) {\n questions.push({\n type: \"input\",\n name: \"projectName\",\n message: \"Project name:\",\n default: \"my-rebase-app\",\n validate: (input: string) => validateProjectName(input) ?? true\n });\n }\n\n if (headlessArg === undefined) {\n questions.push({\n type: \"select\",\n name: \"headless\",\n message: \"What do you want to build?\",\n choices: HEADLESS_CHOICES,\n default: false\n });\n }\n\n if (!templateArg) {\n questions.push({\n type: \"select\",\n name: \"preset\",\n message: \"Choose a starter template:\",\n choices: PRESET_CHOICES,\n default: \"blog\",\n // A headless project has no collection files, so a preset is moot.\n when: (answers: Record<string, unknown>) => !(headlessArg ?? answers.headless)\n });\n }\n\n if (!hasGitFlag) {\n questions.push({\n type: \"confirm\",\n name: \"git\",\n message: \"Initialize a git repository?\",\n default: true\n });\n }\n\n if (!hasInstallFlag) {\n questions.push({\n type: \"confirm\",\n name: \"installDeps\",\n message: `Install dependencies with ${pm}?`,\n default: true\n });\n }\n\n questions.push({\n type: \"input\",\n name: \"databaseUrl\",\n message: \"Enter your PostgreSQL database connection string (leave blank to use a local default):\",\n default: \"\",\n validate: (input: string) => {\n if (input.trim() && /[\\r\\n]/.test(input)) {\n return \"Database URL cannot contain newline characters.\";\n }\n return true;\n }\n });\n\n questions.push({\n type: \"confirm\",\n name: \"introspect\",\n message: \"Would you like to introspect this database to automatically generate collections?\",\n default: true,\n when: (answers: Record<string, unknown>) => !!(answers.databaseUrl as string)?.trim()\n });\n\n return questions;\n}\n\n/**\n * The `cd` a user must type to enter the new project.\n *\n * Not the project's basename: `init apps/my-app` has to say `cd apps/my-app`,\n * and `init .` returns \"\" because they are already in the project.\n */\nexport function formatCdTarget(cwd: string, targetDirectory: string): string {\n return path.relative(cwd, targetDirectory);\n}\n\n/** Help for `rebase init` — the flags were previously only discoverable by\n * triggering the non-TTY error. */\nexport function printInitHelp(): void {\n console.log(`\n${chalk.bold(\"rebase init\")} — Create a new Rebase project\n\n${chalk.bold(\"Usage\")}\n rebase init ${chalk.blue(\"[name]\")} [options]\n\n ${chalk.gray(\"The name may be a nested path (apps/my-app) or \\\".\\\" for the current directory.\")}\n ${chalk.gray(\"Defaults to \\\"my-rebase-app\\\" when omitted with --yes.\")}\n\n${chalk.bold(\"Options\")}\n ${chalk.blue(\"-t, --template\")} ${chalk.gray(\"<preset>\")} blog | ecommerce | blank ${chalk.gray(\"(default: blog)\")}\n ${chalk.blue(\"--headless\")} Backend only — no admin panel, no collections\n ${chalk.blue(\"-y, --yes\")} Accept defaults, never prompt ${chalk.gray(\"(required for CI / non-TTY)\")}\n ${chalk.blue(\"-i, --install\")} Install dependencies after scaffolding\n ${chalk.blue(\"-g, --git\")} Initialize a git repository and make an initial commit\n ${chalk.blue(\"--database-url\")} ${chalk.gray(\"<url>\")} Use an existing database instead of the generated one\n ${chalk.blue(\"--introspect\")} Generate collections from that database ${chalk.gray(\"(implies --template blank; needs --install)\")}\n ${chalk.blue(\"--project\")} ${chalk.gray(\"<slug>\")} Link the scaffold to a Rebase Cloud project\n ${chalk.blue(\"--setup-key\")} ${chalk.gray(\"<key>\")} One-time key authenticating the cloud link ${chalk.gray(\"(use with --project)\")}\n\n${chalk.bold(\"What gets scaffolded\")}\n ${chalk.gray(\"default\")} Backend + an admin UI, driven by collections you define ${chalk.gray(\"(like Payload/Directus)\")}\n ${chalk.blue(\"--headless\")} Backend only, over your existing database ${chalk.gray(\"(like Supabase)\")}\n ${chalk.gray(\"--template has no effect: there are no collections to seed.\")}\n\n${chalk.bold(\"Examples\")}\n ${chalk.gray(\"$\")} rebase init my-shop --template ecommerce --install\n ${chalk.gray(\"$\")} rebase init my-api --headless --yes\n ${chalk.gray(\"$\")} rebase init . --yes --git\n`);\n}\n\nexport async function createRebaseApp(rawArgs: string[]) {\n if (rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n printInitHelp();\n return;\n }\n\n console.log(`\n${chalk.bold(\"Rebase\")} — Create a new project 🚀\n`);\n\n const pm = detectPackageManager();\n const options = await promptForOptions(rawArgs, pm);\n await createProject(options);\n}\n\nasync function promptForOptions(rawArgs: string[], pm: PackageManager): Promise<InitOptions> {\n const args = arg(\n {\n \"--git\": Boolean,\n \"--install\": Boolean,\n \"--database-url\": String,\n \"--introspect\": Boolean,\n \"--template\": String,\n \"--headless\": Boolean,\n \"--project\": String,\n \"--setup-key\": String,\n \"--yes\": Boolean,\n \"-g\": \"--git\",\n \"-i\": \"--install\",\n \"-t\": \"--template\",\n \"-y\": \"--yes\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node\", \"rebase\", \"init\"\n permissive: true\n }\n );\n\n // The first positional arg after \"init\" is the project name\n const nameArg = args._[0];\n const isNonInteractive = args[\"--yes\"] || false;\n\n // The interactive prompt validates typed names; a name passed as an\n // argument must pass the same check or it becomes an invalid package.json\n // \"name\" that only fails later, at install time. Validate the basename so\n // nested paths (\"apps/my-app\") and \".\" still work.\n if (nameArg) {\n const resolvedName = path.basename(path.resolve(process.cwd(), nameArg));\n const nameError = validateProjectName(resolvedName);\n if (nameError) {\n console.error(chalk.red(`Invalid project name \"${resolvedName}\": ${nameError}`));\n process.exit(1);\n }\n }\n\n const templateArg = args[\"--template\"] as TemplatePreset | undefined;\n if (templateArg && !PRESET_CHOICES.some(p => p.value === templateArg)) {\n console.error(chalk.red(`Unknown template \"${templateArg}\". Available: ${PRESET_CHOICES.map(p => p.value).join(\", \")}`));\n process.exit(1);\n }\n\n const headlessArg = args[\"--headless\"] === true ? true : undefined;\n\n if (isNonInteractive) {\n const projectName = nameArg || \"my-rebase-app\";\n const targetDirectory = path.resolve(process.cwd(), projectName);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName: path.basename(targetDirectory),\n git: args[\"--git\"] ?? false,\n installDeps: args[\"--install\"] ?? false,\n targetDirectory,\n templateDirectory,\n databaseUrl: args[\"--database-url\"] || undefined,\n introspect: args[\"--introspect\"] || false,\n preset: templateArg || \"blog\",\n explicitPreset: !!templateArg,\n headless: headlessArg ?? false,\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n }\n\n // A non-interactive stdin (CI, a pipe, no TTY) can't answer prompts:\n // inquirer either blocks forever waiting for input or aborts with a raw\n // ExitPromptError stack trace. Fail fast with actionable guidance instead.\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"Cannot prompt: this is a non-interactive terminal (no TTY).\"));\n console.error(chalk.yellow(\" Re-run with --yes to accept defaults, passing any choices as flags, e.g.:\"));\n console.error(chalk.yellow(` rebase init ${nameArg || \"my-app\"} --yes --template blog`));\n console.error(chalk.gray(\" Options: --template <blog|ecommerce|blank> --headless --database-url <url> --install --git\"));\n process.exit(1);\n }\n\n const questions = buildInitQuestions({\n nameArg,\n templateArg,\n headlessArg,\n hasGitFlag: !!args[\"--git\"],\n hasInstallFlag: !!args[\"--install\"],\n pm\n });\n\n\n const answers = await inquirer.prompt(questions as unknown as Parameters<typeof inquirer.prompt>[0]);\n\n const targetDirectory = path.resolve(process.cwd(), nameArg || answers.projectName);\n const projectName = path.basename(targetDirectory);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName,\n git: args[\"--git\"] || answers.git || false,\n installDeps: args[\"--install\"] || answers.installDeps || false,\n targetDirectory,\n templateDirectory,\n databaseUrl: (answers.databaseUrl as string)?.trim() || undefined,\n introspect: answers.introspect || false,\n preset: templateArg || (answers.preset as TemplatePreset) || \"blog\",\n // Only a flag is \"explicit\" here: the interactive path never asks for a\n // preset once baas is chosen, so it can't produce a conflicting answer.\n explicitPreset: !!templateArg,\n headless: headlessArg ?? Boolean(answers.headless),\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n}\n\n/**\n * Redeem the one-time setup key from the console's setup page and write the\n * `.rebase/cloud.json` link into the scaffold, so `rebase cloud deploy` etc.\n * work in the new directory with no further flags. `--project` carries the\n * project's slug (its subdomain, as shown in console URLs); the control plane\n * also accepts a raw id for old copies of the command.\n *\n * Best-effort by design: a failed link must never fail the scaffold, so every\n * exit path other than success is a warning plus instructions to link later.\n */\nasync function linkScaffoldToCloud(options: InitOptions): Promise<void> {\n if (!options.cloudProject && !options.setupKey) return;\n\n const linkLater = `Link it later with ${chalk.bold(\"rebase cloud login\")} then ${chalk.bold(\"rebase cloud link\")}.`;\n if (!options.cloudProject || !options.setupKey) {\n console.warn(chalk.yellow(\" --project and --setup-key go together; skipping the cloud link.\"));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n\n try {\n const res = await fetch(`${options.cloudUrl}/api/functions/setup-key/validate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ projectId: options.cloudProject,\nsetupKey: options.setupKey })\n });\n const body = (await res.json().catch(() => ({}))) as {\n error?: { message?: string };\n project?: { id?: string | number; subdomain?: string; name?: string };\n };\n if (!res.ok || body.project?.id === undefined) {\n console.warn(chalk.yellow(` Could not verify the setup key: ${body.error?.message || res.statusText}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n writeLink(\n {\n url: String(options.cloudUrl),\n projectId: String(body.project.id),\n slug: body.project.subdomain,\n projectName: body.project.name\n },\n options.targetDirectory\n );\n console.log(\"\");\n console.log(` ${chalk.green(\"✓\")} Linked to cloud project ${chalk.bold(body.project.subdomain ?? options.cloudProject)}`);\n } catch (e) {\n console.warn(chalk.yellow(` Could not reach the control plane: ${e instanceof Error ? e.message : String(e)}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n }\n}\n\nasync function createProject(options: InitOptions) {\n // Check if directory already exists and is not empty\n if (fs.existsSync(options.targetDirectory)) {\n if (fs.readdirSync(options.targetDirectory).length !== 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} Directory \"${options.projectName}\" already exists and is not empty`);\n process.exit(1);\n }\n } else {\n fs.mkdirSync(options.targetDirectory, { recursive: true });\n }\n\n // Verify template exists\n try {\n await access(options.templateDirectory, fs.constants.R_OK);\n } catch {\n console.error(`${chalk.red.bold(\"ERROR\")} Template not found at ${options.templateDirectory}`);\n process.exit(1);\n }\n\n // Copy template files\n console.log(chalk.gray(\" Copying project files...\"));\n try {\n await cp(options.templateDirectory, options.targetDirectory, {\n recursive: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n // Skip node_modules and .DS_Store\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n } catch (err: unknown) {\n console.error(`${chalk.red.bold(\"ERROR\")} Failed to copy template files: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n // npm/pnpm always strip files named .gitignore and .npmrc from published\n // tarballs, so the template ships them un-dotted and we restore the real\n // names here.\n for (const [from, to] of [[\"gitignore\", \".gitignore\"], [\"npmrc\", \".npmrc\"]] as const) {\n const shipped = path.join(options.targetDirectory, from);\n if (fs.existsSync(shipped)) {\n fs.renameSync(shipped, path.join(options.targetDirectory, to));\n }\n }\n\n // Apply the selected template preset (swap collection files)\n if (options.headless && options.explicitPreset) {\n // baas has no collections, so there is nothing for a preset to swap.\n // Say so rather than accepting the flag and silently dropping it.\n console.log(chalk.yellow(` Ignoring --template ${options.preset}: a headless project declares no collections.`));\n }\n if (!options.headless) {\n // When introspecting, the database is the source of truth: start from\n // the blank preset so example collections never register on top of\n // tables the database doesn't have.\n if (options.introspect && options.preset !== \"blank\") {\n console.log(chalk.gray(\" Using the blank template: collections will come from your database.\"));\n }\n await applyPreset(options.targetDirectory, options.introspect ? \"blank\" : options.preset);\n }\n\n // Reduce the project to the selected shape\n await applyHeadless(options.targetDirectory, options.headless);\n\n // Replace placeholder project name in package.json files\n await replacePlaceholders(options);\n\n // Rename .env.example to .env if it exists and randomize secrets\n await configureEnvFile(options.targetDirectory, options.databaseUrl);\n\n // Initialize git\n if (options.git) {\n console.log(chalk.gray(\" Initializing git repository...\"));\n try {\n await execa(\"git\", [\"init\"], { cwd: options.targetDirectory });\n // Name the branch `main` rather than inheriting whatever\n // `init.defaultBranch` is (often still `master`). `git init -b` would\n // be the obvious way, but it needs git >= 2.28; rewriting HEAD works\n // on every version and is safe before the first commit.\n try {\n await execa(\"git\", [\"symbolic-ref\", \"HEAD\", \"refs/heads/main\"], { cwd: options.targetDirectory });\n } catch {\n // Leave the default branch name; not worth failing the scaffold.\n }\n // Leaving the tree uncommitted makes the very first `git diff`\n // useless and hides the scaffold in a wall of untracked files.\n // .gitignore is already in place, so .env is never committed.\n await execa(\"git\", [\"add\", \"-A\"], { cwd: options.targetDirectory });\n // A machine with no user.email configured cannot commit at all.\n // Supply an identity only in that case, so a configured user still\n // authors their own initial commit.\n let identity: Record<string, string> = {};\n try {\n await execa(\"git\", [\"config\", \"user.email\"], { cwd: options.targetDirectory });\n } catch {\n identity = {\n GIT_AUTHOR_NAME: \"Rebase\", GIT_AUTHOR_EMAIL: \"noreply@rebase.pro\",\n GIT_COMMITTER_NAME: \"Rebase\", GIT_COMMITTER_EMAIL: \"noreply@rebase.pro\"\n };\n }\n await execa(\"git\", [\"commit\", \"-m\", \"Initial commit from Rebase\"], {\n cwd: options.targetDirectory,\n env: identity\n });\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to initialize git repository\"));\n }\n }\n\n const { pm, pmCommands } = options;\n const installCmd = pmCommands.install;\n const execCmd = pmCommands.exec(\"rebase\", [\"schema\", \"introspect\", \"--force\"]);\n const generateCmd = pmCommands.exec(\"rebase\", [\"schema\", \"generate\", \"--collections\", \"../config/collections\"]);\n\n if (options.installDeps) {\n console.log(\"\");\n console.log(chalk.gray(` Installing dependencies with ${pm}...`));\n console.log(\"\");\n try {\n await execa(installCmd[0], installCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n } catch {\n console.warn(chalk.yellow(` Warning: Failed to install dependencies. You may need to run \\`${installCmd.join(\" \")}\\` manually.`));\n }\n }\n\n // Whether introspection actually ran and produced collections. The next\n // steps below report what really happened, so a skipped or failed\n // introspection is never announced as a success.\n let introspected = false;\n\n if (options.introspect) {\n console.log(\"\");\n if (options.installDeps) {\n console.log(chalk.gray(\" Introspecting database and generating collections...\"));\n console.log(\"\");\n try {\n // --force overwrites template example collections with real ones\n await execa(execCmd[0], execCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n // The template ships a schema.generated.ts for the example blog\n // collections; regenerate it from the introspected collections or\n // the backend serves a schema that doesn't match the database.\n await execa(generateCmd[0], generateCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n console.log(chalk.green(\" Database successfully introspected!\"));\n introspected = true;\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to introspect database automatically.\"));\n console.warn(chalk.yellow(` You can run \\`${execCmd.join(\" \")}\\` then \\`${generateCmd.join(\" \")}\\` manually after setup.`));\n }\n } else {\n console.warn(chalk.yellow(\" Skipping introspection because dependencies were not installed.\"));\n console.warn(chalk.yellow(` Run \\`${installCmd.join(\" \")}\\` then \\`${execCmd.join(\" \")}\\` manually.`));\n }\n }\n\n await linkScaffoldToCloud(options);\n\n // Success message\n console.log(\"\");\n console.log(`${chalk.green.bold(\"✓\")} Project ${chalk.bold(options.projectName)} created successfully!`);\n console.log(\"\");\n console.log(chalk.bold(\"Next steps:\"));\n console.log(\"\");\n const runDev = pmCommands.run(\"dev\");\n const runDbPush = pmCommands.run(\"db:push\");\n const isBaas = options.headless;\n // The path the user has to type, not the project's basename: `init\n // apps/my-app` must say `cd apps/my-app`, and `init .` needs no cd at all\n // because they are already standing in the project.\n const cdTarget = formatCdTarget(process.cwd(), options.targetDirectory);\n if (cdTarget) {\n console.log(` ${chalk.cyan(\"cd\")} ${cdTarget}`);\n }\n if (!options.installDeps) {\n console.log(` ${chalk.cyan(installCmd.join(\" \"))}`);\n }\n console.log(\"\");\n\n if (options.databaseUrl) {\n if (introspected) {\n console.log(chalk.gray(\" # Database has been introspected & collections generated!\"));\n console.log(chalk.gray(\" # Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else if (options.introspect) {\n // Introspection was requested but did not run. Point at the steps\n // that finish the job rather than claiming collections exist.\n console.log(chalk.gray(\" # Introspection did not run — finish it with:\"));\n console.log(` ${chalk.cyan(execCmd.join(\" \"))}`);\n console.log(` ${chalk.cyan(generateCmd.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # Then start the development server:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # Your custom database is configured in .env.\"));\n console.log(chalk.gray(\" # If the database is empty, push the Rebase schema to initialize it:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # Then start the development server:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n } else if (isBaas) {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Create your tables (migrations, SQL, any tool you like).\"));\n console.log(chalk.gray(\" # A table is served once it has an authorization model, i.e.\"));\n console.log(chalk.gray(\" # row-level security enabled plus at least one policy:\"));\n console.log(` ${chalk.cyan(\"ALTER TABLE your_table ENABLE ROW LEVEL SECURITY;\")}`);\n console.log(chalk.gray(\" # The API logs any table it skips, and why.\"));\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the API — every protected table is served automatically:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Push the Rebase schema to initialize database tables:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n\n console.log(\"\");\n console.log(isBaas\n ? chalk.gray(\"This starts a headless API (Hono + PostgreSQL). There are no collection files: \")\n + chalk.gray(\"the API is derived from your database schema. Once it serves a table, docs are at /api/swagger.\")\n : chalk.gray(\"This starts both the backend (Hono + PostgreSQL)\")\n + chalk.gray(\" and the frontend (Vite + React) concurrently.\"));\n console.log(\"\");\n console.log(chalk.gray(\"Docs: https://rebase.pro/docs\"));\n console.log(chalk.gray(\"GitHub: https://github.com/rebasepro/rebase\"));\n console.log(\"\");\n console.log(chalk.bold(\"🤖 AI Agent Skills\"));\n console.log(\"\");\n console.log(chalk.gray(\" Install Rebase agent skills for your AI coding assistant:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(\"rebase skills install\")} ${chalk.gray(\"or\")} ${chalk.cyan(pmCommands.run(\"skills:install\").join(\" \"))}`);\n console.log(\"\");\n}\n\n/**\n * Apply a template preset by replacing the default collection files.\n *\n * The template ships with blog collections at the top level and\n * preset alternatives under `config/collections/presets/<name>/`.\n * This function swaps the active collection files and removes the\n * presets directory so the final project is clean.\n */\n/**\n * Reduce the scaffolded project to the chosen shape.\n *\n * The base template is the full triad. `--headless` drops the frontend and the\n * declared collections — there is nothing to define, since the server derives\n * its API from the database — and overlays the files that differ.\n *\n * The config *package* stays, holding only `storageAuthorize`. Storage is not\n * under row-level security, so a deployment with file storage enabled and no\n * access model serves every user's files to every signed-in user; the server\n * refuses to boot in that state. Deleting the package outright would leave a\n * headless project with nowhere to put the hook, and the scaffold's own\n * docker-compose.yml enables storage — so the first `docker compose up` would\n * crash-loop.\n */\nasync function applyHeadless(targetDirectory: string, headless: boolean): Promise<void> {\n if (!headless) return;\n\n fs.rmSync(path.join(targetDirectory, \"frontend\"), { recursive: true, force: true });\n // Collections only. `rebase build` reads the absence of this directory as\n // \"introspect from the database\", and the overlay replaces config/index.ts\n // with one that exports the storage hook alone.\n fs.rmSync(path.join(targetDirectory, \"config\", \"collections\"), { recursive: true, force: true });\n for (const stray of [\"admin.d.ts\", \"frontend-assets.d.ts\"]) {\n fs.rmSync(path.join(targetDirectory, \"config\", stray), { force: true });\n }\n // Generated from collection files; a headless project reads the live schema.\n fs.rmSync(path.join(targetDirectory, \"backend\", \"src\", \"schema.generated.ts\"), { force: true });\n\n const overlayDir = path.resolve(cliRoot!, \"templates\", \"overlays\", \"baas\");\n if (!fs.existsSync(overlayDir)) {\n console.error(`${chalk.red.bold(\"ERROR\")} BaaS template overlay not found at ${overlayDir}`);\n process.exit(1);\n }\n\n await cp(overlayDir, targetDirectory, {\n recursive: true,\n force: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n}\n\nasync function applyPreset(targetDirectory: string, preset: TemplatePreset): Promise<void> {\n const collectionsDir = path.join(targetDirectory, \"config\", \"collections\");\n const presetsDir = path.join(collectionsDir, \"presets\");\n\n if (preset !== \"blog\") {\n const presetDir = path.join(presetsDir, preset);\n if (!fs.existsSync(presetDir)) {\n console.warn(chalk.yellow(` Warning: Preset \"${preset}\" not found, falling back to blog template.`));\n cleanupPresets(presetsDir);\n return;\n }\n\n // Remove the default blog collection files (keep users.ts — it's shared)\n const blogFiles = [\"posts.ts\", \"authors.ts\", \"tags.ts\", \"index.ts\"];\n for (const file of blogFiles) {\n const filePath = path.join(collectionsDir, file);\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n }\n }\n\n // Copy preset files into the collections directory\n const presetFiles = fs.readdirSync(presetDir).filter(f => f.endsWith(\".ts\"));\n for (const file of presetFiles) {\n fs.copyFileSync(\n path.join(presetDir, file),\n path.join(collectionsDir, file)\n );\n }\n }\n\n // Always clean up the presets directory — it shouldn't ship with the final project\n cleanupPresets(presetsDir);\n}\n\nfunction cleanupPresets(presetsDir: string): void {\n if (fs.existsSync(presetsDir)) {\n fs.rmSync(presetsDir, { recursive: true,\nforce: true });\n }\n}\n\nasync function replacePlaceholders(options: InitOptions) {\n const filesToProcess = TEMPLATE_PLACEHOLDER_FILES;\n\n const packageJsonPath = path.resolve(cliRoot!, \"package.json\");\n let cliVersion = \"latest\";\n if (fs.existsSync(packageJsonPath)) {\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\"));\n cliVersion = pkg.version || \"latest\";\n }\n\n const versionCache = new Map<string, string>();\n /** Packages with no release matching the CLI's own version. */\n const unreleased = new Map<string, string>();\n\n // Use npm view for registry queries — it's universal and works regardless of PM\n const viewBin = \"npm\";\n\n const getPackageVersion = async (pkgName: string) => {\n if (versionCache.has(pkgName)) return versionCache.get(pkgName)!;\n if (process.env.REBASE_E2E === \"true\") {\n versionCache.set(pkgName, cliVersion);\n return cliVersion;\n }\n let versionToUse = cliVersion;\n try {\n // First try to check if the specific cliVersion exists for this package\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${cliVersion}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // If specific version doesn't exist, try the matching tag (canary or latest)\n const tag = cliVersion.includes(\"canary\") ? \"canary\" : \"latest\";\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${tag}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // Fallback to absolute latest\n const { stdout } = await execa(viewBin, [\"view\", pkgName, \"version\"]);\n versionToUse = stdout.trim() || \"latest\";\n } catch {\n versionToUse = \"latest\";\n }\n }\n\n // The fallbacks above answer \"what can I install?\", not \"what matches\n // this CLI?\". When a package has no release at the CLI's own version,\n // they quietly pin whatever the registry last tagged — which can be a\n // prerelease from an entirely different era of the framework. Record\n // it so we can refuse rather than scaffold a mixed-version app.\n if (versionToUse !== cliVersion) {\n unreleased.set(pkgName, versionToUse);\n }\n }\n versionCache.set(pkgName, versionToUse);\n return versionToUse;\n };\n\n // First, find all unique @rebasepro packages across all files to process in parallel\n const allPackages = new Set<string>();\n const fileContents = new Map<string, string>();\n\n for (const file of filesToProcess) {\n const fullPath = path.resolve(options.targetDirectory, file);\n if (!fs.existsSync(fullPath)) continue;\n const content = fs.readFileSync(fullPath, \"utf-8\");\n fileContents.set(fullPath, content);\n\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n allPackages.add(match[1]);\n }\n }\n\n console.log(chalk.gray(\" Resolving package versions...\"));\n\n // Resolve all versions in parallel\n await Promise.all(Array.from(allPackages).map(getPackageVersion));\n\n // A stable CLI whose packages resolve only to a prerelease means those\n // packages were never released at this version — the usual cause is a rename\n // that left the new name published on the canary tag alone. Scaffolding\n // anyway mixes eras (say @rebasepro/types@0.9.0 beside a 0.0.1 canary) and\n // hands the user an app that fails at install or, worse, at runtime. Neither\n // failure names this as the cause, so stop here and say it plainly.\n const cliIsStable = cliVersion !== \"latest\" && !cliVersion.includes(\"-\");\n const prereleasePins = [...unreleased].filter(([, version]) => version === \"latest\" || version.includes(\"-\"));\n\n if (cliIsStable && prereleasePins.length > 0) {\n const lines = prereleasePins.map(([name, version]) => ` ${name} → ${version}`).join(\"\\n\");\n throw new Error(\n `Rebase ${cliVersion} is not fully published to npm.\\n\\n` +\n `These packages have no ${cliVersion} release, so the newest thing on the\\n` +\n `registry is a prerelease:\\n\\n${lines}\\n\\n` +\n `Scaffolding would pin those alongside the ${cliVersion} packages and produce\\n` +\n `an app that cannot install or run. That is a release gap in Rebase itself —\\n` +\n `not a problem with your machine, your network, or your package manager.\\n\\n` +\n `Stopped before writing dependency versions or installing anything. The\\n` +\n `project directory ${path.basename(options.targetDirectory)}/ was created and is safe to delete.\\n` +\n `Please report this with the list above.`\n );\n }\n\n // Perform replacements\n for (const [fullPath, originalContent] of fileContents.entries()) {\n let content = originalContent.replace(/\\{\\{PROJECT_NAME\\}\\}/g, options.projectName);\n\n // Replace workspace:* with the dynamically resolved version\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n const pkgName = match[1];\n const resolvedVersion = versionCache.get(pkgName) || \"latest\";\n content = content.replace(new RegExp(`\"${pkgName}\":\\\\s*\"workspace:\\\\*\"`, \"g\"), `\"${pkgName}\": \"${resolvedVersion}\"`);\n }\n\n fs.writeFileSync(fullPath, content, \"utf-8\");\n }\n}\n\n\nasync function isPortAvailable(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once(\"error\", () => {\n resolve(false);\n });\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n server.listen(port);\n });\n}\n\nasync function findAvailablePort(startPort: number): Promise<number> {\n let port = startPort;\n while (!(await isPortAvailable(port))) {\n port++;\n }\n return port;\n}\n\n/**\n * The CLI's own version, which is the runtime image tag a scaffolded project\n * pins. They move together: the CLI, the packages and the runtime image are cut\n * from one release, so the version that installed the project is the version\n * whose runtime can boot its bundle.\n *\n * Falls back to `latest` only when the CLI cannot read its own manifest — a\n * floating tag is worse than a pinned one, but better than a compose file that\n * names a version that was never published.\n */\nfunction readCliVersion(): string {\n try {\n const manifest = path.resolve(cliRoot!, \"package.json\");\n if (fs.existsSync(manifest)) {\n const pkg = JSON.parse(fs.readFileSync(manifest, \"utf-8\"));\n if (typeof pkg.version === \"string\" && pkg.version) return pkg.version;\n }\n } catch {\n // Fall through — see the doc comment.\n }\n return \"latest\";\n}\n\nexport async function configureEnvFile(targetDirectory: string, databaseUrl?: string) {\n const envExamplePath = path.join(targetDirectory, \".env.example\");\n const envPath = path.join(targetDirectory, \".env\");\n if (fs.existsSync(envExamplePath) && !fs.existsSync(envPath)) {\n // Copy .env.example → .env (keep .env.example as a reference in the repo)\n fs.copyFileSync(envExamplePath, envPath);\n\n // Generate secure random strings\n const jwtSecret = crypto.randomBytes(32).toString(\"hex\");\n const dbPassword = crypto.randomBytes(16).toString(\"hex\");\n const serviceKey = crypto.randomBytes(48).toString(\"base64\");\n\n let envContent = fs.readFileSync(envPath, \"utf-8\");\n\n envContent = envContent.replace(\n /^JWT_SECRET=.*$/m,\n `JWT_SECRET=${jwtSecret}`\n );\n\n // Ships commented out in .env.example. Left unset, the server generates\n // one on every boot and silently invalidates the previous run's tokens,\n // so write a stable one now rather than making each restart a logout.\n envContent = envContent.replace(\n /^#\\s*REBASE_SERVICE_KEY=.*$/m,\n `REBASE_SERVICE_KEY=${serviceKey}`\n );\n\n // Pin the runtime image `docker-compose.yml` pulls.\n //\n // The compose file reads `rebasepro/server:${REBASE_VERSION:-latest}`,\n // and unset it resolves to `latest` — a tag that moves under a running\n // deployment. That is precisely the hazard `cloudbuild-runtime.yaml`\n // designed away for the managed fleet, which pins releases by digest\n // because \"re-pushing a tag silently changes what the fleet is running\n // with no version anywhere changing\". A self-hoster deserves the same\n // guarantee, and it costs one line here.\n //\n // It also makes the compose header's upgrade instruction true: \"To\n // upgrade Rebase, change REBASE_VERSION and restart\" is a no-op while\n // the value is unset and the tag floats.\n const runtimeVersion = readCliVersion();\n envContent = /^#?\\s*REBASE_VERSION=.*$/m.test(envContent)\n ? envContent.replace(/^#?\\s*REBASE_VERSION=.*$/m, `REBASE_VERSION=${runtimeVersion}`)\n : `${envContent.trimEnd()}\\n\\n# The Rebase runtime image tag docker-compose.yml pulls.\\n# Change this and restart to upgrade; your project bundle is untouched.\\nREBASE_VERSION=${runtimeVersion}\\n`;\n\n if (databaseUrl) {\n if (/[\\r\\n]/.test(databaseUrl)) {\n throw new Error(\"Invalid DATABASE_URL: multiline values are not allowed.\");\n }\n // DATABASE_PASSWORD is still written even though the URL points\n // elsewhere: docker-compose.yml interpolates it into both\n // POSTGRES_PASSWORD and the backend's own DATABASE_URL, defaulting\n // to `${DATABASE_PASSWORD:-changeme}`. Omitting it here shipped a\n // compose stack whose database password was literally \"changeme\",\n // on a service that publishes a host port by default.\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n `DATABASE_URL=${databaseUrl}\\nDATABASE_PASSWORD=${dbPassword}`\n );\n } else {\n const dbPort = await findAvailablePort(5432);\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n // sslmode=disable: the paired docker-compose Postgres has no TLS,\n // and Go-based tooling (atlas, via `rebase db push`) defaults to\n // requiring SSL when the URL doesn't say otherwise.\n `DATABASE_URL=postgresql://rebase:${dbPassword}@localhost:${dbPort}/rebase?options=-c%20search_path=public&sslmode=disable\\nDATABASE_PASSWORD=${dbPassword}`\n );\n\n // Also update docker-compose.yml with the dynamic host port if it has the default 5432 port mapping\n const dockerComposePath = path.join(targetDirectory, \"docker-compose.yml\");\n if (fs.existsSync(dockerComposePath)) {\n let dockerComposeContent = fs.readFileSync(dockerComposePath, \"utf-8\");\n dockerComposeContent = dockerComposeContent.replace(\n /-\\s*\"5432:5432\"/g,\n `- \"${dbPort}:5432\"`\n );\n fs.writeFileSync(dockerComposePath, dockerComposeContent, \"utf-8\");\n }\n }\n\n fs.writeFileSync(envPath, envContent, \"utf-8\");\n }\n}\n","/**\n * CLI command: generate-sdk\n *\n * Reads collection definitions from a specified directory (default: ./config/collections),\n * generates a typed TypeScript SDK, and writes it to the output directory (default: ./generated/sdk).\n *\n * Uses jiti for dynamic TypeScript import of collection files.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig, computeSchemaVersion, deserializeCollections } from \"@rebasepro/types\";\nimport { generateSDK, GeneratedFile } from \"@rebasepro/codegen\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { findProjectRoot } from \"../utils/project\";\nimport { readLink } from \"./cloud/context\";\n\ninterface GenerateSDKArgs {\n collectionsDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no collections — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n help?: boolean;\n}\n\n/**\n * Dynamically load collection definitions from a directory.\n *\n * Expects the directory to have an index.ts/index.js that exports a default\n * array of CollectionConfig objects (matching the app/config/collections pattern).\n */\nasync function loadCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n const absDir = path.resolve(collectionsDir);\n\n if (!fs.existsSync(absDir)) {\n throw new Error(`Collections directory not found: ${absDir}`);\n }\n\n // Try to import the index file using jiti (supports TypeScript natively)\n let jiti: (id: string, userOptions?: Record<string, unknown>) => (modulePath: string) => Record<string, unknown>;\n try {\n const jitiModule = await import(\"jiti\");\n jiti = (jitiModule.default || jitiModule) as typeof jiti;\n } catch {\n const installCmd = [...getPMCommands(detectPackageManager()).install, \"-D\", \"jiti\"].join(\" \");\n throw new Error(\n `Could not load 'jiti'. Install it with: ${installCmd}\\n` +\n \"jiti is required to dynamically import TypeScript collection definitions.\"\n );\n }\n\n const jitiInstance = jiti(absDir, {\n interopDefault: true,\n esmResolve: true\n });\n\n // Look for index file\n const indexCandidates = [\"index.ts\", \"index.js\", \"index.mjs\"];\n let indexPath: string | null = null;\n\n for (const candidate of indexCandidates) {\n const p = path.join(absDir, candidate);\n if (fs.existsSync(p)) {\n indexPath = p;\n break;\n }\n }\n\n if (!indexPath) {\n // Fallback: load each .ts/.js file individually\n console.log(chalk.yellow(\" No index file found, scanning individual collection files...\"));\n const collections: CollectionConfig[] = [];\n const files = fs.readdirSync(absDir).filter(f =>\n (f.endsWith(\".ts\") || f.endsWith(\".js\")) && !f.startsWith(\".\")\n );\n\n for (const file of files) {\n try {\n const mod = jitiInstance(path.join(absDir, file));\n const exported = mod.default || mod;\n if (exported && typeof exported === \"object\" && \"slug\" in exported) {\n collections.push(exported as CollectionConfig);\n } else if (Array.isArray(exported)) {\n collections.push(...exported);\n }\n } catch (err) {\n console.warn(chalk.yellow(` ⚠ Skipping ${file}: ${(err as Error).message}`));\n }\n }\n\n return collections;\n }\n\n // Import the index\n const mod = jitiInstance(indexPath);\n const exported = mod.default || mod;\n\n if (Array.isArray(exported)) {\n return exported as CollectionConfig[];\n } else if (typeof exported === \"object\" && exported !== null) {\n // Could be a named export like { collections: [...] }\n if (\"collections\" in exported && Array.isArray(exported.collections)) {\n return exported.collections;\n }\n // Or individual named exports\n const collections: CollectionConfig[] = [];\n for (const value of Object.values(exported)) {\n if (value && typeof value === \"object\" && \"slug\" in (value as CollectionConfig)) {\n collections.push(value as CollectionConfig);\n }\n }\n if (collections.length > 0) return collections;\n }\n\n throw new Error(\n `Could not extract collections from ${indexPath}.\\n` +\n \"Expected a default export of CollectionConfig[] or an object with named collection exports.\"\n );\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n -c, --collections-dir <dir> Local collections directory (default: ./config/collections)\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From local collections\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n`.trim());\n}\n\n/**\n * Fetch collections from a running project's contract endpoint.\n *\n * The payload replaces relation `target` functions with slug references, so it\n * has to be rehydrated before the generator sees it — the generator *calls*\n * `target()` to decide whether a foreign key is a string or a number, and a\n * missing target silently degrades that to a union rather than failing.\n */\nasync function fetchRemoteCollections(\n baseUrl: string,\n token: string | undefined\n): Promise<{ collections: CollectionConfig[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n console.log(chalk.gray(\" Pass --token, or set REBASE_SERVICE_KEY.\"));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract = await response.json() as {\n collections?: unknown[];\n schemaVersion?: string;\n };\n\n if (!Array.isArray(contract.collections)) {\n console.log(chalk.red(\" ✗ The contract response did not contain collections.\"));\n process.exit(1);\n }\n\n return {\n collections: deserializeCollections(contract.collections),\n schemaVersion: contract.schemaVersion ?? \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port this project last ran on; fall back to the literal only when the project\n * has never been started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { collectionsDir, output, cwd } = args;\n\n if (args.help) {\n printSdkHelp();\n return;\n }\n\n const resolvedCollectionsDir = path.isAbsolute(collectionsDir)\n ? collectionsDir\n : path.join(cwd, collectionsDir);\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n\n let collections: CollectionConfig[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteCollections(baseUrl, args.token || ambient);\n collections = remote.collections;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n console.log(` ${chalk.gray(\"Collections:\")} ${resolvedCollectionsDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading collection definitions...\"));\n collections = await loadCollections(resolvedCollectionsDir);\n }\n\n // Sort collections alphabetically by slug to ensure deterministic SDK generation\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n\n if (collections.length === 0) {\n console.log(chalk.red(\" ✗ No collections found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map(c => c.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n const files = generateSDK(collections);\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(collections);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\nexport const GENERATED_AT = ${JSON.stringify(new Date().toISOString())};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const exampleSlug = collections[0]?.slug || \"my_collection\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { collectionsDictionary, type Database } from '${typesImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" collections: collectionsDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.…` is the typed surface. `rebase.collection(slug)` exists\n // too, but it is generic over `Record<string, unknown>` and has no link to\n // `Database` — printing it here would advertise the one call shape that\n // throws away the types this command just generated.\n console.log(chalk.gray(` const { data } = await rebase.data.collection('${exampleSlug}').find();`));\n if (isIdentifierLike(exampleSlug)) {\n console.log(chalk.gray(` // …or in property style: rebase.data.${exampleSlug}.find()`));\n }\n console.log(\"\");\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printSchemaHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n process.exit(1);\n }\n}\n\nfunction printSchemaHelp() {\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} Path to collections directory\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n`);\n}\n","/**\n * CLI command: rebase db <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printDbHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n\nfunction printDbHelp() {\n console.log(`\n${chalk.bold(\"rebase db\")} — Database management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase db ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"push\")} Apply schema directly to database (development)\n ${chalk.blue.bold(\"generate\")} Generate migration files\n ${chalk.blue.bold(\"migrate\")} Run pending migrations\n ${chalk.blue.bold(\"branch\")} Database branching (create, list, delete, info)\n ${chalk.blue.bold(\"backup\")} Create a backup with pg_dump (--out <path|s3://…>)\n ${chalk.blue.bold(\"restore\")} Restore a backup with pg_restore (destructive; needs --yes)\n ${chalk.blue.bold(\"backups\")} List stored backups (backups list)\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.gray(\"# Quick development workflow\")}\n rebase schema generate && rebase db push\n\n ${chalk.gray(\"# Production migration workflow\")}\n rebase db generate\n rebase db migrate\n\n ${chalk.gray(\"# Create a database branch\")}\n rebase db branch create feature_auth\n\n ${chalk.gray(\"# Back up to a local directory, then to object storage\")}\n rebase db backup --out ./backups\n rebase db backup --out s3://my-private-bucket/backups\n\n ${chalk.gray(\"# Restore into a fresh database (safe: does not touch the live one)\")}\n rebase db restore ./backups/rebase-app-20260714T030000Z.dump --create-db --target-db app_restored\n`);\n}\n","/**\n * Loading, validating and synthesizing `rebase.json`.\n *\n * The manifest declares *topology*: which runtime major a project targets and\n * which apps this repository contributes. It is deliberately small — schema,\n * security rules, hooks and functions stay in TypeScript, where a type system\n * can check them.\n *\n * Two properties matter more than the file format itself:\n *\n * - **A missing manifest is never an error.** Every project that exists today\n * predates this file. One is synthesized from the conventions the template\n * already follows, so nothing breaks and nobody is forced to migrate.\n * - **Validation reports every problem at once**, with the path to each. A\n * config file that surfaces its mistakes one run at a time is a bad config\n * file.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n findStorageSuffixCollision,\n storageEnvSuffix,\n type DeclaredStorageSources,\n type ManagedCompatibility,\n type RebaseAppConfig,\n type RebaseBackendAppConfig,\n type RebaseProjectManifest\n} from \"@rebasepro/types\";\nimport { MANIFEST_FILENAME } from \"./utils/project\";\n\n/** Runtime range written into new manifests. */\nexport const CURRENT_RUNTIME_RANGE = \"^1\";\n\n/** Conventional locations, matching what `rebase init` scaffolds. */\nexport const DEFAULT_CONFIG_DIR = \"config\";\nexport const DEFAULT_FUNCTIONS_DIR = \"backend/functions\";\nexport const DEFAULT_CRONS_DIR = \"backend/crons\";\nexport const DEFAULT_SCHEMA_FILE = \"backend/src/schema.generated.ts\";\n\nexport interface ManifestValidationIssue {\n /** Dotted path to the offending value, e.g. `apps.web.output`. */\n path: string;\n message: string;\n}\n\nexport interface LoadedManifest {\n manifest: RebaseProjectManifest;\n /** Where it came from — a real file, or inferred from the directory layout. */\n source: \"file\" | \"synthesized\";\n /** Absolute path to `rebase.json`, when one exists. */\n filePath?: string;\n}\n\nexport class ManifestError extends Error {\n constructor(message: string, readonly issues: ManifestValidationIssue[] = []) {\n super(message);\n this.name = \"ManifestError\";\n }\n}\n\nconst APP_TYPES = [\"backend\", \"static\"] as const;\n\n/**\n * App types that used to exist, and what replaced each one.\n *\n * Kept so a manifest written against the old vocabulary fails with the fix in\n * hand rather than with `must be one of: backend, static`, which tells a reader\n * what is wrong but not what to write instead.\n */\nconst REMOVED_APP_TYPES: Record<string, string> = {\n admin:\n 'the admin panel is an ordinary static app now — declare it as ' +\n '{ \"type\": \"static\", \"root\": \"frontend\", \"output\": \"frontend/dist\", \"path\": \"/admin\" }',\n custom:\n 'who owns the server is a property of the backend now — declare ' +\n '{ \"type\": \"backend\", \"runtime\": \"custom\" } instead of a separate app',\n mobile:\n \"mobile apps are no longer declared in the manifest — nothing consumed this type. \" +\n \"Remove the entry\"\n};\n\n/** Reserved because they name things in URLs and CLI output. */\nconst RESERVED_APP_NAMES = new Set([\"api\", \"health\", \"metrics\", \"livez\", \"_rebase\"]);\n\n/**\n * Validate a static app's public base path.\n *\n * Normalizes to \"no trailing slash, except for the root\" so that mounting and\n * the `REBASE_APP_BASE` build variable have one shape to reason about.\n */\nfunction checkAppPath(\n value: unknown,\n fieldPath: string,\n issues: ManifestValidationIssue[]\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\" || !value.startsWith(\"/\") || value.includes(\"..\")) {\n issues.push({\n path: fieldPath,\n message: 'must be an absolute path like \"/admin\"'\n });\n return undefined;\n }\n if (value !== \"/\" && value.endsWith(\"/\")) {\n issues.push({\n path: fieldPath,\n message: 'must not end with a slash — write \"/admin\", not \"/admin/\"'\n });\n return undefined;\n }\n return value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reject paths that escape the repository.\n *\n * A manifest is committed and reviewed, so this is not a security boundary so\n * much as a guard against `../../` typos that would otherwise have `rebase build`\n * writing outside the project.\n */\nfunction checkRelativePath(\n value: unknown,\n fieldPath: string,\n issues: ManifestValidationIssue[],\n { required }: { required: boolean }\n): string | undefined {\n if (value === undefined) {\n if (required) issues.push({ path: fieldPath,\nmessage: \"is required\" });\n return undefined;\n }\n if (typeof value !== \"string\" || value.trim() === \"\") {\n issues.push({ path: fieldPath,\nmessage: \"must be a non-empty string\" });\n return undefined;\n }\n if (path.isAbsolute(value)) {\n issues.push({ path: fieldPath,\nmessage: \"must be a relative path, not absolute\" });\n return undefined;\n }\n const normalized = path.normalize(value);\n if (normalized === \"..\" || normalized.startsWith(`..${path.sep}`)) {\n issues.push({ path: fieldPath,\nmessage: \"must stay inside the project directory\" });\n return undefined;\n }\n return value;\n}\n\n/** Fields each app type understands. Anything else is a typo or a newer CLI. */\nconst KNOWN_APP_FIELDS: Record<string, readonly string[]> = {\n backend: [\"type\", \"runtime\", \"config\", \"functions\", \"crons\", \"schema\",\n \"usersCollection\", \"dockerfile\", \"context\", \"port\"],\n static: [\"type\", \"root\", \"build\", \"output\", \"path\", \"spa\"]\n};\n\n/**\n * Report a field this CLI does not recognise.\n *\n * A warning rather than an error, and the distinction matters in both\n * directions. `\"pathh\": \"/admin\"` is a typo that would otherwise be silently\n * dropped — the app builds for `/`, mounts at `/`, and the only symptom is that\n * it is not where you put it. But an unknown field is also what an *older* CLI\n * sees when it opens a manifest written for a newer one, and refusing to build\n * over a field that is simply from the future would make every manifest addition\n * a breaking change.\n *\n * So: name it, suggest the near-miss, and carry on.\n */\nfunction warnUnknownFields(name: string, raw: Record<string, unknown>, type: string): void {\n const known = KNOWN_APP_FIELDS[type];\n if (!known) return;\n\n for (const field of Object.keys(raw)) {\n if (known.includes(field)) continue;\n const suggestion = known.find(candidate => isNearMiss(candidate, field));\n console.warn(\n `⚠ rebase.json: apps.${name}.${field} is not a field this CLI knows.` +\n (suggestion ? ` Did you mean \"${suggestion}\"?` : \" It is ignored — your CLI may be older than this manifest.\")\n );\n }\n}\n\n/** One edit apart, ignoring case: enough for a typo, tight enough to stay quiet. */\nfunction isNearMiss(a: string, b: string): boolean {\n const x = a.toLowerCase();\n const y = b.toLowerCase();\n if (x === y) return true;\n if (Math.abs(x.length - y.length) > 1) return false;\n\n const [shorter, longer] = x.length <= y.length ? [x, y] : [y, x];\n let i = 0;\n let j = 0;\n let edits = 0;\n while (i < shorter.length && j < longer.length) {\n if (shorter[i] === longer[j]) { i++; j++; continue; }\n if (++edits > 1) return false;\n if (shorter.length === longer.length) i++;\n j++;\n }\n return edits + (longer.length - j) + (shorter.length - i) <= 1;\n}\n\nfunction validateApp(\n name: string,\n raw: unknown,\n issues: ManifestValidationIssue[]\n): RebaseAppConfig | undefined {\n const base = `apps.${name}`;\n\n if (!isRecord(raw)) {\n issues.push({ path: base,\nmessage: \"must be an object\" });\n return undefined;\n }\n\n const type = raw.type;\n if (typeof type === \"string\" && REMOVED_APP_TYPES[type]) {\n issues.push({ path: `${base}.type`,\nmessage: `\"${type}\" is no longer an app type — ${REMOVED_APP_TYPES[type]}` });\n return undefined;\n }\n if (typeof type !== \"string\" || !(APP_TYPES as readonly string[]).includes(type)) {\n issues.push({\n path: `${base}.type`,\n message: `must be one of: ${APP_TYPES.join(\", \")}`\n });\n return undefined;\n }\n\n warnUnknownFields(name, raw, type);\n\n switch (type) {\n case \"backend\": {\n checkRelativePath(raw.config, `${base}.config`, issues, { required: false });\n checkRelativePath(raw.functions, `${base}.functions`, issues, { required: false });\n checkRelativePath(raw.crons, `${base}.crons`, issues, { required: false });\n checkRelativePath(raw.schema, `${base}.schema`, issues, { required: false });\n checkRelativePath(raw.usersCollection, `${base}.usersCollection`, issues, { required: false });\n\n if (raw.mode !== undefined) {\n issues.push({\n path: `${base}.mode`,\n message:\n \"is no longer a field — collections come from the config directory when \" +\n \"it exists, and are introspected from the database when it does not\"\n });\n }\n\n const custom = raw.runtime === \"custom\";\n if (raw.runtime !== \"managed\" && !custom) {\n issues.push({\n path: `${base}.runtime`,\n message: 'is required, and must be \"managed\" or \"custom\"'\n });\n }\n\n // The image fields describe an image this repository builds. Under a\n // managed backend there is no such image, so accepting them silently\n // would be accepting a Dockerfile that never gets built.\n for (const field of [\"dockerfile\", \"context\", \"port\"] as const) {\n if (raw[field] !== undefined && !custom) {\n issues.push({\n path: `${base}.${field}`,\n message: 'only applies to a custom runtime — set \"runtime\": \"custom\" to build your own image'\n });\n }\n }\n checkRelativePath(raw.dockerfile, `${base}.dockerfile`, issues, { required: false });\n checkRelativePath(raw.context, `${base}.context`, issues, { required: false });\n if (raw.port !== undefined && (typeof raw.port !== \"number\" || !Number.isInteger(raw.port))) {\n issues.push({ path: `${base}.port`,\nmessage: \"must be an integer\" });\n }\n return raw as unknown as RebaseAppConfig;\n }\n case \"static\": {\n checkRelativePath(raw.root, `${base}.root`, issues, { required: true });\n checkRelativePath(raw.output, `${base}.output`, issues, { required: true });\n if (raw.build !== undefined && typeof raw.build !== \"string\") {\n issues.push({ path: `${base}.build`,\nmessage: \"must be a string command\" });\n }\n if (raw.spa !== undefined && typeof raw.spa !== \"boolean\") {\n issues.push({ path: `${base}.spa`,\nmessage: \"must be a boolean\" });\n }\n checkAppPath(raw.path, `${base}.path`, issues);\n return raw as unknown as RebaseAppConfig;\n }\n default:\n return undefined;\n }\n}\n\n/**\n * Validate a parsed manifest, collecting every problem.\n */\nexport function validateManifest(raw: unknown): {\n manifest?: RebaseProjectManifest;\n issues: ManifestValidationIssue[];\n} {\n const issues: ManifestValidationIssue[] = [];\n\n if (!isRecord(raw)) {\n return { issues: [{ path: \"\",\nmessage: `${MANIFEST_FILENAME} must contain a JSON object` }] };\n }\n\n if (typeof raw.rebase !== \"string\" || raw.rebase.trim() === \"\") {\n // `runtime` used to be this key. It now means who owns the backend\n // process, so a manifest still using it at the top level is naming the\n // wrong thing rather than merely missing a field.\n const message = typeof raw.runtime === \"string\"\n ? `is required, e.g. \"${CURRENT_RUNTIME_RANGE}\" — this is the top-level \"runtime\" key renamed, ` +\n 'because \"runtime\" now means \"managed\" or \"custom\" on the backend app'\n : `is required, e.g. \"${CURRENT_RUNTIME_RANGE}\"`;\n issues.push({ path: \"rebase\",\nmessage });\n }\n\n if (!isRecord(raw.apps)) {\n issues.push({ path: \"apps\",\nmessage: \"is required and must be an object\" });\n return { issues };\n }\n\n const apps: Record<string, RebaseAppConfig> = {};\n let backendCount = 0;\n\n for (const [name, value] of Object.entries(raw.apps)) {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {\n issues.push({\n path: `apps.${name}`,\n message: \"name must be lowercase alphanumeric with dashes (it appears in URLs)\"\n });\n continue;\n }\n if (RESERVED_APP_NAMES.has(name)) {\n issues.push({ path: `apps.${name}`,\nmessage: \"name is reserved\" });\n continue;\n }\n\n const app = validateApp(name, value, issues);\n if (!app) continue;\n if (app.type === \"backend\") backendCount++;\n apps[name] = app;\n }\n\n // One backend per *project*. A repository declaring two would have two sets\n // of collections claiming the same database and the same API surface.\n if (backendCount > 1) {\n issues.push({\n path: \"apps\",\n message: \"a project may declare at most one backend app\"\n });\n }\n\n // Two apps at one path is not a preference conflict — the first one mounted\n // swallows the other's URLs, and the loser looks like it deployed fine.\n const byPath = new Map<string, string>();\n for (const [name, app] of Object.entries(apps)) {\n if (app.type !== \"static\") continue;\n const at = app.path ?? \"/\";\n const owner = byPath.get(at);\n if (owner) {\n issues.push({\n path: `apps.${name}.path`,\n message: `two apps cannot serve the same path — \"${owner}\" is already at \"${at}\"`\n });\n continue;\n }\n byPath.set(at, name);\n }\n\n const storage = validateStorageSources(raw.storage, issues);\n\n if (issues.length > 0) return { issues };\n\n return {\n manifest: {\n $schema: typeof raw.$schema === \"string\" ? raw.$schema : undefined,\n rebase: raw.rebase as string,\n apps,\n ...(storage ? { storage } : {})\n },\n issues\n };\n}\n\n/**\n * Validate the `storage` block — which buckets this project uses.\n *\n * Absent means one default source, so `undefined` is a valid answer and not an\n * issue. Everything else is checked strictly, because each key here becomes the\n * suffix of a set of environment variables: a key that cannot become a variable\n * name, or two keys that become the *same* one, are failures worth catching\n * while someone is looking at the file rather than at a tenant serving one\n * bucket's files with another's credentials.\n */\nfunction validateStorageSources(\n raw: unknown,\n issues: ManifestValidationIssue[]\n): DeclaredStorageSources | undefined {\n if (raw === undefined) return undefined;\n if (!isRecord(raw)) {\n issues.push({ path: \"storage\", message: \"must be an object keyed by storage source name\" });\n return undefined;\n }\n\n const sources: DeclaredStorageSources = {};\n for (const [key, value] of Object.entries(raw)) {\n if (!isRecord(value)) {\n issues.push({ path: `storage.${key}`, message: \"must be an object\" });\n continue;\n }\n if (typeof value.engine !== \"string\" || value.engine.trim() === \"\") {\n issues.push({\n path: `storage.${key}.engine`,\n message: 'is required, e.g. \"s3\", \"gcs\" or \"local\"'\n });\n continue;\n }\n if (value.transport !== undefined && value.transport !== \"server\" && value.transport !== \"direct\") {\n issues.push({\n path: `storage.${key}.transport`,\n message: 'must be \"server\" or \"direct\"'\n });\n continue;\n }\n if (value.label !== undefined && typeof value.label !== \"string\") {\n issues.push({ path: `storage.${key}.label`, message: \"must be a string\" });\n continue;\n }\n try {\n storageEnvSuffix(key);\n } catch {\n issues.push({\n path: `storage.${key}`,\n message: \"name cannot become an environment variable suffix — \" +\n \"use a name containing at least one letter or digit\"\n });\n continue;\n }\n sources[key] = {\n engine: value.engine,\n ...(value.transport !== undefined ? { transport: value.transport } : {}),\n ...(value.label !== undefined ? { label: value.label as string } : {})\n };\n }\n\n const collision = findStorageSuffixCollision(Object.keys(sources));\n if (collision) {\n issues.push({\n path: `storage.${collision.b}`,\n message: `maps to the same environment variable suffix ` +\n `(\"${collision.suffix || \"(none)\"}\") as \"${collision.a}\", so the two would read ` +\n \"each other's configuration — rename one of them\"\n });\n }\n\n return Object.keys(sources).length > 0 ? sources : undefined;\n}\n\n/**\n * Infer a manifest from a directory that does not have one.\n *\n * This mirrors exactly what the template scaffolds, which is what makes adopting\n * the manifest a no-op for existing projects: the synthesized result is what\n * they would have written by hand.\n *\n * The backend's `runtime` is inferred from whether the repository declares a\n * **Dockerfile** — the thing that actually builds an image — and from nothing\n * else. It used to be inferred from the presence of `backend/src/index.ts`,\n * which every scaffolded project had whether or not it wanted its own server, so\n * projects predating the manifest silently landed on the custom runtime and paid\n * for it (see `docs/cloud-deploy-workspace-vendoring.md`).\n */\nexport function synthesizeManifest(projectRoot: string): RebaseProjectManifest {\n const exists = (relative: string): boolean => fs.existsSync(path.join(projectRoot, relative));\n const apps: Record<string, RebaseAppConfig> = {};\n\n const hasConfig = exists(DEFAULT_CONFIG_DIR);\n const hasBackend = exists(\"backend\");\n const dockerfile = [\"Dockerfile\", \"backend/Dockerfile\"].find(exists);\n\n if (hasBackend || hasConfig) {\n const backend: RebaseBackendAppConfig = dockerfile\n ? { type: \"backend\",\nruntime: \"custom\",\ndockerfile,\ncontext: \".\" }\n : { type: \"backend\",\nruntime: \"managed\" };\n if (exists(DEFAULT_FUNCTIONS_DIR)) backend.functions = DEFAULT_FUNCTIONS_DIR;\n if (exists(DEFAULT_CRONS_DIR)) backend.crons = DEFAULT_CRONS_DIR;\n apps.backend = backend;\n\n // Say it out loud. The file looks exactly like the server and is never\n // loaded, which used to be discovered only after a deploy answered 404\n // on every route defined in it.\n if (!dockerfile && exists(\"backend/src/index.ts\")) {\n console.warn(\n \"⚠ backend/src/index.ts exists but this project's backend is managed — it is\\n\" +\n \" never loaded. Delete it, or run `rebase eject` to make it the entrypoint.\"\n );\n }\n }\n\n if (exists(\"frontend\")) {\n apps.web = {\n type: \"static\",\n root: \"frontend\",\n build: \"npm run build --workspace frontend\",\n output: \"frontend/dist\",\n path: \"/\",\n spa: true\n };\n }\n\n return { rebase: CURRENT_RUNTIME_RANGE,\napps };\n}\n\nexport function manifestPath(projectRoot: string): string {\n return path.join(projectRoot, MANIFEST_FILENAME);\n}\n\nexport function manifestExists(projectRoot: string): boolean {\n return fs.existsSync(manifestPath(projectRoot));\n}\n\n/**\n * Read the manifest, falling back to a synthesized one.\n *\n * A malformed manifest throws — unlike a missing one. Silently ignoring a file\n * the developer wrote, and building something else instead, is the worst\n * available behaviour.\n */\nexport function loadManifest(projectRoot: string): LoadedManifest {\n const filePath = manifestPath(projectRoot);\n\n if (!fs.existsSync(filePath)) {\n return { manifest: synthesizeManifest(projectRoot),\nsource: \"synthesized\" };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, \"utf8\"));\n } catch (err) {\n throw new ManifestError(\n `${MANIFEST_FILENAME} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n const { manifest, issues } = validateManifest(parsed);\n if (!manifest) {\n throw new ManifestError(`${MANIFEST_FILENAME} is invalid`, issues);\n }\n\n return { manifest,\nsource: \"file\",\nfilePath };\n}\n\n/** Write a manifest, with a trailing newline so it plays well with other tools. */\nexport function writeManifest(projectRoot: string, manifest: RebaseProjectManifest): string {\n const filePath = manifestPath(projectRoot);\n const ordered = {\n $schema: manifest.$schema ?? \"https://rebase.pro/schemas/rebase.json\",\n rebase: manifest.rebase,\n apps: manifest.apps\n };\n fs.writeFileSync(filePath, `${JSON.stringify(ordered, null, 4)}\\n`, \"utf8\");\n return filePath;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Queries\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Find the single backend app, if this repository declares one. */\nexport function findBackendApp(\n manifest: RebaseProjectManifest\n): { name: string; app: RebaseBackendAppConfig } | undefined {\n for (const [name, app] of Object.entries(manifest.apps)) {\n if (app.type === \"backend\") return { name,\napp: app as RebaseBackendAppConfig };\n }\n return undefined;\n}\n\n/** Apps that produce build output, in the order they should be built. */\nexport function buildableApps(\n manifest: RebaseProjectManifest\n): { name: string; app: RebaseAppConfig }[] {\n // Backend first: a static app's build may consume an SDK generated from the\n // backend's collections, so building it second is the order that works.\n const entries = Object.entries(manifest.apps).map(([name, app]) => ({ name,\napp }));\n const rank = (app: RebaseAppConfig): number => (app.type === \"backend\" ? 0 : 1);\n return entries.sort((a, b) => rank(a.app) - rank(b.app));\n}\n\n/**\n * Decide whether a project can run on the managed runtime, and say why not.\n *\n * \"Not eligible\" is never a dead end — it selects the custom-runtime path, which\n * still deploys. The reasons exist so the answer is actionable rather than a\n * verdict.\n */\nexport function assessManagedCompatibility(\n manifest: RebaseProjectManifest\n): ManagedCompatibility {\n const backend = findBackendApp(manifest);\n\n if (!backend) {\n return {\n eligible: false,\n reasons: [\n \"No backend app is declared in this repository. Only the repository that \" +\n \"declares the backend selects the runtime.\"\n ]\n };\n }\n\n // Declared, not deduced. A project on the custom runtime is there because\n // somebody wrote it down, which is the whole point of the field.\n if (backend.app.runtime === \"custom\") {\n return {\n eligible: false,\n reasons: [\n `App \"${backend.name}\" declares runtime: \"custom\", so it builds and runs its ` +\n \"own image. The managed runtime boots the platform image with your bundle; \" +\n \"the custom runtime deploys exactly the same way, from your Dockerfile.\"\n ]\n };\n }\n\n return { eligible: true,\nreasons: [] };\n}\n\n/**\n * Resolve a backend app's directories against the conventions it omits.\n *\n * `hasCollections` replaces the old `mode: \"cms\" | \"baas\"` field. Where the\n * collections come from was never an independent choice: either they are\n * declared in code and the bundle ships them, or they are not and the runtime\n * introspects the live database at boot. Declaring it separately only created\n * the contradictory state — code-first declared, no collections anywhere.\n *\n * `hasConfig` is deliberately a **separate** question. A headless project has no\n * `config/collections`, but it may still ship a config package — that is where\n * the `storageAuthorize` hook lives, and storage is not under row-level\n * security, so without one the server refuses to boot with storage enabled.\n * Collapsing the two would leave a headless project nowhere to put it.\n */\nexport function resolveBackendPaths(\n app: RebaseBackendAppConfig,\n projectRoot: string\n): {\n config: string;\n functions: string;\n crons: string;\n schema: string;\n usersCollection: string;\n /** Whether a config package exists — hooks, storage authorization. */\n hasConfig: boolean;\n /** Whether collections are declared in code, under `<config>/collections`. */\n hasCollections: boolean;\n} {\n const config = app.config ?? DEFAULT_CONFIG_DIR;\n return {\n config,\n functions: app.functions ?? DEFAULT_FUNCTIONS_DIR,\n crons: app.crons ?? DEFAULT_CRONS_DIR,\n schema: app.schema ?? DEFAULT_SCHEMA_FILE,\n usersCollection: app.usersCollection ?? \"collections/users\",\n hasConfig: fs.existsSync(path.join(projectRoot, config)),\n hasCollections: fs.existsSync(path.join(projectRoot, config, \"collections\"))\n };\n}\n","/**\n * CLI command: rebase dev\n *\n * Starts the full development environment:\n * - Backend: tsx watch with auto-reload\n * - Frontend: vite dev server\n *\n * Both processes stream output with color-coded prefixes.\n *\n * When the backend uses port-retry (i.e. the configured port is busy and it\n * binds to the next free one), the CLI detects the actual port from stdout\n * and injects VITE_API_URL into the frontend so it connects automatically.\n *\n * Each project gets a deterministic default port derived from the project\n * root path, so multiple Rebase instances never collide.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa, execaCommandSync, type ResultPromise } from \"execa\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { fileURLToPath } from \"url\";\nimport { findBackendApp, loadManifest, resolveBackendPaths } from \"../manifest\";\nimport {\n requireProjectRoot,\n findBackendDir,\n findFrontendDir,\n findEnvFile,\n resolveTsx,\n validateTsxInstallation,\n getActiveBackendPlugin,\n resolvePluginCliScript\n} from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\n/**\n * Quote a path for the shell `execa` runs the backend through.\n *\n * The dev runtime's path is absolute and therefore contains whatever the\n * developer's directories are called. Double quotes do not neutralize `$`,\n * backticks or backslashes in a POSIX shell, so a checkout under a directory\n * named `$(...)` would execute it. Single quotes disable all expansion; on\n * Windows, `cmd.exe` performs no such expansion and wants double quotes.\n */\nfunction quoteForShell(value: string): string {\n if (process.platform === \"win32\") return `\"${value.replace(/\"/g, \"\\\\\\\"\")}\"`;\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Locate the dev runtime shim shipped with the CLI.\n *\n * Published under `runtime/` in the package rather than compiled into `dist/`,\n * because tsx executes it as a file and it must exist on disk at a stable path.\n */\nfunction resolveDevRuntimeEntry(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n // Walk up from wherever this module ended up (src/ in development, dist/ in\n // a published install) until the package root with `runtime/` is found.\n let dir = here;\n for (let i = 0; i < 5; i++) {\n const candidate = path.join(dir, \"runtime\", \"dev-server.mjs\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new Error(\n \"Could not find the Rebase dev runtime (runtime/dev-server.mjs). \" +\n \"Reinstall @rebasepro/cli, or add a backend/src/index.ts to run your own entrypoint.\"\n );\n}\n\n/**\n * Tell the dev runtime where this project keeps its parts.\n *\n * Read from `rebase.json` when there is one, so a project that moved its config\n * directory is honoured; otherwise the conventional layout.\n */\nfunction devRuntimeEnv(projectRoot: string): Record<string, string> {\n const result: Record<string, string> = {\n REBASE_DEV_PROJECT_ROOT: projectRoot,\n REBASE_DEV_CONFIG: \"config\",\n REBASE_DEV_FUNCTIONS: \"backend/functions\",\n REBASE_DEV_CRONS: \"backend/crons\",\n REBASE_DEV_SCHEMA: \"backend/src/schema.generated.ts\"\n };\n\n try {\n const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (backend) {\n const paths = resolveBackendPaths(backend.app, projectRoot);\n result.REBASE_DEV_CONFIG = paths.config;\n result.REBASE_DEV_FUNCTIONS = paths.functions;\n result.REBASE_DEV_CRONS = paths.crons;\n result.REBASE_DEV_SCHEMA = paths.schema;\n result.REBASE_DEV_APP = backend.name;\n }\n } catch {\n // An invalid manifest is reported by `rebase build`; dev falls back to\n // the conventional layout rather than refusing to start.\n }\n\n // Nothing here says whether collections are declared or introspected, and\n // nothing should: `createSourceBundle` drops a config directory that does\n // not exist, and the server derives the answer from that. A REBASE_DEV_MODE\n // env var said it a second time, and a second place to say it is a second\n // place for it to disagree.\n return result;\n}\n\n/** Well-known filename the backend writes its actual port to. */\nconst DEV_PORT_FILENAME = \".rebase-dev-port\";\n\n/**\n * Compute a deterministic port from the project root path.\n * Range: 3001–3999 (avoids privileged ports and common services).\n * Two different project directories will almost always get different ports.\n */\nfunction getProjectPort(projectRoot: string): number {\n let hash = 0;\n for (let i = 0; i < projectRoot.length; i++) {\n hash = ((hash << 5) - hash + projectRoot.charCodeAt(i)) | 0;\n }\n return 3001 + (Math.abs(hash) % 999);\n}\n\n/**\n * Resolve the best starting port for this project:\n * 1. Explicit --port flag (highest priority)\n * 2. PORT env var\n * 3. Previously used port from .rebase-dev-port (port affinity across restarts)\n * 4. Deterministic hash from project path (unique per project)\n */\nfunction resolveStartPort(projectRoot: string, explicitPort?: number): number {\n // 1. Explicit flag\n if (explicitPort) return explicitPort;\n\n // 2. PORT env var\n if (process.env.PORT) return parseInt(process.env.PORT, 10);\n\n // 3. Port affinity — check if we wrote a port file from a previous run\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) {\n const saved = parseInt(fs.readFileSync(portFile, \"utf-8\").trim(), 10);\n if (saved > 0 && saved < 65536) return saved;\n }\n } catch { /* ignore */ }\n\n // 4. Deterministic hash\n return getProjectPort(projectRoot);\n}\n\nexport async function devCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--backend-only\": Boolean,\n \"--frontend-only\": Boolean,\n \"--port\": Number,\n \"--generate\": Boolean,\n \"--help\": Boolean,\n \"-b\": \"--backend-only\",\n \"-f\": \"--frontend-only\",\n \"-p\": \"--port\",\n \"-g\": \"--generate\",\n \"-h\": \"--help\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node rebase dev\"\n permissive: true\n }\n );\n\n if (args[\"--help\"]) {\n printDevHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n const frontendDir = findFrontendDir(projectRoot);\n const backendOnly = args[\"--backend-only\"] || false;\n const frontendOnly = args[\"--frontend-only\"] || false;\n const shouldGenerate = args[\"--generate\"] || process.env.REBASE_AUTO_GENERATE === \"true\" || process.env.REBASE_GENERATE === \"true\";\n\n // Resolve the port ONCE, before starting anything\n const startPort = resolveStartPort(projectRoot, args[\"--port\"]);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🚀 Rebase Dev Server\"));\n console.log(\"\");\n\n const children: ResultPromise[] = [];\n\n // --- State for printing the banner ---\n let frontendUrl = \"\";\n let backendUrl = \"\";\n let debounceSummary: NodeJS.Timeout | null = null;\n let bannerPrinted = false;\n\n /** Actual backend port, resolved once the server prints its URL. */\n let resolvedBackendPort: number | null = null;\n\n // Use regex to strip ANSI codes before matching\n // eslint-disable-next-line no-control-regex\n const stripAnsi = (str: string) => str.replace(/[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, \"\");\n\n function printSummary() {\n if (!frontendUrl || !backendUrl) return;\n if (debounceSummary) clearTimeout(debounceSummary);\n debounceSummary = setTimeout(() => {\n if (bannerPrinted) return;\n console.log(\"\");\n console.log(chalk.cyan(\"┌────────────────────────────────────────────────────────────┐\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"│ ✦ Rebase Admin App is ready! │\"));\n const cleanUrl = stripAnsi(frontendUrl);\n const paddedUrl = cleanUrl.padEnd(41);\n console.log(chalk.cyan(\"│ ➜ Frontend URL: \") + chalk.white(paddedUrl) + chalk.cyan(\"│\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"└────────────────────────────────────────────────────────────┘\"));\n console.log(\"\");\n bannerPrinted = true;\n }, 500);\n }\n\n // Handle graceful shutdown\n const cleanup = () => {\n // Clean up dev port file\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) fs.unlinkSync(portFile);\n\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(urlFile)) fs.unlinkSync(urlFile);\n } catch { /* ignore */ }\n\n children.forEach((child) => {\n if (child.pid && !child.killed) {\n try {\n if (process.platform === \"win32\") {\n execaCommandSync(`taskkill /pid ${child.pid} /T /F`);\n } else {\n process.kill(-child.pid, \"SIGKILL\");\n }\n } catch (e) {\n try {\n child.kill(\"SIGKILL\");\n } catch (err) {\n // ignore\n }\n }\n }\n });\n process.exit(0);\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n /**\n * Start the Vite frontend, optionally injecting the backend port.\n */\n function startFrontend(backendPort: number | null) {\n if (!frontendDir) return;\n\n console.log(` ${chalk.magenta(\"▶\")} Frontend: ${chalk.gray(frontendDir)}`);\n\n const frontendEnv: Record<string, string> = { ...process.env as Record<string, string> };\n\n // Inject the resolved backend URL so Vite picks it up\n if (backendPort) {\n frontendEnv.VITE_API_URL = `http://localhost:${backendPort}`;\n console.log(` ${chalk.gray(\"↳ VITE_API_URL\")} = ${chalk.white(`http://localhost:${backendPort}`)}`);\n }\n\n const pm = detectPackageManager(projectRoot);\n const pmCmds = getPMCommands(pm);\n const runDevCmd = pmCmds.run(\"dev\");\n\n const frontendChild = execa(\n runDevCmd[0],\n runDevCmd.slice(1),\n {\n cwd: frontendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: frontendEnv,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n frontendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n frontendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const urlMatch = cleanLine.match(/(http:\\/\\/(?:localhost|127\\.0\\.0\\.1):\\d+)/);\n if (cleanLine.includes(\"Local:\") && urlMatch) {\n frontendUrl = urlMatch[1];\n printSummary();\n }\n });\n });\n\n frontendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n });\n });\n\n children.push(frontendChild);\n }\n\n // Start backend\n if (!frontendOnly && backendDir) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const addCmd = [...pmCmdsLocal.install, \"-D\", \"tsx\"].join(\" \");\n console.error(chalk.red(\" ✗ Could not find tsx binary for backend.\"));\n console.error(chalk.gray(` Install it with: ${addCmd}`));\n process.exit(1);\n }\n\n // Verify the tsx installation is intact (not just the symlink)\n const tsxValidationError = validateTsxInstallation(tsxBin);\n if (tsxValidationError) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const installCmd = pmCmdsLocal.install.join(\" \");\n console.error(chalk.red(\" ✗ tsx installation appears corrupted.\"));\n console.error(chalk.gray(` ${tsxValidationError}`));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n process.exit(1);\n }\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n // Always inject PORT so the backend uses our resolved port instead of\n // its hardcoded default (3001). This prevents cross-project collisions\n // when multiple Rebase instances run simultaneously.\n env.PORT = String(startPort);\n\n console.log(` ${chalk.cyan(\"▶\")} Backend: ${chalk.gray(backendDir)}`);\n console.log(` ${chalk.gray(\"↳ PORT\")} = ${chalk.white(String(startPort))}`);\n\n // The .env's PORT / VITE_API_URL look authoritative but are overridden in\n // dev: we derive a per-project port to avoid cross-project collisions and\n // point the frontend at it. Surface that so a mismatched .env doesn't turn\n // into a silent \"connecting to the wrong port\" debugging loop.\n if (envFile) {\n try {\n const envText = fs.readFileSync(envFile, \"utf-8\");\n const readEnvKey = (key: string): string | undefined => {\n const m = envText.match(new RegExp(`^\\\\s*${key}\\\\s*=\\\\s*(.+?)\\\\s*$`, \"m\"));\n return m ? m[1].replace(/^[\"']|[\"']$/g, \"\") : undefined;\n };\n const envPort = readEnvKey(\"PORT\");\n const envApiUrl = readEnvKey(\"VITE_API_URL\");\n // Only name the keys — never echo a raw `http://localhost:<port>`\n // value, so log scrapers don't mistake it for the dev server URL.\n const overridden: string[] = [];\n if (envPort && envPort !== String(startPort)) overridden.push(\"PORT\");\n if (envApiUrl && envApiUrl !== `http://localhost:${startPort}`) overridden.push(\"VITE_API_URL\");\n if (overridden.length > 0) {\n console.log(chalk.yellow(\n ` ⚠ dev uses a derived per-project port (${startPort}); your .env ${overridden.join(\" / \")} ` +\n `${overridden.length > 1 ? \"are\" : \"is\"} ignored here (avoids cross-project collisions). ` +\n `Pass ${chalk.white(\"--port\")} to pin a port.`\n ));\n }\n } catch { /* ignore — best-effort notice */ }\n }\n\n /** Whether the frontend has been launched (we only launch it once). */\n let frontendLaunched = false;\n\n // Initial schema and SDK generation (disabled by default, enabled via --generate or env var)\n if (shouldGenerate) {\n console.log(chalk.gray(\" → Ensuring schema and SDK are generated on start...\"));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Initial schema and SDK generated successfully.\\n\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Initial schema/SDK generation failed: ${err instanceof Error ? err.message : err}\\n`));\n }\n\n // Watch collections folder for changes\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let watchDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n\n if (watchDebounce) clearTimeout(watchDebounce);\n watchDebounce = setTimeout(async () => {\n console.log(chalk.yellow(`\\n 🔄 Collection change detected (${filename}). Regenerating schema & SDK...`));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Schema & SDK regenerated successfully. Hono will reload.\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Failed to regenerate schema/SDK: ${err instanceof Error ? err.message : err}`));\n }\n }, 300);\n });\n }\n }\n\n // A project with its own `backend/src/index.ts` runs it, exactly as\n // before. Without one, dev boots the stock runtime over the project's\n // TypeScript source — the same boot path a deployment takes, so what runs\n // locally is what will run deployed. This is what makes the hand-written\n // entrypoint optional instead of something every project must carry.\n const ejectedEntry = path.join(backendDir, \"src\", \"index.ts\");\n const usesStockRuntime = !fs.existsSync(ejectedEntry);\n const entryTarget = usesStockRuntime ? resolveDevRuntimeEntry() : \"src/index.ts\";\n\n if (usesStockRuntime) {\n Object.assign(env, devRuntimeEnv(projectRoot));\n }\n\n const watchArgs = [\"watch\", \"--conditions\", \"development\", quoteForShell(entryTarget)];\n if (!shouldGenerate) {\n // When auto-generation is disabled, watch the config/collections dir directly so the dev server\n // still reloads automatically when files there are edited/updated manually.\n watchArgs.splice(1, 0, `--watch=\"${path.join(\"..\", \"config\", \"**\", \"*\")}\"`);\n\n // Watch collections folder and warn about potential schema drift\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let driftDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (_eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n if (driftDebounce) clearTimeout(driftDebounce);\n driftDebounce = setTimeout(() => {\n console.log([\n \"\",\n chalk.yellow(\" ┌──────────────────────────────────────────────────────────────┐\"),\n chalk.yellow(\" │ ⚠️ Collection file changed: \") + chalk.white(filename!.padEnd(31)) + chalk.yellow(\"│\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ Your schema may be out of sync. Run: │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase schema generate\") + chalk.yellow(\" regenerate Drizzle schema │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase db push \") + chalk.yellow(\" sync schema to database │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase doctor \") + chalk.yellow(\" check for drift │\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ TIP: Use \") + chalk.bold(\"rebase dev --generate\") + chalk.yellow(\" for auto-regeneration │\"),\n chalk.yellow(\" └──────────────────────────────────────────────────────────────┘\"),\n \"\"\n ].join(\"\\n\"));\n }, 500);\n });\n }\n }\n\n const backendChild = execa(\n tsxBin,\n watchArgs,\n {\n cwd: backendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n backendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n backendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const serverMatch = cleanLine.match(/Server running at http:\\/\\/(?:localhost|127\\.0\\.0\\.1):(\\d+)/);\n if (serverMatch) {\n resolvedBackendPort = parseInt(serverMatch[1], 10);\n backendUrl = \"started\";\n printSummary();\n\n // Save the url to a temp file for scripts to pick up\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n fs.writeFileSync(urlFile, `http://localhost:${resolvedBackendPort}`, \"utf-8\");\n\n // Save the port to .rebase-dev-port for port affinity\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n fs.writeFileSync(portFile, String(resolvedBackendPort), \"utf-8\");\n\n // Start frontend now that we know the real port\n if (!backendOnly && frontendDir && !frontendLaunched) {\n frontendLaunched = true;\n startFrontend(resolvedBackendPort);\n }\n }\n });\n });\n\n /** Whether we've already shown a corrupted-modules recovery hint. */\n let corruptedModulesWarned = false;\n\n backendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n\n // Detect corrupted node_modules at runtime\n // (covers tsx and any other dependency whose pnpm store entry is broken)\n if (!corruptedModulesWarned) {\n const cleanLine = stripAnsi(line);\n if (\n cleanLine.includes(\"Cannot find module\") &&\n cleanLine.includes(\"node_modules/.pnpm/\")\n ) {\n corruptedModulesWarned = true;\n // Delay slightly so the full Node.js error stack prints first\n setTimeout(() => {\n const pm = detectPackageManager(projectRoot);\n const installCmd = getPMCommands(pm).install.join(\" \");\n console.error(\"\");\n console.error(chalk.red(\" ✗ node_modules appears corrupted — a required file is missing.\"));\n console.error(chalk.gray(\" This usually happens when a previous install was interrupted\"));\n console.error(chalk.gray(\" or the package manager store was cleaned.\"));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, stop the dev server and run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n console.error(\"\");\n }, 200);\n }\n }\n });\n });\n\n children.push(backendChild);\n } else if (!frontendOnly && !backendDir) {\n console.warn(chalk.yellow(\" ⚠ No backend/ directory found, skipping backend.\"));\n }\n\n // Start frontend immediately if backend-only mode or no backend\n if (!backendOnly && frontendDir && (frontendOnly || !backendDir)) {\n startFrontend(null);\n } else if (!backendOnly && !frontendDir) {\n console.warn(chalk.yellow(\" ⚠ No frontend/ directory found, skipping frontend.\"));\n }\n\n if (children.length === 0) {\n console.error(chalk.red(\" ✗ Nothing to start. Check your project structure.\"));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Press Ctrl+C to stop all servers.\"));\n console.log(\"\");\n\n // Wait for all children to exit\n await Promise.all(\n children.map(\n (child) =>\n new Promise<void>((resolve) => {\n child.finally(() => resolve());\n })\n )\n );\n}\n\nfunction printDevHelp() {\n console.log(`\n${chalk.bold(\"rebase dev\")} — Start the development server\n\n${chalk.green.bold(\"Usage\")}\n rebase dev [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--backend-only, -b\")} Only start the backend server\n ${chalk.blue(\"--frontend-only, -f\")} Only start the frontend server\n ${chalk.blue(\"--port, -p\")} Backend port (default: auto-detected per project)\n ${chalk.blue(\"--generate, -g\")} Enable automatic schema and SDK generation on startup and file changes\n\n${chalk.green.bold(\"Description\")}\n Starts both the backend (tsx watch + Hono) and frontend (Vite)\n dev servers concurrently with color-coded output prefixes.\n\n Each project automatically receives a unique default port derived\n from its directory path, preventing collisions when running multiple\n Rebase instances simultaneously.\n\n If the assigned port is already in use, the server will automatically\n try the next available port. The frontend is started only after the\n backend is ready, and VITE_API_URL is injected automatically.\n\n By default, automatic schema and SDK generation is disabled on startup\n and file changes. Pass --generate (-g) or set REBASE_AUTO_GENERATE=true\n in your environment to enable it.\n`);\n}\n","/**\n * Building a project bundle.\n *\n * A bundle is the deployable form of a project: compiled collections, functions,\n * crons and schema, plus a generated manifest describing exactly what it needs\n * to run. It contains no Dockerfile and no repository — the runtime is supplied\n * separately, which is what allows a project to be moved onto a patched runtime\n * without being rebuilt.\n *\n * Compilation runs through a generated tsconfig rooted at the project directory,\n * so the output mirrors the source layout (`config/…`, `backend/functions/…`)\n * and every path in the manifest is predictable. Letting each workspace package\n * emit into its own `dist/` would have meant guessing at three different\n * layouts, since `rootDir` differs between the template flavours.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { createRequire } from \"module\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport {\n BUNDLE_FORMAT_VERSION,\n RUNTIME_CONTRACT_VERSION,\n computeSchemaVersion,\n findStorageSuffixCollision,\n normalizeStorageSources,\n type CollectionConfig,\n type DeclaredStorageSources,\n type NativeDependency,\n type RebaseBundleManifest,\n type RebaseBackendAppConfig\n} from \"@rebasepro/types\";\nimport { resolveBackendPaths } from \"./manifest\";\nimport {\n getActiveBackendPlugin,\n resolveLocalBin,\n resolvePluginCliScript,\n resolveTsx\n} from \"./utils/project\";\n\nexport const DEFAULT_BUNDLE_DIR = \"dist-bundle\";\n\nexport interface BuildBundleOptions {\n projectRoot: string;\n appName: string;\n app: RebaseBackendAppConfig;\n /** Output directory, absolute or relative to the project root. */\n outDir?: string;\n /** Runtime range from the manifest, recorded for compatibility checks. */\n runtimeRange: string;\n /**\n * The `storage` block of `rebase.json` — which buckets this project uses.\n *\n * Passed in rather than re-read here so `rebase.json` is parsed and validated\n * once, by the command that owns it.\n */\n storage?: DeclaredStorageSources;\n /** Skip type checking. Faster, and strictly worse — for iteration only. */\n skipTypeCheck?: boolean;\n /** Skip regenerating the Drizzle schema from the collections. */\n skipSchema?: boolean;\n /** Emit progress. */\n log?: (message: string) => void;\n}\n\nexport interface BuildBundleResult {\n outDir: string;\n manifest: RebaseBundleManifest;\n collectionCount: number;\n}\n\n/** Packages whose presence means the bundle cannot run on a stock runtime image. */\nconst KNOWN_NATIVE_PACKAGES = new Set([\n \"sharp\",\n \"canvas\",\n \"bcrypt\",\n \"argon2\",\n \"node-sass\",\n \"sqlite3\",\n \"better-sqlite3\",\n \"grpc\",\n \"@grpc/grpc-js-native\",\n \"re2\",\n \"sodium-native\",\n \"libpq\",\n \"pg-native\"\n]);\n\n/** Dependencies supplied by the runtime image itself, not by the bundle. */\nconst RUNTIME_PROVIDED = new Set([\n \"@rebasepro/server\",\n \"@rebasepro/types\",\n \"@rebasepro/client\",\n \"@rebasepro/common\",\n \"@rebasepro/utils\",\n \"hono\",\n \"@hono/node-server\",\n \"typescript\",\n \"tsx\"\n]);\n\nfunction log(options: BuildBundleOptions, message: string): void {\n (options.log ?? ((m: string) => console.log(m)))(message);\n}\n\n/**\n * Every `node_modules/@types` directory the project can see.\n *\n * Type roots normally resolve by walking up from the tsconfig's own directory,\n * which breaks here for two reasons: the generated config lives in `.rebase/`,\n * and a pnpm workspace puts `@types/node` inside the *package* that depends on\n * it (`config/node_modules/@types`) rather than at the project root. Listing them\n * explicitly, as absolute paths, sidesteps both.\n */\nfunction discoverTypeRoots(projectRoot: string): string[] {\n const candidates: string[] = [];\n\n for (const relative of [\".\", \"config\", \"backend\", \"frontend\"]) {\n candidates.push(path.join(projectRoot, relative, \"node_modules\", \"@types\"));\n }\n\n // Walk up as well, for a project nested inside a larger workspace.\n let dir = projectRoot;\n for (let i = 0; i < 4; i++) {\n const parent = path.dirname(dir);\n if (parent === dir) break;\n candidates.push(path.join(parent, \"node_modules\", \"@types\"));\n dir = parent;\n }\n\n return candidates.filter(candidate => fs.existsSync(candidate));\n}\n\n/**\n * Read a tsconfig's own `compilerOptions`.\n *\n * Parsed with the project's own TypeScript, because a tsconfig is not JSON: it\n * permits comments and trailing commas. Hand-rolled comment stripping gets this\n * wrong in a way that is easy to miss — a `paths` entry like\n * `\"@acme/types/*\": [\"src/*\"]` contains the character sequence that opens a\n * block comment, so a regex happily eats the rest of the file and the result\n * parses as *something*, just not the config the developer wrote.\n *\n * One level only, and only `paths` is used from it.\n */\nasync function readCompilerOptions(\n projectRoot: string,\n file: string\n): Promise<Record<string, unknown> | undefined> {\n if (!fs.existsSync(file)) return undefined;\n\n const text = fs.readFileSync(file, \"utf8\");\n\n try {\n const require = createRequire(path.join(projectRoot, \"package.json\"));\n const ts = require(\"typescript\") as {\n parseConfigFileTextToJson(fileName: string, text: string): {\n config?: { compilerOptions?: Record<string, unknown> };\n error?: unknown;\n };\n };\n const { config } = ts.parseConfigFileTextToJson(file, text);\n return config?.compilerOptions;\n } catch {\n // TypeScript is not resolvable from the project root. Fall back to\n // stripping whole-line comments only — never block comments, for the\n // reason above — and give up quietly if that still is not valid JSON.\n try {\n const parsed = JSON.parse(text.replace(/^\\s*\\/\\/.*$/gm, \"\")) as {\n compilerOptions?: Record<string, unknown>;\n };\n return parsed.compilerOptions;\n } catch {\n return undefined;\n }\n }\n}\n\n/**\n * Drop path aliases that resolve outside the project.\n *\n * A monorepo commonly aliases its workspace packages to their **source**\n * (`\"@acme/types\": [\"packages/types/src/index.ts\"]`) so editors jump to real\n * files. That is right for developing the monorepo and wrong for building a\n * bundle: it drags foreign `.ts` files into the program, none of which are under\n * the project's `rootDir`, and the compile fails on files the developer never\n * asked to build.\n *\n * A bundle is built against *installed packages*. Aliases pointing inside the\n * project are kept, because those are the project's own code.\n */\nfunction filterProjectPaths(\n baseDir: string,\n projectRoot: string,\n paths: Record<string, string[]>,\n baseUrl: string\n): { kept: Record<string, string[]>; dropped: string[] } {\n const kept: Record<string, string[]> = {};\n const dropped: string[] = [];\n\n for (const [alias, targets] of Object.entries(paths)) {\n if (!Array.isArray(targets)) continue;\n const resolved = targets.map(target => path.resolve(baseUrl, target));\n const allInside = resolved.every(target => {\n const relative = path.relative(projectRoot, target);\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n });\n if (allInside) {\n kept[alias] = resolved.map(target => {\n const relative = path.relative(baseDir, target);\n return relative.split(path.sep).join(\"/\");\n });\n } else {\n dropped.push(alias);\n }\n }\n\n return { kept,\ndropped };\n}\n\n/**\n * Compose the tsconfig used to compile the bundle.\n *\n * Extends the config package's own tsconfig when there is one, so the project's\n * choices about target, JSX and strictness are respected. It has to be `extends`\n * rather than a copy of `compilerOptions`: TypeScript resolves relative paths\n * against the file they were written in, so copying a value like\n * `baseUrl: \"../../\"` into a config in a different directory silently repoints\n * it at the wrong place.\n */\nasync function writeBundleTsconfig(\n projectRoot: string,\n outDir: string,\n includes: string[],\n skipTypeCheck: boolean\n): Promise<string> {\n // Paths written *here* resolve against this file's directory. Posix\n // separators, because tsconfig wants them on every platform.\n const tsconfigDir = path.join(projectRoot, \".rebase\");\n const fromTsconfig = (target: string): string => {\n const relative = path.relative(tsconfigDir, path.resolve(projectRoot, target));\n return relative.split(path.sep).join(\"/\");\n };\n\n const configTsconfigPath = path.join(projectRoot, \"config\", \"tsconfig.json\");\n const extendsFrom = fs.existsSync(configTsconfigPath)\n ? fromTsconfig(path.join(\"config\", \"tsconfig.json\"))\n : undefined;\n\n // Neutralize aliases that escape the project (see `filterProjectPaths`).\n let pathOverrides: Record<string, unknown> = {};\n const baseOptions = await readCompilerOptions(projectRoot, configTsconfigPath);\n if (baseOptions?.paths && typeof baseOptions.paths === \"object\") {\n const baseDir = path.dirname(configTsconfigPath);\n const baseUrl = path.resolve(\n baseDir,\n typeof baseOptions.baseUrl === \"string\" ? baseOptions.baseUrl : \".\"\n );\n const { kept, dropped } = filterProjectPaths(\n tsconfigDir,\n projectRoot,\n baseOptions.paths as Record<string, string[]>,\n baseUrl\n );\n pathOverrides = { baseUrl: fromTsconfig(\".\"),\npaths: kept };\n if (dropped.length > 0) {\n console.log(chalk.dim(\n ` ignoring ${dropped.length} path alias(es) pointing outside the project ` +\n `(${dropped.join(\", \")}) — resolving those from node_modules instead`\n ));\n }\n }\n\n const compilerOptions: Record<string, unknown> = {\n // Defaults, used when there is no project tsconfig to extend. When there\n // is one, its values win over these and are overridden only by the block\n // below.\n target: \"ES2022\",\n module: \"ESNext\",\n moduleResolution: \"bundler\",\n lib: [\"ES2022\"],\n jsx: \"react-jsx\",\n allowSyntheticDefaultImports: true,\n esModuleInterop: true,\n resolveJsonModule: true,\n forceConsistentCasingInFileNames: true,\n\n // Everything below is the bundle's contract and is not negotiable.\n rootDir: fromTsconfig(\".\"),\n outDir: fromTsconfig(path.relative(projectRoot, outDir) || \".\"),\n typeRoots: discoverTypeRoots(projectRoot),\n ...pathOverrides,\n declaration: false,\n declarationMap: false,\n sourceMap: true,\n noEmit: false,\n skipLibCheck: true,\n // The runtime imports the emitted files directly with Node's ESM loader,\n // so they stay ES modules regardless of what the project targets for its\n // own builds.\n allowJs: true,\n ...(skipTypeCheck ? { noCheck: true } : {})\n };\n\n const tsconfig = {\n ...(extendsFrom ? { extends: extendsFrom } : {}),\n compilerOptions,\n include: includes.map(fromTsconfig),\n exclude: [\n \"node_modules\",\n \"**/*.test.ts\",\n \"**/*.spec.ts\",\n \"**/dist/**\",\n DEFAULT_BUNDLE_DIR\n ].map(pattern => (pattern.startsWith(\"**\") ? pattern : fromTsconfig(pattern)))\n };\n\n fs.mkdirSync(tsconfigDir, { recursive: true });\n const tsconfigPath = path.join(tsconfigDir, \"tsconfig.bundle.json\");\n fs.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2), \"utf8\");\n return tsconfigPath;\n}\n\n/**\n * Whether the compiled config package exports a `storageAuthorize` hook.\n *\n * Recorded in the manifest so a host can refuse a deploy that would enable file\n * storage with no access model, rather than let the runtime's boot guard turn it\n * into a crash loop the developer cannot read.\n *\n * Read from the *compiled* index, deliberately: that is the exact module the\n * runtime imports and reads the export off, so this cannot disagree with what\n * actually happens at boot. It is a textual check rather than an import because\n * a freshly built bundle cannot resolve its own dependencies until it is\n * deployed — the same reason schema hashing reads source.\n *\n * Errs toward `false`: a missed detection costs a deploy rejection whose message\n * says exactly how to proceed, while a false positive would hand back the crash\n * loop this exists to prevent.\n */\nexport function detectStorageAuthorize(compiledConfigDir: string, depth = 0): boolean {\n const indexPath = [\".js\", \".mjs\", \".ts\"]\n .map(ext => path.join(compiledConfigDir, `index${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!indexPath) return false;\n return moduleExportsStorageAuthorize(indexPath, depth);\n}\n\n/**\n * Whether one compiled module re-exports or defines `storageAuthorize`.\n *\n * Split out from {@link detectStorageAuthorize} so a wildcard re-export can be\n * followed. `export * from \"./storage.js\"` is an ordinary way to write a config\n * barrel, and treating it as \"no hook\" rejected deploys that were correct — with\n * a message telling the developer to add a hook they had already written.\n */\nfunction moduleExportsStorageAuthorize(modulePath: string, depth: number): boolean {\n let source: string;\n try {\n source = fs.readFileSync(modulePath, \"utf8\");\n } catch {\n return false;\n }\n\n // `export const/let/var/function/async function storageAuthorize`\n if (/\\bexport\\s+(?:async\\s+)?(?:const|let|var|function)\\s+storageAuthorize\\b/.test(source)) {\n return true;\n }\n // `export { storageAuthorize }` / `export { x as storageAuthorize }`,\n // including re-export forms (`export { storageAuthorize } from \"./storage\"`).\n for (const clause of source.matchAll(/\\bexport\\s*\\{([^}]*)\\}/g)) {\n const names = clause[1].split(\",\").map(entry => {\n const parts = entry.split(/\\bas\\b/);\n return parts[parts.length - 1].trim();\n });\n if (names.includes(\"storageAuthorize\")) return true;\n }\n\n // `export * from \"./storage.js\"` — follow it. Bounded to a few levels: a\n // barrel of barrels is realistic, an infinite chain is not, and the cost of\n // giving up is a rejection message rather than a wrong answer.\n if (depth < 3) {\n for (const clause of source.matchAll(/\\bexport\\s*\\*\\s*from\\s*[\"']([^\"']+)[\"']/g)) {\n const specifier = clause[1];\n if (!specifier.startsWith(\".\")) continue;\n const resolved = resolveRelativeModule(path.dirname(modulePath), specifier);\n if (resolved && moduleExportsStorageAuthorize(resolved, depth + 1)) return true;\n }\n }\n return false;\n}\n\n/**\n * Resolve a relative ESM specifier to a file on disk.\n *\n * Compiled output carries explicit `.js` extensions, but the same function reads\n * TypeScript sources during a source boot, where the specifier may be\n * extensionless or point at a directory index.\n */\nfunction resolveRelativeModule(fromDir: string, specifier: string): string | null {\n const base = path.resolve(fromDir, specifier);\n const candidates = [\n base,\n `${base}.js`,\n `${base}.mjs`,\n `${base}.ts`,\n path.join(base, \"index.js\"),\n path.join(base, \"index.mjs\"),\n path.join(base, \"index.ts\")\n ];\n for (const candidate of candidates) {\n try {\n if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;\n } catch {\n continue;\n }\n }\n // A `.js` specifier that only exists as `.ts` — the shape every compiled-from-\n // TypeScript barrel has when this runs against sources rather than output.\n if (/\\.js$/.test(base)) {\n const asTs = base.replace(/\\.js$/, \".ts\");\n try {\n if (fs.existsSync(asTs) && fs.statSync(asTs).isFile()) return asTs;\n } catch {\n return null;\n }\n }\n return null;\n}\n\n/**\n * Detect native code in the dependency closure.\n *\n * Walks declared runtime dependencies breadth-first through `node_modules`,\n * flagging anything with a `binding.gyp`, a prebuilt `.node` binary, or an\n * install script that builds one. The managed runtime cannot run these: a\n * binary compiled for one image will not load in another, and finding that out\n * at deploy time is far better than in a crash loop.\n *\n * The walk is bounded. A dependency graph can be enormous, and this is a\n * heuristic gate whose false negatives are caught at deploy time anyway.\n */\nexport function detectNativeDependencies(\n projectRoot: string,\n declared: Record<string, string>,\n limit = 2000\n): NativeDependency[] {\n const found: NativeDependency[] = [];\n const seen = new Set<string>();\n const queue = Object.keys(declared);\n let visited = 0;\n\n const searchRoots = [\n path.join(projectRoot, \"node_modules\"),\n path.join(projectRoot, \"backend\", \"node_modules\"),\n path.join(projectRoot, \"config\", \"node_modules\")\n ].filter(dir => fs.existsSync(dir));\n\n while (queue.length > 0 && visited < limit) {\n const name = queue.shift()!;\n if (seen.has(name)) continue;\n seen.add(name);\n visited++;\n\n if (KNOWN_NATIVE_PACKAGES.has(name)) {\n found.push({ name,\nreason: \"known native module\" });\n continue;\n }\n\n const packageDir = searchRoots\n .map(root => path.join(root, ...name.split(\"/\")))\n .find(dir => fs.existsSync(path.join(dir, \"package.json\")));\n\n if (!packageDir) continue;\n\n let pkg: {\n dependencies?: Record<string, string>;\n scripts?: Record<string, string>;\n gypfile?: boolean;\n };\n try {\n pkg = JSON.parse(fs.readFileSync(path.join(packageDir, \"package.json\"), \"utf8\"));\n } catch {\n continue;\n }\n\n if (pkg.gypfile || fs.existsSync(path.join(packageDir, \"binding.gyp\"))) {\n found.push({ name,\nreason: \"builds a native addon (binding.gyp)\" });\n continue;\n }\n\n const install = `${pkg.scripts?.install ?? \"\"} ${pkg.scripts?.preinstall ?? \"\"} ${pkg.scripts?.postinstall ?? \"\"}`;\n if (/node-gyp|prebuild|node-pre-gyp|cmake-js/.test(install)) {\n found.push({ name,\nreason: \"install script compiles native code\" });\n continue;\n }\n\n if (hasNodeBinary(packageDir)) {\n found.push({ name,\nreason: \"ships a prebuilt .node binary\" });\n continue;\n }\n\n for (const dep of Object.keys(pkg.dependencies ?? {})) {\n if (!seen.has(dep)) queue.push(dep);\n }\n }\n\n return found;\n}\n\n/** Shallow scan for `.node` binaries — deep enough for the usual `build/Release`. */\nfunction hasNodeBinary(dir: string, depth = 0): boolean {\n if (depth > 3) return false;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return false;\n }\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith(\".node\")) return true;\n if (entry.isDirectory() && entry.name !== \"node_modules\" && entry.name !== \".bin\") {\n if (hasNodeBinary(path.join(dir, entry.name), depth + 1)) return true;\n }\n }\n return false;\n}\n\n/**\n * Whether a dependency name resolves to a package *inside this repository* — a\n * workspace package rather than a registry one.\n *\n * The bundle's declared deps are installed with `npm install` from the public\n * registry beside the bundle at boot. A workspace package is not there, so\n * declaring it guarantees a boot-time install failure. The most common case is\n * the standard `config` package: the backend depends on it by name, but it is\n * *carried in the bundle* (as `entry.config`), so it must never also be an npm\n * dependency. Projects often express this as a `workspace:` range — caught\n * separately — but a plain `\"*\"` against a workspace symlink is just as common\n * and looks like a registry range, so the symlink is what actually settles it.\n *\n * Detection: the installed `node_modules/<name>` is a symlink whose real path is\n * inside the project and not within a pnpm virtual store (`.pnpm`). That is\n * exactly a workspace link and nothing else.\n */\nfunction resolvesToWorkspacePackage(projectRoot: string, name: string): boolean {\n // Resolve the root's own symlinks too: on macOS a temp/checkout path under\n // `/var/...` realpaths to `/private/var/...`, so comparing a realpath'd link\n // target against a non-realpath'd root would never match.\n let realRoot: string;\n try {\n realRoot = fs.realpathSync(projectRoot);\n } catch {\n realRoot = projectRoot;\n }\n\n for (const base of [projectRoot, path.join(projectRoot, \"backend\"), path.join(projectRoot, \"config\")]) {\n const link = path.join(base, \"node_modules\", name);\n try {\n // A workspace link is a *symlink*; a normal (non-pnpm) registry\n // install is a real directory inside node_modules, which would also\n // sit \"inside the repo\" — so the symlink is what separates the two.\n if (!fs.lstatSync(link).isSymbolicLink()) continue;\n const real = fs.realpathSync(link);\n const insideRepo = real.startsWith(realRoot + path.sep);\n // pnpm links registry packages into its virtual store; those live\n // under node_modules/.pnpm and are not workspace packages.\n const inStore = real.includes(`${path.sep}.pnpm${path.sep}`)\n || real.includes(`${path.sep}node_modules${path.sep}`);\n if (insideRepo && !inStore) return true;\n } catch {\n // No such entry, broken link, or race: let it be declared.\n }\n }\n return false;\n}\n\n/**\n * Collect the runtime dependencies a bundle needs installed beside it.\n *\n * Packages the runtime image already provides are excluded — reinstalling a\n * second copy of the server next to the one running the process is at best\n * wasted space and at worst a version conflict. Workspace packages are excluded\n * too: they are not on the registry the runtime installs from, and the project's\n * own config package already travels inside the bundle.\n */\nexport function collectDeclaredDependencies(projectRoot: string): Record<string, string> {\n const declared: Record<string, string> = {};\n\n for (const relative of [\"backend/package.json\", \"config/package.json\", \"package.json\"]) {\n const file = path.join(projectRoot, relative);\n if (!fs.existsSync(file)) continue;\n try {\n const pkg = JSON.parse(fs.readFileSync(file, \"utf8\")) as {\n dependencies?: Record<string, string>;\n };\n for (const [name, version] of Object.entries(pkg.dependencies ?? {})) {\n if (RUNTIME_PROVIDED.has(name)) continue;\n // A workspace protocol means nothing outside this repository.\n if (typeof version === \"string\" && version.startsWith(\"workspace:\")) continue;\n // A plain range that nonetheless resolves to an in-repo workspace\n // package (e.g. `\"config\": \"*\"` symlinked to `../../config`) —\n // the runtime cannot install it from the registry.\n if (resolvesToWorkspacePackage(projectRoot, name)) continue;\n declared[name] = version;\n }\n } catch {\n // Unparseable package.json: nothing to declare from it.\n }\n }\n\n return declared;\n}\n\n/**\n * Rewrite relative import specifiers in emitted JavaScript so Node can resolve them.\n *\n * TypeScript deliberately does not touch specifiers: `moduleResolution: \"bundler\"`\n * lets a project write `from \"./posts\"` or `from \"./collections\"`, and TypeScript\n * emits them unchanged on the assumption that a bundler will finish the job.\n * Nothing bundles a Rebase bundle — the runtime imports these files directly with\n * Node's ESM loader, which requires a full path with an extension and refuses\n * directory imports outright.\n *\n * Without this, adopting the bundle would mean asking every project written in\n * the (extremely common) extensionless style to rewrite all of its imports. The\n * rewrite is mechanical and verifiable: only relative specifiers are touched, and\n * only when the target file actually exists on disk.\n */\nexport function normalizeEsmSpecifiers(outDir: string): { rewritten: number; unresolved: string[] } {\n const unresolved: string[] = [];\n let rewritten = 0;\n\n // The specifier of a static import/export, a bare side-effect import, or a\n // dynamic import. Emitted output is not minified, so these forms are stable.\n const SPECIFIER = /(\\bfrom\\s*|\\bimport\\s*\\(\\s*|\\bimport\\s+)([\"'])(\\.[^\"']*)\\2/g;\n\n const walk = (dir: string): void => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\") continue;\n walk(full);\n } else if (entry.isFile() && entry.name.endsWith(\".js\")) {\n rewriteFile(full);\n }\n }\n };\n\n const rewriteFile = (file: string): void => {\n const original = fs.readFileSync(file, \"utf8\");\n const dir = path.dirname(file);\n\n const updated = original.replace(SPECIFIER, (match, prefix, quote, specifier) => {\n // Already resolvable: has a real extension.\n if (/\\.(js|mjs|cjs|json|node)$/.test(specifier)) return match;\n\n const target = path.resolve(dir, specifier);\n\n if (fs.existsSync(`${target}.js`)) {\n rewritten++;\n return `${prefix}${quote}${specifier}.js${quote}`;\n }\n if (fs.existsSync(path.join(target, \"index.js\"))) {\n rewritten++;\n const suffix = specifier.endsWith(\"/\") ? \"index.js\" : \"/index.js\";\n return `${prefix}${quote}${specifier}${suffix}${quote}`;\n }\n\n // A `.ts` extension written explicitly in source becomes `.js` on disk.\n if (specifier.endsWith(\".ts\") && fs.existsSync(`${target.slice(0, -3)}.js`)) {\n rewritten++;\n return `${prefix}${quote}${specifier.slice(0, -3)}.js${quote}`;\n }\n\n unresolved.push(`${path.basename(file)} → ${specifier}`);\n return match;\n });\n\n if (updated !== original) {\n fs.writeFileSync(file, updated, \"utf8\");\n }\n };\n\n if (fs.existsSync(outDir)) walk(outDir);\n return { rewritten,\nunresolved };\n}\n\n/**\n * Remove a previous build so stale output cannot masquerade as current.\n *\n * The containment check matters because this is a recursive force-delete of a\n * path that came from a command-line flag: `rebase build --out ../..` would\n * otherwise erase the parent of the project. The manifest's own paths are\n * checked the same way; a flag deserves no less.\n */\nfunction cleanOutDir(projectRoot: string, outDir: string): void {\n const relative = path.relative(projectRoot, outDir);\n if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(\n `Refusing to build into \"${outDir}\": the output directory must be inside the project.`\n );\n }\n\n if (fs.existsSync(outDir)) {\n fs.rmSync(outDir, { recursive: true,\nforce: true });\n }\n fs.mkdirSync(outDir, { recursive: true });\n}\n\n/**\n * Regenerate the Drizzle schema from the collections.\n *\n * Delegated to the database driver's own CLI — the same code `rebase schema\n * generate` runs — so there is one implementation of what a schema is. When no\n * driver is resolvable the build continues with a warning rather than failing:\n * a `baas` project has no schema to generate, and a project mid-install should\n * get a clear message rather than a hard stop.\n */\nasync function regenerateSchema(\n projectRoot: string,\n configDir: string,\n options: BuildBundleOptions\n): Promise<void> {\n const backendDir = path.join(projectRoot, \"backend\");\n if (!fs.existsSync(backendDir)) return;\n\n const plugin = getActiveBackendPlugin(backendDir);\n const script = plugin ? resolvePluginCliScript(backendDir, plugin) : null;\n if (!script) {\n log(options, chalk.dim(\" (no database driver found — skipping schema generation)\"));\n return;\n }\n\n const runner = script.endsWith(\".ts\") ? resolveTsx(projectRoot) : \"node\";\n if (!runner) {\n log(options, chalk.dim(\" (tsx not installed — skipping schema generation)\"));\n return;\n }\n\n const collectionsPath = path.join(\"..\", configDir, \"collections\");\n try {\n await execa(\n runner,\n [script, \"schema\", \"generate\", \"--collections\", collectionsPath],\n { cwd: backendDir,\nstdio: \"pipe\" }\n );\n log(options, chalk.dim(\" regenerated database schema from collections\"));\n } catch (err) {\n // A schema that cannot be generated means the bundle would carry a stale\n // one, and a stale schema is how a deploy quietly writes to the wrong\n // columns. Fail rather than ship it.\n const detail = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Schema generation failed, so the bundle was not written.\\n${detail}\\n` +\n \"Run `rebase schema generate` to see the full output, or pass --skip-schema \" +\n \"if the committed schema is deliberately hand-maintained.\"\n );\n }\n}\n\n/**\n * A hand-written server entrypoint that a bundle does not use.\n *\n * `rebase dev` runs `backend/src/index.ts` whenever a project has one, so for\n * the whole of local development that file *is* the server and every route\n * written in it works. A bundle has no entrypoint of its own: the runtime boots\n * the bundle and mounts what the manifest points at — the config package,\n * functions, crons and the schema. The file is not compiled, not shipped, and\n * never imported.\n *\n * Nothing said so. A project with custom routes in its entrypoint built clean,\n * deployed green, and answered 404 on every one of them, with the file still\n * sitting in the repository looking exactly like the server.\n *\n * A project that means to keep its own entrypoint runs `rebase eject`, which\n * writes the entrypoint, a Dockerfile and a compose file together and flips the\n * backend to `runtime: \"custom\"`. The warning names that route rather than\n * implying the file is a mistake.\n */\nexport function findUnusedServerEntry(projectRoot: string, functionsDir: string): string | undefined {\n // A project that relocated its functions keeps the entrypoint beside them,\n // so the second candidate is derived rather than only the default known.\n const candidates = [\n path.join(\"backend\", \"src\", \"index.ts\"),\n path.join(path.dirname(functionsDir), \"src\", \"index.ts\")\n ];\n\n const found = candidates.find(candidate => fs.existsSync(path.join(projectRoot, candidate)));\n return found ? found.split(path.sep).join(\"/\") : undefined;\n}\n\n/**\n * Compile and assemble a bundle.\n */\nexport async function buildBundle(options: BuildBundleOptions): Promise<BuildBundleResult> {\n const { projectRoot, app, appName } = options;\n const paths = resolveBackendPaths(app, projectRoot);\n const outDir = path.resolve(projectRoot, options.outDir ?? DEFAULT_BUNDLE_DIR);\n\n const includes: string[] = [];\n const addIfExists = (relative: string, pattern: string): void => {\n if (fs.existsSync(path.join(projectRoot, relative))) includes.push(pattern);\n };\n\n // The whole config package, not just its collections: a headless project\n // has no `config/collections` but still ships `storageAuthorize` here.\n if (paths.hasConfig) {\n addIfExists(paths.config, `${paths.config}/**/*.ts`);\n }\n addIfExists(paths.functions, `${paths.functions}/**/*.ts`);\n addIfExists(paths.crons, `${paths.crons}/**/*.ts`);\n if (fs.existsSync(path.join(projectRoot, paths.schema))) {\n includes.push(paths.schema);\n }\n\n if (includes.length === 0) {\n throw new Error(\n `Nothing to build for app \"${appName}\". Expected a config directory at ` +\n `\"${paths.config}\" or functions at \"${paths.functions}\".`\n );\n }\n\n // Regenerate the Drizzle schema from the collections first.\n //\n // The template's backend build did this, so a project moving to the bundle\n // flow would otherwise silently ship whatever `schema.generated.ts` happened\n // to be on disk — stale by exactly the edits just made.\n if (paths.hasCollections && options.skipSchema !== true) {\n await regenerateSchema(projectRoot, paths.config, options);\n }\n\n // Say out loud what this build is NOT going to include. See\n // `findUnusedServerEntry` for why silence here was expensive.\n const unusedEntry = findUnusedServerEntry(projectRoot, paths.functions);\n if (unusedEntry) {\n const parts = [\n ...(paths.hasCollections ? [`${paths.config}/`] : []),\n `${paths.functions}/`,\n \"the schema\"\n ];\n const compiled = `${parts.slice(0, -1).join(\", \")} and ${parts[parts.length - 1]}`;\n console.log(chalk.yellow(` ⚠ ${unusedEntry} is not the bundle's entry point — it is not compiled or shipped.`));\n console.log(chalk.dim(` The runtime boots the bundle itself and mounts ${compiled}.`));\n console.log(chalk.dim(` Routes defined there will not exist once deployed: move them to ${paths.functions}/,`));\n console.log(chalk.dim(` or run \\`rebase eject\\` to make this file the entrypoint and own the image.`));\n }\n\n log(options, chalk.dim(` compiling ${includes.length} source group(s) → ${path.relative(projectRoot, outDir)}/`));\n\n cleanOutDir(projectRoot, outDir);\n const tsconfigPath = await writeBundleTsconfig(projectRoot, outDir, includes, options.skipTypeCheck === true);\n\n const tsc = resolveLocalBin(projectRoot, \"tsc\");\n if (!tsc) {\n throw new Error(\n \"TypeScript is not installed in this project. Run your package manager's install first.\"\n );\n }\n\n try {\n await execa(tsc, [\"-p\", tsconfigPath], { cwd: projectRoot,\nstdio: \"inherit\" });\n } catch {\n throw new Error(\"TypeScript compilation failed — the bundle was not written.\");\n }\n\n // Node resolves these files directly, so their specifiers must be complete.\n const normalized = normalizeEsmSpecifiers(outDir);\n if (normalized.rewritten > 0) {\n log(options, chalk.dim(` resolved ${normalized.rewritten} relative import(s) for Node ESM`));\n }\n if (normalized.unresolved.length > 0) {\n console.log(chalk.yellow(\n ` ⚠ ${normalized.unresolved.length} import(s) could not be resolved to a file:`\n ));\n for (const item of normalized.unresolved.slice(0, 5)) {\n console.log(chalk.dim(` ${item}`));\n }\n if (normalized.unresolved.length > 5) {\n console.log(chalk.dim(` … and ${normalized.unresolved.length - 5} more`));\n }\n }\n\n // ── Inspect what was produced ────────────────────────────────────────────\n const compiledConfigDir = path.join(outDir, paths.config);\n const compiledCollectionsDir = path.join(compiledConfigDir, \"collections\");\n\n let collections: CollectionConfig[] = [];\n if (paths.hasCollections) {\n collections = await loadSourceCollections(path.join(projectRoot, paths.config, \"collections\"));\n if (collections.length === 0) {\n throw new Error(\n \"No collections were found in \" +\n `${path.join(paths.config, \"collections\")}. ` +\n \"Define at least one collection there, or remove the directory to have the \" +\n \"runtime introspect collections from the live database instead.\"\n );\n }\n if (!fs.existsSync(compiledCollectionsDir)) {\n throw new Error(\n \"Compilation produced no collections directory at \" +\n `${path.relative(projectRoot, compiledCollectionsDir)}.`\n );\n }\n }\n\n const declared = collectDeclaredDependencies(projectRoot);\n const nativeModules = detectNativeDependencies(projectRoot, declared);\n const declaresStorageAuthorize = detectStorageAuthorize(path.join(outDir, paths.config));\n\n // Resolve the declared buckets now, and refuse the build if two of them would\n // read the same environment variables. Catching it here means a rename, not a\n // tenant that silently served one bucket's files from another's credentials.\n const storageSources = normalizeStorageSources(options.storage, undefined);\n const collision = findStorageSuffixCollision(storageSources.map(s => s.key));\n if (collision) {\n throw new Error(\n `Storage sources \"${collision.a}\" and \"${collision.b}\" in rebase.json both map to the ` +\n `environment variable suffix \"${collision.suffix || \"(none)\"}\", so they would read each ` +\n \"other's configuration. Rename one of them.\"\n );\n }\n\n const schemaOut = paths.schema.replace(/\\.ts$/, \".js\");\n const relative = (target: string): string | undefined =>\n fs.existsSync(path.join(outDir, target)) ? target : undefined;\n\n const manifest: RebaseBundleManifest = {\n bundleFormat: BUNDLE_FORMAT_VERSION,\n runtime: {\n range: options.runtimeRange,\n builtAgainst: resolveServerVersion(projectRoot),\n contract: RUNTIME_CONTRACT_VERSION\n },\n // A build with no config directory genuinely does not know the schema —\n // collections are introspected from the live database at boot. Recording\n // a version here would stamp the hash of an empty list, and the runtime\n // would then serve that as the identity of whatever it actually found.\n // Empty means \"ask the runtime\", which is the honest answer.\n schemaVersion: paths.hasCollections ? computeSchemaVersion(collections) : \"\",\n app: appName,\n kind: \"backend\",\n entry: {\n config: paths.hasConfig ? relative(paths.config) : undefined,\n collections: paths.hasCollections ? relative(path.join(paths.config, \"collections\")) : undefined,\n functions: relative(paths.functions),\n crons: relative(paths.crons),\n schema: relative(schemaOut),\n usersCollection: paths.hasCollections\n ? relative(path.join(paths.config, `${paths.usersCollection}.js`))\n : undefined\n },\n collections: collections\n .map(collection => collection.slug)\n .filter((slug): slug is string => Boolean(slug))\n .sort(),\n hooks: {\n native: nativeModules.length > 0,\n nativeModules: nativeModules.length > 0 ? nativeModules : undefined\n },\n storage: {\n authorize: declaresStorageAuthorize,\n ...(storageSources.length > 0 ? { sources: storageSources } : {})\n },\n deps: { declared },\n build: {\n cli: resolveCliVersion(),\n node: process.versions.node.split(\".\")[0],\n createdAt: new Date().toISOString()\n }\n };\n\n fs.writeFileSync(\n path.join(outDir, \"manifest.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n \"utf8\"\n );\n\n // A package.json beside the bundle lets a deployment install exactly the\n // dependencies the project declared, with no access to the repository.\n fs.writeFileSync(\n path.join(outDir, \"package.json\"),\n `${JSON.stringify({\n name: \"rebase-bundle\",\n private: true,\n type: \"module\",\n dependencies: declared\n }, null, 2)}\\n`,\n \"utf8\"\n );\n\n return { outDir,\nmanifest,\ncollectionCount: collections.length };\n}\n\n/**\n * Package a built static app (a `static` or bundled-`admin` app) into a bundle.\n *\n * A static bundle is the counterpart to a backend bundle: the same shape, the\n * same runtime image runs it, but its manifest says `mode: \"static\"` and it\n * carries only the built assets under `static/`. That is what lets a frontend or\n * admin app be its own deployable, scalable unit rather than something baked into\n * the backend container.\n *\n * `assetsDir` is the app's built output (e.g. `frontend/dist`), already produced\n * by its own build command. This copies it into the bundle and writes the\n * manifest — no compilation, no dependency closure (a static bundle installs\n * nothing at boot).\n */\n/**\n * Fold a built static app into a backend bundle, so one runtime serves both.\n *\n * ## Why this exists\n *\n * A managed tenant runs one pod, and `bootFromBundle` on the backend path already\n * knows how to serve a SPA — it looks for `entry.static` and mounts `serveSPA`\n * last, behind `REBASE_SERVE_STATIC`. What was missing was anything putting the\n * assets there.\n *\n * The consequence was not subtle. A project whose custom image served its website\n * at `/` and its API at `/api` — the shape the scaffolded template produces — lost\n * the website the moment it moved to the managed runtime: the API answered\n * perfectly and every page 404'd. Managed could not be a drop-in replacement for\n * custom while the frontend simply vanished.\n *\n * Folding restores parity with the container it replaces, which is the only\n * honest baseline. It is deliberately the FIRST implementation and not the last:\n * a static app on its own bucket behind a CDN is better for cache behaviour and\n * lets the frontend deploy independently. But that needs infrastructure that does\n * not exist yet, and \"your site is gone\" is not an acceptable state to leave a\n * project in while it gets built.\n *\n * The trade it makes, stated plainly: frontend and backend now deploy together\n * and the bundle carries the built assets. For a project that was shipping both\n * in one image already, that is exactly what it had.\n */\nexport function foldStaticIntoBundle(options: {\n /** The backend bundle directory, already written. */\n bundleDir: string;\n /** Directory of built frontend assets (the static app's `output`). */\n assetsDir: string;\n /** The app's name in `rebase.json`. Names its directory inside the bundle. */\n appName: string;\n /** Public base path this app is served under. */\n path: string;\n /** Serve `index.html` for unmatched paths under `path`. */\n spa: boolean;\n}): { fileCount: number; dir: string } {\n const { bundleDir, assetsDir, appName, path: basePath, spa } = options;\n const manifestPath = path.join(bundleDir, \"manifest.json\");\n if (!fs.existsSync(manifestPath)) {\n throw new Error(`No manifest at ${manifestPath} — build the backend bundle first.`);\n }\n if (!fs.existsSync(assetsDir)) {\n throw new Error(`No built assets at ${assetsDir}.`);\n }\n\n // Each app gets its own directory, and only its own is cleared. Folding used\n // to wipe `static/` wholesale and write a single `entry.static` string, so a\n // second app silently replaced the first — both in the tree and in the\n // manifest — and the bundle deployed looking complete.\n const dir = path.posix.join(\"static\", appName);\n const staticOut = path.join(bundleDir, \"static\", appName);\n fs.rmSync(staticOut, { recursive: true, force: true });\n fs.mkdirSync(staticOut, { recursive: true });\n fs.cpSync(assetsDir, staticOut, { recursive: true });\n\n let fileCount = 0;\n const count = (target: string): void => {\n for (const entry of fs.readdirSync(target, { withFileTypes: true })) {\n if (entry.isDirectory()) count(path.join(target, entry.name));\n else fileCount++;\n }\n };\n count(staticOut);\n\n // Record it, because the runtime finds the assets through the manifest —\n // not by guessing a directory name.\n const manifest = JSON.parse(fs.readFileSync(manifestPath, \"utf8\")) as RebaseBundleManifest;\n const existing = (manifest.entry?.static ?? []).filter(entry => entry.dir !== dir);\n manifest.entry = {\n ...manifest.entry,\n static: [...existing, { path: basePath,\ndir,\nspa }]\n };\n fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\n\n return { fileCount,\ndir };\n}\n\nexport function buildStaticBundle(options: {\n projectRoot: string;\n appName: string;\n assetsDir: string;\n outDir: string;\n runtimeRange: string;\n /** Public base path. Default `/` — a standalone bundle owns its origin. */\n path?: string;\n /** Serve `index.html` for unmatched paths. Default `true`. */\n spa?: boolean;\n}): { outDir: string; manifest: RebaseBundleManifest; fileCount: number } {\n const { projectRoot, appName, assetsDir, outDir, runtimeRange } = options;\n const basePath = options.path ?? \"/\";\n\n cleanOutDir(projectRoot, outDir);\n\n const staticOut = path.join(outDir, \"static\");\n fs.mkdirSync(staticOut, { recursive: true });\n fs.cpSync(assetsDir, staticOut, { recursive: true });\n\n let fileCount = 0;\n const count = (dir: string): void => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) count(path.join(dir, entry.name));\n else fileCount++;\n }\n };\n count(staticOut);\n\n const manifest: RebaseBundleManifest = {\n bundleFormat: BUNDLE_FORMAT_VERSION,\n runtime: {\n range: runtimeRange,\n builtAgainst: resolveServerVersion(projectRoot),\n contract: RUNTIME_CONTRACT_VERSION\n },\n // A static app has no collections and therefore no schema contract.\n schemaVersion: \"\",\n app: appName,\n kind: \"static\",\n // Normally `/` — a standalone bundle owns its origin. It carries the\n // app's declared path rather than hardcoding one so that the bundle\n // agrees with what the assets were actually *built* for; serving a\n // `/admin`-built app at `/` is the blank-page failure in reverse.\n entry: { static: [{ path: basePath,\ndir: \"static\",\nspa: options.spa ?? true }] },\n hooks: { native: false },\n // Nothing to install beside a static bundle — it is just files.\n deps: { declared: {} },\n build: {\n cli: resolveCliVersion(),\n node: process.versions.node.split(\".\")[0],\n createdAt: new Date().toISOString()\n }\n };\n\n fs.writeFileSync(\n path.join(outDir, \"manifest.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n \"utf8\"\n );\n // An empty package.json keeps the runtime's boot-time install a clean no-op.\n fs.writeFileSync(\n path.join(outDir, \"package.json\"),\n `${JSON.stringify({ name: \"rebase-bundle\", private: true, type: \"module\", dependencies: {} }, null, 2)}\\n`,\n \"utf8\"\n );\n\n return { outDir, manifest, fileCount };\n}\n\n/**\n * Which files in a collections directory are collections.\n *\n * Mirrors the runtime loader's rules exactly, and must keep mirroring them: the\n * set of files counted here decides the schema version, and the runtime decides\n * what it serves the same way. A divergence would show up as a client that is\n * permanently \"out of date\" against a server that agrees with it.\n *\n * (`._*` guards macOS AppleDouble files, which look like sources and are not.)\n */\nfunction isCollectionSourceFile(name: string): boolean {\n if (name.startsWith(\".\")) return false;\n if (name.includes(\".test.\") || name.includes(\".spec.\")) return false;\n if (name.endsWith(\".d.ts\")) return false;\n if (name === \"index.ts\" || name === \"index.js\") return false;\n return name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Load collections from **source**, for hashing and for the manifest's slug list.\n *\n * Deliberately not the compiled output. A compiled bundle imports its\n * dependencies from beside itself — that is the whole point of shipping a\n * `package.json` with it — but at build time nothing has been installed there\n * yet, and under pnpm the project's own `node_modules` lives one directory per\n * package, so the emitted files genuinely cannot resolve their imports until\n * they are deployed.\n *\n * Reading source costs nothing in fidelity: compilation erases types, it does\n * not change the values a collection module exports, so the hash is the same\n * either way.\n */\nasync function loadSourceCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n if (!fs.existsSync(collectionsDir)) return [];\n\n const { createJiti } = await import(\"jiti\") as {\n createJiti: (filename: string, options?: Record<string, unknown>) => {\n import: (id: string) => Promise<unknown>;\n };\n };\n const jiti = createJiti(path.join(collectionsDir, \"index.ts\"), {\n interopDefault: true,\n esmResolve: true\n });\n\n const files = fs.readdirSync(collectionsDir)\n .filter(isCollectionSourceFile)\n .sort();\n\n const collections: CollectionConfig[] = [];\n const failures: string[] = [];\n\n for (const file of files) {\n try {\n const mod = await jiti.import(path.join(collectionsDir, file)) as\n { default?: CollectionConfig } | CollectionConfig;\n const collection = (mod as { default?: CollectionConfig }).default\n ?? (mod as CollectionConfig);\n if (collection && typeof collection === \"object\" && \"slug\" in collection) {\n collections.push(collection);\n } else {\n failures.push(`${file}: no default-exported collection`);\n }\n } catch (err) {\n failures.push(`${file}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Could not read ${failures.length} collection file(s):\\n` +\n failures.map(f => ` • ${f}`).join(\"\\n\")\n );\n }\n\n return collections;\n}\n\n/** The `@rebasepro/server` version the project resolves — what it was built against. */\nfunction resolveServerVersion(projectRoot: string): string {\n const candidates = [\n path.join(projectRoot, \"node_modules\", \"@rebasepro\", \"server\", \"package.json\"),\n path.join(projectRoot, \"backend\", \"node_modules\", \"@rebasepro\", \"server\", \"package.json\")\n ];\n for (const candidate of candidates) {\n if (!fs.existsSync(candidate)) continue;\n try {\n return (JSON.parse(fs.readFileSync(candidate, \"utf8\")) as { version: string }).version;\n } catch {\n // fall through\n }\n }\n return \"unknown\";\n}\n\nfunction resolveCliVersion(): string {\n try {\n const here = path.dirname(new URL(import.meta.url).pathname);\n let dir = here;\n for (let i = 0; i < 5; i++) {\n const candidate = path.join(dir, \"package.json\");\n if (fs.existsSync(candidate)) {\n const pkg = JSON.parse(fs.readFileSync(candidate, \"utf8\")) as {\n name?: string;\n version?: string;\n };\n if (pkg.name === \"@rebasepro/cli\" && pkg.version) return pkg.version;\n }\n dir = path.dirname(dir);\n }\n } catch {\n // Version is informational; an unknown value must not fail a build.\n }\n return \"unknown\";\n}\n","/**\n * Folding a project's static apps into its backend bundle.\n *\n * Shared by `rebase build` and `rebase cloud deploy` deliberately. It lived in\n * the build *command* first, and `deploy` rebuilds the bundle itself — so a\n * deploy silently produced a bundle without the frontend, packed 164 KB where\n * 39 MB was expected, and the site 404'd on the managed runtime exactly as if\n * folding had never been written. Two callers building the same artefact must\n * share the step that completes it.\n *\n * Why fold at all: `bootFromBundle` serves static apps from `entry.static`\n * behind `REBASE_SERVE_STATIC` (default on). A managed tenant runs one pod, so\n * putting the built assets in the bundle gives it the shape a custom container\n * already had — site at `/`, admin at `/admin`, API at `/api` — which is the\n * only honest baseline for calling the managed runtime a drop-in replacement.\n *\n * **Every** static app is folded, each at its declared path. Folding used to\n * pick exactly one and refuse when it found two, which meant a project with a\n * site and an admin panel deployed with neither.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { foldStaticIntoBundle } from \"./bundle\";\n\n/** The apps section of a project manifest, as much of it as folding needs. */\nexport interface FoldableManifest {\n apps?: Record<string, {\n type?: string;\n build?: string;\n output?: string;\n path?: string;\n spa?: boolean;\n }>;\n}\n\nexport interface FoldOptions {\n projectRoot: string;\n manifest: FoldableManifest;\n /** The backend bundle directory, already written. */\n bundleDir: string;\n /** Skip running each app's own build command; fold what is already built. */\n skipBuild?: boolean;\n log?: (message: string) => void;\n}\n\nexport interface FoldOutcome {\n appName: string;\n fileCount: number;\n /** Public base path this app was folded in at. */\n path: string;\n}\n\n/** A static app as folding sees it, with the manifest's defaults applied. */\nexport interface FoldableApp {\n name: string;\n build?: string;\n output?: string;\n /** Public base path, defaulted to `/`. */\n path: string;\n /** SPA fallback, defaulted to `true`. */\n spa: boolean;\n}\n\n/**\n * Every static app in the manifest, in mount order.\n *\n * Longest path first, so the `/`-rooted app is registered last — its catch-all\n * would otherwise claim its siblings' URLs. Pure, so the ordering is testable\n * without a filesystem.\n */\nexport function foldableApps(manifest: FoldableManifest): {\n apps: FoldableApp[];\n /** Apps that cannot be folded, and why. */\n skipped: { name: string; reason: string }[];\n} {\n const apps: FoldableApp[] = [];\n const skipped: { name: string; reason: string }[] = [];\n\n for (const [name, app] of Object.entries(manifest.apps ?? {})) {\n if (app?.type !== \"static\") continue;\n if (!app.output) {\n skipped.push({ name,\nreason: `\"${name}\" declares no output directory — not folded in.` });\n continue;\n }\n apps.push({\n name,\n build: app.build,\n output: app.output,\n path: app.path ?? \"/\",\n spa: app.spa ?? true\n });\n }\n\n apps.sort((a, b) => b.path.length - a.path.length);\n return { apps,\nskipped };\n}\n\n/**\n * Assert a built app's assets are actually rooted at the path it is served from.\n *\n * An app mounted at `/admin` but built with Vite's default `base: \"/\"` emits\n * `<script src=\"/assets/index-a1b2.js\">`. The server serves `index.html` fine\n * and 404s every asset: a blank page, no server error, nothing in the logs. It\n * is the single most expensive silent failure in this design, so it is a build\n * error rather than a runtime surprise.\n *\n * Only `<script src>` and `<link href>` are inspected — those are what a bundler\n * rewrites through `base`. Author-written anchors and canonical URLs are not\n * evidence of a misbuild.\n */\nexport function assertBuiltForPath(\n indexHtml: string,\n basePath: string,\n appName: string\n): void {\n if (basePath === \"/\") return;\n\n const offenders: string[] = [];\n const pattern = /<(?:script|link)\\b[^>]*?\\b(?:src|href)\\s*=\\s*[\"']([^\"']+)[\"']/gi;\n for (const match of indexHtml.matchAll(pattern)) {\n const ref = match[1];\n if (!ref.startsWith(\"/\")) continue;\n if (ref === `${basePath}` || ref.startsWith(`${basePath}/`)) continue;\n offenders.push(ref);\n }\n\n if (offenders.length === 0) return;\n\n throw new Error(\n `\"${appName}\" is declared at ${basePath} but its build emitted assets rooted at /.\\n` +\n ` index.html references: ${offenders.slice(0, 3).join(\", \")}\\n` +\n \" The app would load a blank page. Set `base` from REBASE_APP_BASE in its\\n\" +\n \" build config — see docs/apps-and-runtimes.md §4.2.\"\n );\n}\n\n/**\n * Build the project's static apps and fold them into the backend bundle.\n *\n * Throws rather than exiting, so the caller decides whether a missing frontend\n * should fail its command — a `build` may reasonably want to stop, and so should\n * a deploy, but that is not this function's call to make.\n */\nexport async function foldFrontendIntoBundle(options: FoldOptions): Promise<FoldOutcome[]> {\n const { projectRoot, manifest, bundleDir, skipBuild } = options;\n const log = options.log ?? ((m: string) => console.log(m));\n\n const { apps, skipped } = foldableApps(manifest);\n for (const { reason } of skipped) log(chalk.yellow(` ⚠ ${reason}`));\n if (apps.length === 0) return [];\n\n const outcomes: FoldOutcome[] = [];\n\n for (const app of apps) {\n if (app.build && !skipBuild) {\n await execa(app.build, {\n cwd: projectRoot,\n stdio: \"inherit\",\n shell: true,\n // The path is a build-time input, not only a serving concern.\n // Vite reads `base` from REBASE_APP_BASE; the trailing slash is\n // that field's convention.\n env: {\n REBASE_APP_PATH: app.path,\n REBASE_APP_BASE: app.path === \"/\" ? \"/\" : `${app.path}/`,\n REBASE_APP_NAME: app.name\n }\n });\n }\n\n const assetsDir = path.join(projectRoot, app.output as string);\n if (!fs.existsSync(assetsDir)) {\n // Exited 0 and produced nothing where the manifest says it should.\n // Folding that ships an empty site, which from the outside is\n // indistinguishable from a broken deploy.\n throw new Error(\n `\"${app.name}\" declared output \"${app.output}\" does not exist after building — ` +\n \"the bundle would ship without a frontend.\"\n );\n }\n\n const indexHtml = path.join(assetsDir, \"index.html\");\n if (fs.existsSync(indexHtml)) {\n assertBuiltForPath(fs.readFileSync(indexHtml, \"utf8\"), app.path, app.name);\n }\n\n const { fileCount } = foldStaticIntoBundle({\n bundleDir,\n assetsDir,\n appName: app.name,\n path: app.path,\n spa: app.spa\n });\n outcomes.push({ appName: app.name,\nfileCount,\npath: app.path });\n }\n\n return outcomes;\n}\n","/**\n * CLI command: rebase build [app...]\n *\n * Builds the apps a repository declares in `rebase.json`.\n *\n * For a `backend` app this produces a **bundle** — compiled collections,\n * functions and schema plus a manifest — which is the artifact the runtime\n * loads. For `static` and bundled `admin` apps it runs the declared build\n * command and reports where the output landed.\n *\n * A project with no manifest, or one whose backend has been ejected to its own\n * entrypoint, falls back to the previous behaviour: run every workspace's own\n * `build` script. Nothing that built before stops building.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport type { RebaseAppConfig, RebaseStaticAppConfig } from \"@rebasepro/types\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { buildableApps, findBackendApp, loadManifest, ManifestError } from \"../manifest\";\nimport { buildBundle, buildStaticBundle, DEFAULT_BUNDLE_DIR } from \"../bundle\";\nimport { assertBuiltForPath, foldFrontendIntoBundle } from \"../fold-static\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase build\")} — build the apps declared in rebase.json\n\n${chalk.bold(\"Usage\")}\n rebase build [app...] Build the named apps (default: all)\n\n${chalk.bold(\"Options\")}\n --out <dir> Bundle output directory (default: ${DEFAULT_BUNDLE_DIR})\n --skip-type-check Compile without type checking (faster; use for iteration only)\n --skip-schema Do not regenerate the database schema from collections\n --legacy Run every workspace's own build script instead\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase build Build every app in this repository\n rebase build backend Build only the backend bundle\n rebase build web Build only the \"web\" static app\n`.trim());\n}\n\nexport async function buildCommand(rawArgs: string[] = []): Promise<void> {\n const args = arg(\n {\n \"--out\": String,\n \"--skip-type-check\": Boolean,\n \"--skip-schema\": Boolean,\n /* Do not fold the frontend into the backend bundle. For a project\n that publishes its frontend elsewhere and does not want the assets\n travelling with its API. */\n \"--no-static\": Boolean,\n /* Fold assets that are already built, without re-running the app's\n build command — for a CI job that built the frontend in an earlier\n step. */\n \"--skip-static-build\": Boolean,\n \"--legacy\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n },\n { argv: rawArgs.slice(3), permissive: true }\n );\n\n if (args[\"--help\"]) {\n printHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n\n if (args[\"--legacy\"]) {\n await runWorkspaceBuilds(projectRoot);\n return;\n }\n\n let loaded;\n try {\n loaded = loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.red(` ${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n\n const { manifest, source } = loaded;\n const requested = args._.filter(a => !a.startsWith(\"-\"));\n\n let targets = buildableApps(manifest);\n if (requested.length > 0) {\n const known = new Set(targets.map(t => t.name));\n const unknown = requested.filter(name => !known.has(name));\n if (unknown.length > 0) {\n console.error(chalk.red(`✗ Unknown app(s): ${unknown.join(\", \")}`));\n console.error(chalk.dim(` This repository declares: ${targets.map(t => t.name).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n targets = targets.filter(t => requested.includes(t.name));\n }\n\n if (targets.length === 0) {\n console.log(chalk.yellow(\"No buildable apps declared. Nothing to do.\"));\n return;\n }\n\n // An ejected backend owns its own build; the workspace scripts are the only\n // thing that knows how to run it.\n const backend = findBackendApp(manifest);\n if (!backend && source === \"synthesized\") {\n console.log(chalk.dim(\"No rebase.json found — building workspace packages.\\n\"));\n await runWorkspaceBuilds(projectRoot);\n return;\n }\n\n console.log(`${chalk.bold(\"Rebase\")} — building ${targets.length} app(s)\\n`);\n\n for (const { name, app } of targets) {\n console.log(chalk.cyan(`▸ ${name}`) + chalk.dim(` (${app.type})`));\n\n if (app.type === \"backend\" && app.runtime === \"custom\") {\n // An ejected backend's artifact is an IMAGE, not a bundle. Building\n // one anyway produced a `dist-bundle/` the project never deploys,\n // which is worse than doing nothing: it looks like the thing that\n // ships. The workspace's own `build` script compiles this app, and\n // the Dockerfile turns it into the image.\n console.log(chalk.dim(\" custom runtime — this project builds its own image, not a bundle\"));\n console.log(chalk.dim(` ${chalk.cyan(`npm run build --workspace ${name}`)} then ${chalk.cyan(`docker build -f ${app.dockerfile ?? \"Dockerfile\"} .`)}`));\n console.log(\"\");\n continue;\n }\n\n if (app.type === \"backend\") {\n const result = await buildBundle({\n projectRoot,\n appName: name,\n app,\n outDir: args[\"--out\"],\n runtimeRange: manifest.rebase,\n storage: manifest.storage,\n skipTypeCheck: args[\"--skip-type-check\"],\n skipSchema: args[\"--skip-schema\"]\n });\n const rel = path.relative(projectRoot, result.outDir);\n console.log(chalk.green(` ✓ bundle → ${rel}/`));\n console.log(chalk.dim(` ${result.collectionCount} collection(s), schema ${result.manifest.schemaVersion}`));\n if (result.manifest.hooks.native) {\n const names = (result.manifest.hooks.nativeModules ?? []).map(m => m.name).join(\", \");\n console.log(chalk.yellow(` ⚠ native dependencies detected: ${names}`));\n console.log(chalk.dim(\" These cannot run on the managed runtime. See `rebase doctor`.\"));\n }\n\n /* Fold the project's static apps into the backend bundle, so ONE\n runtime serves the site at `/`, the admin at `/admin` and the API\n at `/api` — the shape the scaffolded template produces and the\n shape a custom container already had.\n\n Without this, moving a project to the managed runtime silently\n removed its website: the API answered perfectly and every page\n 404'd, because the managed pod runs the backend bundle and nothing\n else. Parity with the container being replaced is the only honest\n baseline for calling managed a drop-in.\n\n `--no-static` opts out, for a project that publishes its frontend\n somewhere else and does not want the assets in its bundle. */\n if (!args[\"--no-static\"]) {\n const folded = await foldFrontendIntoBundle({\n projectRoot,\n manifest,\n bundleDir: result.outDir,\n skipBuild: args[\"--skip-static-build\"] === true,\n log: (m) => console.log(m)\n }).catch((err: unknown) => {\n console.error(chalk.red(` ✗ ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n });\n for (const outcome of folded ?? []) {\n console.log(\n chalk.green(` ✓ ${outcome.appName} folded in`) +\n chalk.dim(` (${outcome.fileCount} file(s) → served at ${outcome.path})`)\n );\n }\n }\n } else if (app.type === \"static\") {\n await buildAssetApp(projectRoot, name, app, manifest.rebase, args[\"--out\"]);\n }\n\n console.log(\"\");\n }\n\n console.log(chalk.green(\"✓ Build complete.\"));\n}\n\n/**\n * Build a static app and package it into a static bundle.\n *\n * Runs the app's own build command, checks it produced the declared output, then\n * packages that output into a `static`-kind bundle — the same deployable shape as\n * a backend bundle, so a frontend or admin app deploys through the identical\n * path and runs on the identical image, just serving files instead of an API.\n */\nasync function buildAssetApp(\n projectRoot: string,\n name: string,\n app: RebaseAppConfig,\n runtimeRange: string,\n outOverride?: string\n): Promise<void> {\n const asset = app as RebaseStaticAppConfig;\n const basePath = asset.path ?? \"/\";\n\n if (!asset.build) {\n console.log(chalk.dim(\" no build command declared — skipping\"));\n return;\n }\n\n try {\n await execa(asset.build, {\n cwd: projectRoot,\n stdio: \"inherit\",\n shell: true,\n // See `assertBuiltForPath` — the declared path is a build input.\n env: {\n REBASE_APP_PATH: basePath,\n REBASE_APP_BASE: basePath === \"/\" ? \"/\" : `${basePath}/`,\n REBASE_APP_NAME: name\n }\n });\n } catch {\n console.error(chalk.red(` ✗ build command failed for \"${name}\"`));\n process.exit(1);\n }\n\n if (!asset.output) {\n console.log(chalk.yellow(\" no output directory declared — built, but nothing to bundle\"));\n return;\n }\n\n const outputPath = path.join(projectRoot, asset.output);\n if (!fs.existsSync(outputPath)) {\n // The command exited 0 but produced nothing where the manifest says it\n // should. Bundling that would ship an empty site.\n console.error(chalk.red(` ✗ declared output \"${asset.output}\" does not exist after building`));\n process.exit(1);\n }\n\n // The assets were built for `basePath`; refusing here is the difference\n // between a build error and a blank page nobody can diagnose.\n const indexHtml = path.join(outputPath, \"index.html\");\n if (fs.existsSync(indexHtml)) {\n try {\n assertBuiltForPath(fs.readFileSync(indexHtml, \"utf8\"), basePath, name);\n } catch (err) {\n console.error(chalk.red(` ✗ ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n }\n\n // Per-app bundle directory, so a project's several static apps do not clobber\n // one another or the backend's `dist-bundle`.\n const outDir = outOverride\n ? path.resolve(process.cwd(), outOverride)\n : path.join(projectRoot, `dist-bundle-${name}`);\n const result = buildStaticBundle({\n projectRoot,\n appName: name,\n assetsDir: outputPath,\n outDir,\n runtimeRange,\n path: basePath,\n spa: asset.spa ?? true\n });\n const rel = path.relative(projectRoot, result.outDir);\n console.log(\n chalk.green(` ✓ static bundle → ${rel}/`) +\n chalk.dim(` (${result.fileCount} file(s) → served at ${basePath})`)\n );\n}\n\n/** The pre-manifest behaviour: build every workspace package. */\nasync function runWorkspaceBuilds(projectRoot: string): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const buildCmd = cmds.runAll(\"build\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Building all workspaces with ${chalk.cyan(pm)}...\\n`);\n\n try {\n await execa(buildCmd[0], buildCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\"\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Build failed.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase eject\n *\n * The supported route from the managed runtime to a custom one.\n *\n * Without it, `runtime: \"custom\"` is a mode a user can only reach by\n * hand-writing an entrypoint they have never seen. The template used to solve\n * that by scaffolding `backend/src/index.ts` into every project — ~190 lines\n * configuring CORS, auth, cookies, storage and history, which the managed\n * runtime never loads. It was the most important-looking file in a new project\n * and editing it did nothing.\n *\n * So the file moved here. A managed project does not carry it; a project that\n * asks for it gets it together with the Dockerfile and the manifest change that\n * make it actually run.\n *\n * There is deliberately no `rebase uneject`. Going back is deleting two files\n * and editing one line, and a command that silently discarded a user's server\n * code would be worse than its absence.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport type { RebaseBackendAppConfig } from \"@rebasepro/types\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError, writeManifest } from \"../manifest\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\n/** Walk up to the package root, which holds `templates/`. */\nfunction findCliRoot(from: string): string | null {\n const root = path.parse(from).root;\n let dir = from;\n while (dir && dir !== root) {\n if (fs.existsSync(path.join(dir, \"templates\", \"eject\"))) return dir;\n dir = path.dirname(dir);\n }\n return null;\n}\n\n/** Files the eject payload contributes, as `<source> → <destination>`. */\nconst PAYLOAD: { from: string; to: string; overwrite: boolean }[] = [\n // The entrypoint IS the point of ejecting, so it is written even if\n // something is already there — but only after the guard below has\n // established that this project is not already ejected.\n { from: \"backend/src/index.ts\",\nto: \"backend/src/index.ts\",\noverwrite: true },\n { from: \"backend/src/env.ts\",\nto: \"backend/src/env.ts\",\noverwrite: true },\n // Never overwritten: a Dockerfile someone already wrote is theirs, and so is\n // a compose file they have edited. The scaffolded `docker-compose.yml` is\n // deliberately left alone — it runs the managed shape, and going back should\n // stay a one-line change rather than a restore from git.\n { from: \"Dockerfile\",\nto: \"Dockerfile\",\noverwrite: false },\n { from: \"docker-compose.custom.yml\",\nto: \"docker-compose.custom.yml\",\noverwrite: false }\n];\n\n/**\n * The project's name, for the `{{PROJECT_NAME}}` the payload carries.\n *\n * Falls back to the directory name — a compose project name is cosmetic, and a\n * missing or unreadable package.json is not a reason to refuse to eject.\n */\nfunction projectNameOf(projectRoot: string): string {\n try {\n const pkg = JSON.parse(fs.readFileSync(path.join(projectRoot, \"package.json\"), \"utf8\"));\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name.trim();\n } catch {\n // fall through\n }\n return path.basename(projectRoot);\n}\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase eject\")} — take ownership of the server process\n\nWrites the backend entrypoint and a Dockerfile into this project, and flips its\nbackend to ${chalk.cyan('runtime: \"custom\"')}. From then on this repository builds its own\nimage: platform runtime upgrades no longer reach it, and CORS, auth wiring,\nstorage and shutdown become yours to configure.\n\n${chalk.bold(\"Usage\")}\n rebase eject [app]\n\n${chalk.bold(\"Options\")}\n --dry-run List what would change, and change nothing\n -h, --help Show this help\n`.trim());\n}\n\nexport async function ejectCommand(rawArgs: string[] = []): Promise<void> {\n const args = arg(\n {\n \"--dry-run\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n\n if (args[\"--help\"]) {\n printHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const dryRun = Boolean(args[\"--dry-run\"]);\n // `_[0]` is the command itself.\n const requested = args._.slice(1).find(value => !value.startsWith(\"-\"));\n\n let loaded;\n try {\n loaded = loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.dim(` ${issue.path}: ${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n\n const { manifest } = loaded;\n\n let appName: string;\n let app: RebaseBackendAppConfig;\n\n if (requested) {\n const declared = manifest.apps[requested];\n if (!declared) {\n console.error(chalk.red(`✗ No app named \"${requested}\" in rebase.json.`));\n console.error(chalk.dim(` Declared: ${Object.keys(manifest.apps).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n if (declared.type !== \"backend\") {\n // Ejecting is about who runs the server. A static app has no server.\n console.error(chalk.red(`✗ \"${requested}\" is a ${declared.type} app — only a backend can be ejected.`));\n process.exit(1);\n }\n appName = requested;\n app = declared;\n } else {\n const backend = findBackendApp(manifest);\n if (!backend) {\n console.error(chalk.red(\"✗ This repository declares no backend app.\"));\n console.error(chalk.dim(\" Only the repository that declares the backend chooses its runtime.\"));\n process.exit(1);\n }\n appName = backend.name;\n app = backend.app;\n }\n\n if (app.runtime === \"custom\") {\n console.error(chalk.red(`✗ \"${appName}\" is already ejected — it declares runtime: \"custom\".`));\n console.error(chalk.dim(` Its entrypoint is ${app.dockerfile ?? \"Dockerfile\"} and backend/src/index.ts.`));\n process.exit(1);\n }\n\n const cliRoot = findCliRoot(__dirname);\n if (!cliRoot) {\n console.error(chalk.red(\"✗ Could not locate the eject templates. Reinstall @rebasepro/cli.\"));\n process.exit(1);\n }\n const payloadDir = path.join(cliRoot!, \"templates\", \"eject\");\n\n // Decide everything before writing anything, so --dry-run and the real run\n // report the same list and a mid-way failure cannot leave a half-ejected\n // project.\n const planned: { to: string; action: \"write\" | \"keep\" }[] = [];\n for (const file of PAYLOAD) {\n const source = path.join(payloadDir, file.from);\n if (!fs.existsSync(source)) {\n console.error(chalk.red(`✗ The eject template is missing ${file.from}. Reinstall @rebasepro/cli.`));\n process.exit(1);\n }\n const exists = fs.existsSync(path.join(projectRoot, file.to));\n planned.push({\n to: file.to,\n action: exists && !file.overwrite ? \"keep\" : \"write\"\n });\n }\n\n if (dryRun) {\n console.log(chalk.bold(`Would eject \"${appName}\" to a custom runtime:`));\n console.log(\"\");\n for (const item of planned) {\n console.log(item.action === \"write\"\n ? ` ${chalk.green(\"write\")} ${item.to}`\n : ` ${chalk.dim(\"keep\")} ${item.to} ${chalk.dim(\"(already exists)\")}`);\n }\n console.log(` ${chalk.green(\"write\")} rebase.json ${chalk.dim('(runtime: \"custom\")')}`);\n console.log(\"\");\n console.log(chalk.dim(\"Nothing was changed.\"));\n return;\n }\n\n const projectName = projectNameOf(projectRoot);\n for (const [index, file] of PAYLOAD.entries()) {\n if (planned[index].action === \"keep\") continue;\n const destination = path.join(projectRoot, file.to);\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n const contents = fs\n .readFileSync(path.join(payloadDir, file.from), \"utf8\")\n .replace(/\\{\\{PROJECT_NAME\\}\\}/g, projectName);\n fs.writeFileSync(destination, contents, \"utf8\");\n }\n\n const dockerfile = app.dockerfile ?? \"Dockerfile\";\n manifest.apps[appName] = {\n ...app,\n runtime: \"custom\",\n dockerfile,\n port: app.port ?? 8080\n };\n writeManifest(projectRoot, manifest);\n\n // The backend workspace stops being a package the runtime reads and becomes\n // one that is run. Its scripts have to say so, or `npm start` in the image\n // has nothing to call.\n restoreBackendScripts(projectRoot);\n\n console.log(\"\");\n console.log(chalk.green(`✓ Ejected \"${appName}\" to a custom runtime.`));\n console.log(\"\");\n console.log(` ${chalk.cyan(\"backend/src/index.ts\".padEnd(26))} your entrypoint — the runtime no longer boots the bundle`);\n console.log(` ${chalk.cyan(\"backend/src/env.ts\".padEnd(26))} the environment it reads`);\n console.log(` ${chalk.cyan(dockerfile.padEnd(26))} your image`);\n console.log(` ${chalk.cyan(\"docker-compose.custom.yml\".padEnd(26))} runs it`);\n console.log(` ${chalk.cyan(\"rebase.json\".padEnd(26))} runtime: custom`);\n console.log(\"\");\n console.log(chalk.yellow(\" You now own CORS, auth wiring, storage and shutdown. Platform runtime\"));\n console.log(chalk.yellow(\" upgrades no longer reach this project.\"));\n console.log(\"\");\n console.log(chalk.dim(` ${chalk.cyan(\"docker compose -f docker-compose.custom.yml up --build\")}`));\n console.log(chalk.dim(\" docker-compose.yml is untouched — it still runs the managed shape if you go back.\"));\n console.log(\"\");\n}\n\n/**\n * Point the backend workspace's scripts at the entrypoint that now exists.\n *\n * A managed project's backend package deliberately declares no `main` and no\n * `start`: there is no entrypoint to name. Ejecting creates one.\n */\nfunction restoreBackendScripts(projectRoot: string): void {\n const packagePath = path.join(projectRoot, \"backend\", \"package.json\");\n if (!fs.existsSync(packagePath)) return;\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(fs.readFileSync(packagePath, \"utf8\"));\n } catch {\n // A malformed package.json is the user's to fix, and refusing to finish\n // the eject over it would leave the project half-changed.\n console.log(chalk.yellow(\" ⚠ backend/package.json is not valid JSON — its scripts were left alone.\"));\n return;\n }\n\n const scripts = (parsed.scripts ?? {}) as Record<string, string>;\n parsed.main ??= \"src/index.ts\";\n scripts.dev ??= 'tsx watch --include=\"../config/**/*\" --include=\"./functions/**/*\" src/index.ts';\n scripts.start ??= \"node dist/backend/src/index.js\";\n parsed.scripts = scripts;\n\n fs.writeFileSync(packagePath, `${JSON.stringify(parsed, null, 4)}\\n`, \"utf8\");\n}\n","/**\n * CLI command: rebase start\n *\n * Runs a built bundle through the Rebase runtime — the same path the official\n * container image takes, so what you test locally is what a deployment runs.\n *\n * When there is no bundle (an ejected backend, or a project that has not adopted\n * `rebase.json`) this falls back to the backend workspace's own `start` script,\n * which is what such a project has always used.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { DEFAULT_BUNDLE_DIR } from \"../bundle\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase start\")} — run a built bundle\n\n${chalk.bold(\"Usage\")}\n rebase start [options]\n\n${chalk.bold(\"Options\")}\n --bundle <dir> Bundle directory (default: ${DEFAULT_BUNDLE_DIR})\n --legacy Run the backend workspace's own start script\n -h, --help Show this help\n\nBuild first with ${chalk.cyan(\"rebase build\")}.\n`.trim());\n}\n\nexport async function startCommand(rawArgs: string[] = []): Promise<void> {\n const args = arg(\n {\n \"--bundle\": String,\n \"--legacy\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n },\n { argv: rawArgs.slice(3), permissive: true }\n );\n\n if (args[\"--help\"]) {\n printHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n const bundleDir = path.resolve(projectRoot, args[\"--bundle\"] ?? DEFAULT_BUNDLE_DIR);\n const hasBundle = fs.existsSync(path.join(bundleDir, \"manifest.json\"));\n\n if (args[\"--legacy\"] || !hasBundle) {\n if (!args[\"--legacy\"] && !hasBundle) {\n console.log(chalk.dim(\n `No bundle at ${path.relative(projectRoot, bundleDir)}/ — ` +\n \"starting the backend workspace instead.\\n\"\n ));\n }\n await startWorkspaceBackend(projectRoot, env);\n return;\n }\n\n ensureBundleDependencies(projectRoot, bundleDir);\n\n console.log(`${chalk.bold(\"Rebase\")} — starting runtime from ${chalk.cyan(path.relative(projectRoot, bundleDir))}/\\n`);\n\n // Loaded in-process rather than spawned: the runtime is a library here, so\n // signals, exit codes and stdio need no forwarding, and there is one less\n // process between the developer and a stack trace.\n if (envFile && fs.existsSync(envFile)) {\n const dotenv = await import(\"dotenv\");\n dotenv.config({ path: envFile });\n }\n\n process.env.REBASE_BUNDLE = bundleDir;\n\n try {\n const { runFromBundle } = await import(\"@rebasepro/server\");\n await runFromBundle({ bundleDir });\n } catch (err) {\n console.error(chalk.red(\"\\n✗ Failed to start the runtime.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Make a bundle's imports resolvable for a local run.\n *\n * Node resolves a module by walking up from the *importing file*, so compiled\n * code sitting in `dist-bundle/` no longer sees the per-package `node_modules`\n * its source could: pnpm and npm both install a workspace package's\n * dependencies inside that package, and the bundle is not inside any of them.\n *\n * A deployment solves this by installing the bundle's own `package.json` beside\n * it — that is what the generated `package.json` is for. Locally, doing a second\n * install to run code whose dependencies are already on disk would be wasteful,\n * so this links what is already there instead.\n *\n * Only ever created when absent, and only under the bundle directory, so a real\n * install always wins and nothing here is ever uploaded (`rebase build` cleans\n * the directory and never writes this).\n */\nfunction ensureBundleDependencies(projectRoot: string, bundleDir: string): void {\n const target = path.join(bundleDir, \"node_modules\");\n if (fs.existsSync(target)) return;\n\n // Later sources fill gaps left by earlier ones; the backend's tree wins\n // because it holds the server and driver the runtime itself needs.\n const sources = [\"backend/node_modules\", \"config/node_modules\", \"node_modules\"]\n .map(relative => path.join(projectRoot, relative))\n .filter(dir => fs.existsSync(dir));\n\n if (sources.length === 0) return;\n\n let linked = 0;\n fs.mkdirSync(target, { recursive: true });\n\n const linkInto = (sourceDir: string, targetDir: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(sourceDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \".bin\" || entry.name.startsWith(\".\")) continue;\n const from = path.join(sourceDir, entry.name);\n const to = path.join(targetDir, entry.name);\n\n // A scope is a directory of packages, not a package — merge into it\n // so `@a/one` from one tree and `@a/two` from another both resolve.\n if (entry.name.startsWith(\"@\") && entry.isDirectory()) {\n fs.mkdirSync(to, { recursive: true });\n linkInto(from, to);\n continue;\n }\n\n if (fs.existsSync(to)) continue;\n try {\n fs.symlinkSync(fs.realpathSync(from), to, \"junction\");\n linked++;\n } catch {\n // A package that cannot be linked simply stays unresolved, and\n // the runtime will say so by name if it actually needed it.\n }\n }\n };\n\n for (const source of sources) linkInto(source, target);\n\n if (linked > 0) {\n console.log(chalk.dim(\n ` linked ${linked} package(s) into the bundle for this local run\\n` +\n \" (a deployment installs the bundle's package.json instead)\\n\"\n ));\n }\n}\n\nasync function startWorkspaceBackend(projectRoot: string, env: Record<string, string>): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase auth <action>\n *\n * Subcommands:\n * reset-password — Reset a user's password\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { spawn } from \"child_process\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n findEnvFile,\n resolveTsx\n} from \"../utils/project\";\n\nexport async function authCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printAuthHelp();\n return;\n }\n\n switch (subcommand) {\n case \"reset-password\":\n await resetPassword(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown auth command: ${subcommand}`));\n console.log(\"\");\n printAuthHelp();\n process.exit(1);\n }\n}\n\nasync function resetPassword(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--email\": String,\n \"--password\": String,\n \"-e\": \"--email\",\n \"-p\": \"--password\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase auth reset-password\"\n permissive: true\n }\n );\n\n // Support both --email flag and positional args\n const email = args[\"--email\"] || args._[0];\n const newPassword = args[\"--password\"] || args._[1];\n\n if (!email) {\n console.error(chalk.red(\"✗ Email is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase auth reset-password <email> [new-password]\"));\n console.log(chalk.gray(\" rebase auth reset-password --email user@example.com --password NewPass123!\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n\n // 1. Try API-first reset\n let envServiceKey: string | undefined;\n const envFile = findEnvFile(projectRoot);\n if (envFile && fs.existsSync(envFile)) {\n try {\n const envContent = fs.readFileSync(envFile, \"utf8\");\n const match = envContent.match(/^\\s*REBASE_SERVICE_KEY\\s*=\\s*['\"]?(.*?)['\"]?\\s*$/m);\n if (match && match[1]) {\n envServiceKey = match[1];\n }\n } catch {\n // Ignore\n }\n }\n\n let baseUrl = process.env.REBASE_BASE_URL;\n let serviceKey = process.env.REBASE_SERVICE_KEY || envServiceKey;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as Record<string, unknown>;\n if (state && typeof state === \"object\") {\n if (typeof state.baseUrl === \"string\" && !baseUrl) {\n baseUrl = state.baseUrl;\n }\n if (typeof state.serviceKey === \"string\" && !serviceKey) {\n serviceKey = state.serviceKey;\n }\n }\n } catch {\n // Ignore\n }\n }\n\n const devUrlPath = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(devUrlPath) && !baseUrl) {\n try {\n baseUrl = fs.readFileSync(devUrlPath, \"utf8\").trim();\n } catch {\n // Ignore\n }\n }\n\n if (baseUrl && serviceKey) {\n console.log(\"Trying API-first reset via running backend...\");\n try {\n const finalPass = newPassword || \"NewPassword123!\";\n const cleanBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n const searchUrl = `${cleanBaseUrl}/api/admin/users?search=${encodeURIComponent(email)}&limit=1`;\n const searchRes = await fetch(searchUrl, {\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\"\n }\n });\n if (!searchRes.ok) {\n throw new Error(`Failed to list users: ${searchRes.statusText}`);\n }\n const searchData = await searchRes.json() as unknown;\n if (!searchData || typeof searchData !== \"object\") {\n throw new Error(\"Invalid response format from user search API.\");\n }\n \n let userId: string | undefined;\n if (Array.isArray(searchData)) {\n const firstUser = searchData[0] as unknown;\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n } else if (\"users\" in searchData && Array.isArray((searchData as { users: unknown }).users)) {\n const users = (searchData as { users: unknown[] }).users;\n const firstUser = users[0];\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n }\n\n if (!userId) {\n throw new Error(`User not found with email: ${email}`);\n }\n\n const resetUrl = `${cleanBaseUrl}/api/admin/users/${userId}/reset-password`;\n const resetRes = await fetch(resetUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({ password: finalPass })\n });\n\n if (!resetRes.ok) {\n const errText = await resetRes.text();\n throw new Error(`Password reset endpoint failed: ${errText || resetRes.statusText}`);\n }\n\n console.log(\"API reset successful.\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (via API)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n console.log(` ${chalk.gray(\"Password:\")} ${finalPass}`);\n console.log(\"\");\n return;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.warn(chalk.yellow(\"API reset failed, falling back to direct database update...\"));\n console.warn(chalk.gray(` Details: ${errMsg}`));\n }\n }\n\n // 2. Direct-DB Fallback\n const backendDir = requireBackendDir(projectRoot);\n const tsxBin = resolveTsx(projectRoot);\n\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n\n try {\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env.REBASE_RESET_EMAIL = email;\n env.REBASE_RESET_PASSWORD = newPassword || \"NewPassword123!\";\n env.REBASE_ENV_FILE_PATH = envFile || path.join(projectRoot, \".env\");\n\n const scriptContent = `\nimport { createPostgresDatabaseConnection } from \"@rebasepro/server-postgres\";\nimport { hashPassword } from \"@rebasepro/server\";\nimport { eq } from \"drizzle-orm\";\nimport * as dotenv from \"dotenv\";\nimport path from \"path\";\nimport fs from \"fs\";\n\ndotenv.config({ path: process.env.REBASE_ENV_FILE_PATH });\n\nconst email = process.env.REBASE_RESET_EMAIL!;\nconst newPassword = process.env.REBASE_RESET_PASSWORD!;\n\nasync function resetPassword() {\n const { db } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);\n const hash = await hashPassword(newPassword);\n\n let usersTable;\n try {\n const schemaPath = path.resolve(\"./src/schema.generated.ts\");\n if (fs.existsSync(schemaPath)) {\n const schema = await import(\"file://\" + schemaPath);\n usersTable = schema.users || schema.tables?.users;\n }\n } catch (e) {\n // ignore and fallback\n }\n\n if (!usersTable) {\n const pgServer = await import(\"@rebasepro/server-postgres\");\n usersTable = pgServer.users;\n }\n\n const passwordHashKey = (usersTable.passwordHash || \"passwordHash\" in usersTable) ? \"passwordHash\" : \"password_hash\";\n\n const result = await db.update(usersTable)\n .set({ [passwordHashKey]: hash })\n .where(eq(usersTable.email, email))\n .returning({\n id: usersTable.id,\n email: usersTable.email\n });\n\n if (result.length > 0) {\n console.log(\"✅ Password reset for: \" + result[0].email);\n ${!newPassword ? 'console.log(\" New password: \" + newPassword);' : \"\"}\n } else {\n console.log(\"✗ User not found: \" + email);\n }\n process.exit(0);\n}\n\nresetPassword().catch(console.error);\n`;\n\n const tmpScriptPath = path.join(backendDir, \".tmp-reset-password.ts\");\n fs.writeFileSync(tmpScriptPath, scriptContent, \"utf-8\");\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (Direct DB Fallback)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n if (newPassword) {\n console.log(` ${chalk.gray(\"Password:\")} ${\"*\".repeat(newPassword.length)}`);\n }\n console.log(\"\");\n\n const child = spawn(tsxBin, [tmpScriptPath], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n\n return new Promise((resolve) => {\n child.on(\"close\", (code) => {\n // Clean up temp script\n try { fs.unlinkSync(tmpScriptPath); } catch { /* ignore */ }\n if (code !== 0) {\n process.exit(code ?? 1);\n }\n resolve();\n });\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction printAuthHelp() {\n console.log(`\n${chalk.bold(\"rebase auth\")} — Authentication management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase auth ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"reset-password\")} Reset a user's password\n\n${chalk.green.bold(\"reset-password Options\")}\n ${chalk.blue(\"--email, -e\")} User's email address\n ${chalk.blue(\"--password, -p\")} New password (default: NewPassword123!)\n\n${chalk.green.bold(\"Examples\")}\n rebase auth reset-password user@example.com\n rebase auth reset-password --email user@example.com --password MyNewPass!\n`);\n}\n","/**\n * CLI command: rebase doctor\n *\n * Detects three-way schema drift between collection definitions,\n * the generated Drizzle schema, and the live PostgreSQL database.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function doctorCommand(rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport inquirer from \"inquirer\";\nimport { createRequire } from \"module\";\n\nconst require = createRequire(import.meta.url);\n\n/** Supported agent environments and their target directories. */\nconst AGENTS = {\n cursor: {\n label: \"Cursor\",\n detectDir: \".cursor\",\n targetDir: \".cursor/rules\",\n /** Cursor uses .mdc files (Markdown with Context). */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.mdc`,\n content\n })\n },\n claude: {\n label: \"Claude Code\",\n detectDir: \".claude\",\n targetDir: \".claude/skills\",\n /** Claude Code uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n },\n windsurf: {\n label: \"Windsurf\",\n detectDir: \".windsurf\",\n targetDir: \".windsurf/rules\",\n /** Windsurf uses plain .md files. */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.md`,\n content\n })\n },\n gemini: {\n label: \"Gemini CLI / Antigravity\",\n detectDir: \".agents\",\n targetDir: \".agents/skills\",\n /** Gemini uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n }\n} as const;\n\ntype AgentKey = keyof typeof AGENTS;\n\n/**\n * Resolve the path to the skills directory from @rebasepro/agent-skills.\n * Works in both workspace (symlink) and published (real files) layouts.\n */\nfunction getSkillsSourceDir(): string {\n const pkgJsonPath = require.resolve(\"@rebasepro/agent-skills/package.json\");\n const pkgRoot = path.dirname(pkgJsonPath);\n const skillsDir = path.join(pkgRoot, \"skills\");\n\n if (!fs.existsSync(skillsDir)) {\n throw new Error(\n `Skills directory not found at ${skillsDir}. ` +\n `Make sure @rebasepro/agent-skills is installed.`\n );\n }\n\n return skillsDir;\n}\n\n/** Read all skill directories and return their names + content. */\nfunction loadSkills(skillsDir: string): Array<{ name: string; content: string }> {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n const skills: Array<{ name: string; content: string }> = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillMdPath = path.join(skillsDir, entry.name, \"SKILL.md\");\n if (!fs.existsSync(skillMdPath)) continue;\n skills.push({\n name: entry.name,\n content: fs.readFileSync(skillMdPath, \"utf-8\")\n });\n }\n\n return skills;\n}\n\n/** Detect which agent environments already exist in the project. */\nfunction detectAgents(projectDir: string): AgentKey[] {\n const detected: AgentKey[] = [];\n for (const [key, agent] of Object.entries(AGENTS)) {\n if (fs.existsSync(path.join(projectDir, agent.detectDir))) {\n detected.push(key as AgentKey);\n }\n }\n return detected;\n}\n\n/** Install skills for a specific agent into the project directory. */\nfunction installForAgent(\n agentKey: AgentKey,\n skills: Array<{ name: string; content: string }>,\n projectDir: string\n): number {\n const agent = AGENTS[agentKey];\n const targetBase = path.join(projectDir, agent.targetDir);\n\n // Ensure the target directory exists\n fs.mkdirSync(targetBase, { recursive: true });\n\n let count = 0;\n for (const skill of skills) {\n const { fileName, content } = agent.transformFile(skill.name, skill.content);\n const targetPath = path.join(targetBase, fileName);\n\n // Ensure parent directory exists (for subdirectory-based formats)\n fs.mkdirSync(path.dirname(targetPath), { recursive: true });\n fs.writeFileSync(targetPath, content, \"utf-8\");\n count++;\n }\n\n return count;\n}\n\nexport async function skillsCommand(subcommand: string | undefined, rawArgs: string[]) {\n switch (subcommand) {\n case \"install\":\n await skillsInstall(rawArgs);\n break;\n case \"--help\":\n case undefined:\n printSkillsHelp();\n break;\n default:\n console.error(chalk.red(`Unknown skills subcommand: ${subcommand}`));\n console.log(\"\");\n printSkillsHelp();\n process.exit(1);\n }\n}\n\n/**\n * Agents named explicitly on the command line, e.g. `--agent claude --agent cursor`\n * (also accepts a comma-separated list). Returns null when none were given.\n */\nfunction parseAgentFlags(rawArgs: string[]): AgentKey[] | null {\n const requested: string[] = [];\n for (let i = 0; i < rawArgs.length; i++) {\n if (rawArgs[i] !== \"--agent\" && rawArgs[i] !== \"-a\") continue;\n const value = rawArgs[i + 1];\n if (value && !value.startsWith(\"-\")) {\n requested.push(...value.split(\",\").map(v => v.trim()).filter(Boolean));\n }\n }\n if (requested.length === 0) return null;\n\n const valid = Object.keys(AGENTS);\n const unknown = requested.filter(a => !valid.includes(a));\n if (unknown.length > 0) {\n console.error(chalk.red(`Unknown agent(s): ${unknown.join(\", \")}. Available: ${valid.join(\", \")}`));\n process.exit(1);\n }\n return requested as AgentKey[];\n}\n\nasync function skillsInstall(rawArgs: string[] = []) {\n const projectDir = process.cwd();\n\n // 1. Load skills from @rebasepro/agent-skills\n let skillsDir: string;\n try {\n skillsDir = getSkillsSourceDir();\n } catch (err) {\n console.error(`${chalk.red.bold(\"ERROR\")} ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n const skills = loadSkills(skillsDir);\n if (skills.length === 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} No skills found in ${skillsDir}`);\n process.exit(1);\n }\n\n // 2. Explicit --agent wins; otherwise detect existing agent environments\n let agents = parseAgentFlags(rawArgs) ?? detectAgents(projectDir);\n\n // 3. If none detected, ask the user\n if (agents.length === 0) {\n // A scaffolded project ships `.cursorrules` / `CLAUDE.md` files but none\n // of the *directories* detectAgents looks for, so a fresh project always\n // lands here. On a non-TTY that used to abort with a raw ExitPromptError.\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"Cannot prompt: this is a non-interactive terminal (no TTY).\"));\n console.error(chalk.yellow(` Name the agents explicitly, e.g. rebase skills install --agent ${Object.keys(AGENTS)[0]}`));\n console.error(chalk.gray(` Available: ${Object.keys(AGENTS).join(\", \")}`));\n process.exit(1);\n }\n\n const choices = Object.entries(AGENTS).map(([key, agent]) => ({\n name: agent.label,\n value: key,\n checked: false\n }));\n\n const { selectedAgents } = await inquirer.prompt([{\n type: \"checkbox\",\n name: \"selectedAgents\",\n message: \"No AI agent configuration detected. Which agents do you use?\",\n choices,\n validate: (input: string[]) => {\n if (input.length === 0) return \"Please select at least one agent.\";\n return true;\n }\n }]);\n\n agents = selectedAgents as AgentKey[];\n }\n\n // 4. Install skills for each agent\n console.log(\"\");\n console.log(chalk.gray(` Found ${chalk.white(skills.length)} Rebase skills`));\n console.log(\"\");\n\n for (const agentKey of agents) {\n const agent = AGENTS[agentKey];\n const count = installForAgent(agentKey, skills, projectDir);\n console.log(` ${chalk.green(\"✓\")} ${chalk.bold(agent.label)} — ${count} skills installed to ${chalk.gray(agent.targetDir)}`);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Skills are project-local. Commit them to share with your team.\"));\n console.log(chalk.gray(\" Re-run this command anytime to update to the latest skills.\"));\n console.log(\"\");\n}\n\nfunction printSkillsHelp() {\n console.log(`\n${chalk.bold(\"rebase skills\")} — Manage AI agent skills\n\n${chalk.green.bold(\"Usage\")}\n rebase skills ${chalk.blue(\"<subcommand>\")}\n\n${chalk.green.bold(\"Subcommands\")}\n ${chalk.blue.bold(\"install\")} Install Rebase agent skills for your AI coding assistant\n Supports: Cursor, Claude Code, Windsurf, Gemini CLI, Antigravity\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--agent, -a\")} Agent(s) to install for, skipping detection and the prompt.\n Repeat the flag or pass a comma-separated list.\n Available: ${Object.keys(AGENTS).join(\", \")}\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.cyan(\"rebase skills install\")}\n ${chalk.cyan(\"rebase skills install --agent claude\")}\n ${chalk.cyan(\"rebase skills install --agent claude,cursor\")}\n`);\n}\n","/**\n * CLI command: rebase api-keys <action>\n *\n * Subcommands:\n * list — List all API keys (masked)\n * create — Create a new API key\n * revoke — Revoke an existing API key\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireProjectRoot,\n findEnvFile\n} from \"../utils/project\";\nimport fs from \"fs\";\nimport path from \"path\";\n\n/* ═══════════════════════════════════════════════════════════════\n Env helper — reads SERVICE_KEY and PORT from .env\n ═══════════════════════════════════════════════════════════════ */\n\nfunction loadEnv(projectRoot: string): Record<string, string> {\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = {};\n if (envFile && fs.existsSync(envFile)) {\n const content = fs.readFileSync(envFile, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const idx = trimmed.indexOf(\"=\");\n if (idx > 0) {\n const key = trimmed.slice(0, idx).trim();\n let value = trimmed.slice(idx + 1).trim();\n // Strip surrounding quotes\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n env[key] = value;\n }\n }\n }\n return env;\n}\n\nfunction resolveBaseUrl(env: Record<string, string>, projectRoot?: string): string {\n // An explicit override always wins.\n if (env.REBASE_BASE_URL) return env.REBASE_BASE_URL;\n\n // `rebase dev` runs on a derived per-project port, not the .env PORT, and\n // records the URL it actually bound. Without this, these commands default to\n // :3001 and report \"Is the Rebase server running?\" while it is running.\n if (projectRoot) {\n try {\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(urlFile)) {\n const devUrl = fs.readFileSync(urlFile, \"utf-8\").trim();\n if (devUrl) return devUrl;\n }\n } catch { /* fall through to the configured port */ }\n }\n\n const port = env.PORT || env.REBASE_PORT || \"3001\";\n return `http://localhost:${port}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Entry\n ═══════════════════════════════════════════════════════════════ */\n\nexport async function apiKeysCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printApiKeysHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listKeys(rawArgs);\n break;\n case \"create\":\n await createKey(rawArgs);\n break;\n case \"revoke\":\n await revokeKey(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown api-keys command: ${subcommand}`));\n console.log(\"\");\n printApiKeysHelp();\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list\n ═══════════════════════════════════════════════════════════════ */\n\nasync function listKeys(_rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n if (!res.ok) {\n const body = await res.text();\n console.error(chalk.red(`✗ Failed to list API keys: ${res.status} ${body}`));\n process.exit(1);\n }\n\n const { keys } = await res.json() as { keys: Array<{\n id: string; name: string; key_prefix: string;\n permissions: Array<{ collection: string; operations: string[] }>;\n rate_limit: number | null; revoked_at: string | null;\n expires_at: string | null; last_used_at: string | null;\n created_at: string;\n }>};\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 API Keys\"));\n console.log(\"\");\n\n if (keys.length === 0) {\n console.log(chalk.gray(\" No API keys found.\"));\n console.log(\"\");\n return;\n }\n\n for (const key of keys) {\n const status = key.revoked_at ? chalk.red(\"revoked\")\n : (key.expires_at && new Date(key.expires_at) < new Date()) ? chalk.yellow(\"expired\")\n : chalk.green(\"active\");\n\n const perms = key.permissions.map(p =>\n `${p.collection}(${p.operations.join(\",\")})`\n ).join(\", \");\n\n console.log(` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${status}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Permissions:\")} ${perms || \"none\"}`);\n console.log(` ${chalk.gray(\"Created:\")} ${new Date(key.created_at).toLocaleDateString()}`);\n if (key.last_used_at) {\n console.log(` ${chalk.gray(\"Last used:\")} ${new Date(key.last_used_at).toLocaleDateString()}`);\n }\n console.log(\"\");\n }\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n create\n ═══════════════════════════════════════════════════════════════ */\n\nasync function createKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--permissions\": String,\n \"--full-access\": Boolean,\n \"--admin\": Boolean,\n \"--rate-limit\": Number,\n \"--expires\": String,\n \"-n\": \"--name\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys create\"\n permissive: true\n }\n );\n\n const name = args[\"--name\"] || args._[0];\n const permissionsRaw = args[\"--permissions\"];\n\n if (!name) {\n console.error(chalk.red(\"✗ Name is required.\"));\n console.log(\"\");\n console.log(chalk.gray(' Usage: rebase api-keys create --name \"My Key\" --permissions \\'[{\"collection\":\"*\",\"operations\":[\"read\"]}]\\''));\n process.exit(1);\n }\n\n let permissions: Array<{ collection: string; operations: string[] }>;\n if (permissionsRaw) {\n try {\n permissions = JSON.parse(permissionsRaw);\n } catch {\n console.error(chalk.red(\"✗ Invalid --permissions JSON.\"));\n console.log(chalk.gray(' Example: \\'[{\"collection\":\"*\",\"operations\":[\"read\",\"write\"]}]\\''));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n } else if (args[\"--full-access\"]) {\n permissions = [{ collection: \"*\", operations: [\"read\", \"write\", \"delete\"] }];\n } else {\n // No silent full-access default: a \"scoped keys\" feature should not\n // hand out read/write/delete on every collection when the flag is\n // simply forgotten. Full access must be asked for by name.\n console.error(chalk.red(\"✗ Specify what the key may access: --permissions '<json>' or --full-access.\"));\n console.log(\"\");\n console.log(chalk.gray(' Scoped: rebase api-keys create -n \"Analytics\" --permissions \\'[{\"collection\":\"events\",\"operations\":[\"read\"]}]\\''));\n console.log(chalk.gray(' Functions: add {\"collection\":\"functions/<name>\",\"operations\":[\"write\"]} to invoke a custom function'));\n console.log(chalk.gray(' Storage: add {\"collection\":\"storage\",\"operations\":[\"read\",\"write\"]} for file storage'));\n console.log(chalk.gray(' Full access: rebase api-keys create -n \"CI\" --full-access'));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n\n let expires_at: string | null = null;\n const expiresFlag = args[\"--expires\"];\n if (expiresFlag) {\n const days: Record<string, number> = { \"7d\": 7, \"30d\": 30, \"90d\": 90, \"1y\": 365 };\n if (days[expiresFlag]) {\n expires_at = new Date(Date.now() + days[expiresFlag] * 86400000).toISOString();\n } else {\n const parsed = new Date(expiresFlag);\n if (isNaN(parsed.getTime())) {\n console.error(chalk.red(\"✗ Invalid --expires value. Use 7d, 30d, 90d, 1y, or an ISO date.\"));\n process.exit(1);\n }\n expires_at = parsed.toISOString();\n }\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const body: Record<string, unknown> = {\n name,\n permissions,\n admin: args[\"--admin\"] ?? false,\n rate_limit: args[\"--rate-limit\"] ?? null,\n expires_at\n };\n\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to create API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n const { key } = await res.json() as { key: { name: string; key: string; key_prefix: string; id: string } };\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key created successfully\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Name:\")} ${key.name}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Prefix:\")} ${key.key_prefix}`);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy your key now — it won't be shown again:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(key.key)}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n revoke\n ═══════════════════════════════════════════════════════════════ */\n\nasync function revokeKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--id\": String\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys revoke\"\n permissive: true\n }\n );\n\n const id = args[\"--id\"] || args._[0];\n\n if (!id) {\n console.error(chalk.red(\"✗ Key ID is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase api-keys revoke <key-id>\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys/${encodeURIComponent(id)}`, {\n method: \"DELETE\",\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to revoke API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key revoked successfully\"));\n console.log(` ${chalk.gray(\"ID:\")} ${id}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nfunction printApiKeysHelp() {\n console.log(`\n${chalk.bold(\"rebase api-keys\")} — Manage Service API Keys\n\n${chalk.green.bold(\"Usage\")}\n rebase api-keys ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List all API keys\n ${chalk.blue.bold(\"create\")} Create a new API key\n ${chalk.blue.bold(\"revoke\")} Revoke an API key\n\n${chalk.green.bold(\"create Options\")}\n ${chalk.blue(\"--name, -n\")} Key name ${chalk.gray(\"(required)\")}\n ${chalk.blue(\"--permissions\")} JSON array of permissions ${chalk.gray(\"(required unless --full-access)\")}\n ${chalk.gray('Collections by slug; custom functions as \"functions\" or \"functions/<name>\"')}\n ${chalk.blue(\"--full-access\")} Grant read/write/delete on every collection and function\n ${chalk.blue(\"--admin\")} Grant admin role (admin routes + RLS admin policies)\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window ${chalk.gray(\"(default: 1000)\")}\n ${chalk.blue(\"--expires\")} Expiration: 7d, 30d, 90d, 1y, or ISO date\n\n${chalk.green.bold(\"revoke Options\")}\n ${chalk.blue(\"--id\")} API key ID to revoke ${chalk.gray(\"(or positional arg)\")}\n\n${chalk.green.bold(\"Examples\")}\n rebase api-keys list\n rebase api-keys create --name \"Analytics\" --permissions '[{\"collection\":\"events\",\"operations\":[\"read\"]}]'\n rebase api-keys create -n \"Full Access\" --full-access --expires 90d\n rebase api-keys revoke abc123-def456\n`);\n}\n","/**\n * `rebase cloud` auth subcommands: login, logout, whoami.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n resolveCloudUrl,\n createCloudClient,\n requireClient,\n setCurrentContext,\n setContextOrg,\n getContextOrg,\n readLink,\n success,\n fail,\n keyValues,\n reportError\n} from \"./context\";\n\nexport async function loginCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--email\": String,\n\"--password\": String,\n\"-e\": \"--email\",\n\"-p\": \"--password\" },\n { argv: rawArgs.slice(3),\npermissive: true }\n );\n const url = resolveCloudUrl(rawArgs);\n\n console.log(\"\");\n console.log(` Signing in to ${chalk.cyan(url)}`);\n console.log(\"\");\n\n // Collect any missing credentials interactively.\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--email\"]) {\n prompts.push({ type: \"input\",\nname: \"email\",\nmessage: \"Email:\" });\n }\n if (!args[\"--password\"]) {\n prompts.push({ type: \"password\",\nname: \"password\",\nmessage: \"Password:\",\nmask: \"•\" });\n }\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const email = (args[\"--email\"] || (answers as { email?: string }).email || \"\").trim();\n const password = args[\"--password\"] || (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 keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"Active org\", getContextOrg(url)]\n ]);\n console.log(\"\");\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.\");\n }\n reportError(e, \"Login failed\");\n }\n}\n\nexport async function logoutCommand(rawArgs: string[]): Promise<void> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n if (!client.auth.getSession()) {\n console.log(\"\");\n console.log(chalk.gray(` Not logged in to ${url}.`));\n console.log(\"\");\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}\n\nexport async function whoamiCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const user = await client.auth.getUser();\n if (!user) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const link = readLink();\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 [\"Linked project\", link ? `${link.projectName ?? \"\"} (${link.projectId})`.trim() : undefined]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch session\");\n }\n}\n","/**\n * `rebase cloud` context subcommands: link, unlink, use, open.\n *\n * `link` associates the current directory with a cloud project by writing\n * `.rebase/cloud.json`; deploy/logs/status then operate on it with no flags.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n resolveCloudUrl,\n writeLink,\n removeLink,\n readLink,\n projectLinkPath,\n setContextOrg,\n getContextOrg,\n openUrl,\n success,\n fail,\n reportError\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.`);\n return;\n }\n\n if (base.protocol !== \"http:\" && base.protocol !== \"https:\") {\n fail(\"A project URL must be http or https.\");\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 console.log(chalk.yellow(`⚠ Could not reach ${probe}${detail ? ` (${detail})` : \"\"}.`));\n console.log(chalk.dim(\" Linking anyway — the server may not be running yet.\"));\n console.log(chalk.dim(\" It must be a Rebase backend of version 0.11 or newer.\"));\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 console.log(chalk.dim(` Written to ${projectLinkPath()}`));\n console.log(\"\");\n console.log(`Next: ${chalk.cyan(\"rebase generate-sdk --from link\")}`);\n void rawArgs;\n}\n\nexport async function linkCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(3),\npermissive: true });\n\n // A positional URL means \"this exact backend\", which needs no login and no\n // control plane. `rebase link https://api.example.com`\n const positional = args._.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 unknown as ProjectRow | undefined;\n if (!project) fail(`Project ${args[\"--project\"]} not found.`);\n } else {\n const org = getContextOrg(url);\n const projects = (await client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n limit: 100\n })).data as unknown as ProjectRow[];\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 );\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 unknown as Parameters<typeof inquirer.prompt>[0]);\n project = picked as ProjectRow;\n }\n\n if (!project) fail(\"No project selected.\");\n\n writeLink({\n url,\n projectId: String(project.id),\n slug: project.subdomain,\n projectName: project.name,\n orgId: project.organization !== undefined ? String(project.organization) : undefined\n });\n\n success(`Linked to ${chalk.bold(project.name ?? project.subdomain ?? \"\")}`);\n console.log(chalk.gray(` Wrote ${projectLinkPath()}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to link project\");\n }\n}\n\nexport function unlinkCommand(): void {\n const link = readLink();\n if (!link) {\n console.log(\"\");\n console.log(chalk.gray(\" This directory is not linked to a cloud project.\"));\n console.log(\"\");\n return;\n }\n removeLink();\n success(\"Unlinked from cloud project\");\n}\n\nexport async function selectOrgCommand(rawArgs: string[]): Promise<void> {\n // positionals after \"cloud\" are [use, <org>]; take the token after \"use\".\n const target = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\n const { client, url } = await requireClient(rawArgs);\n\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n slug?: string;\n }>;\n\n if (orgs.length === 0) fail(\"You are not a member of any organization.\");\n\n let chosen = target\n ? orgs.find((o) => String(o.id) === target || o.slug === target)\n : undefined;\n\n if (!chosen && !target) {\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 unknown as Parameters<typeof inquirer.prompt>[0]);\n chosen = picked;\n }\n\n if (!chosen) fail(`Organization \"${target}\" not found.`);\n\n setContextOrg(url, String(chosen.id));\n success(`Active organization set to ${chalk.bold(chosen.name ?? chosen.id)}`);\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 const url = resolveCloudUrl(rawArgs);\n const link = readLink();\n const target = link ? `${url}/projects/${link.projectId}` : url;\n openUrl(target);\n}\n","/**\n * `rebase cloud projects` — list / create / info / delete.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n getContextOrg,\n readLink,\n writeLink,\n colorStatus,\n keyValues,\n fetchTenantBaseDomain,\n projectHost,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\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 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) => res.data as unknown as ProjectRow[]),\n fetchTenantBaseDomain(client, url)\n ]);\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(chalk.gray(\" No projects yet. Create one with `rebase cloud projects create`.\"));\n console.log(\"\");\n return;\n }\n\n const linkedId = readLink()?.projectId;\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 } catch (e) {\n reportError(e, \"Failed to list projects\");\n }\n}\n\n/* ─── create ───────────────────────────────────────────────────── */\n\n/** Default region + VM size per provider (both are required on create). */\nfunction providerDefaults(provider: string): { region: string; vmSize: string } {\n switch (provider) {\n case \"gcp\":\n return { region: \"europe-west1\",\nvmSize: \"e2-small\" };\n case \"aws\":\n return { region: \"us-east-1\",\nvmSize: \"t3.small\" };\n default:\n return { region: \"nbg1\",\nvmSize: \"cx21\" };\n }\n}\n\nexport async function createProject(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--provider\": String,\n \"--region\": String,\n \"--vm-size\": String,\n \"--org\": String,\n \"--link\": Boolean,\n \"-n\": \"--name\"\n },\n { argv: rawArgs.slice(4),\npermissive: true }\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 );\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<Record<string, unknown>> = [];\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 as unknown as Parameters<typeof inquirer.prompt>[0])\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 provider = (args[\"--provider\"] || a.provider || \"hetzner\").trim();\n // region + vmSize are required by the control plane; default sensibly per\n // provider so a headless `projects create` needs only name + subdomain.\n const defaults = providerDefaults(provider);\n const region = (args[\"--region\"] || defaults.region).trim();\n const vmSize = (args[\"--vm-size\"] || defaults.vmSize).trim();\n\n if (!name || !subdomain) {\n fail(\"Name and subdomain are required.\");\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 );\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) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const created = (await client.data.collection(\"projects\").create({\n name,\n subdomain,\n gitRepoUrl,\n gitBranch,\n provider,\n region,\n vmSize,\n organization: org,\n createdById: user.uid,\n status: \"provisioning\"\n })) as unknown as ProjectRow;\n\n success(`Created project ${chalk.bold(name)}`);\n keyValues([\n [\"Slug\", String(created.subdomain ?? \"\")],\n [\"URL\", projectHost(created, await fetchTenantBaseDomain(client, url))],\n [\"Provider\", provider],\n [\"Branch\", gitBranch]\n ]);\n\n if (args[\"--link\"]) {\n writeLink({ url,\nprojectId: String(created.id),\nslug: created.subdomain,\nprojectName: name,\norgId: String(org) });\n console.log(chalk.gray(\" Linked this directory to the new project.\"));\n }\n console.log(\"\");\n console.log(chalk.gray(` Deploy it with: ${chalk.bold(`rebase cloud deploy --project ${created.subdomain ?? created.id}`)}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to create project\");\n }\n}\n\n/* ─── info ─────────────────────────────────────────────────────── */\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 unknown as ProjectRow | undefined;\n if (!p) fail(`Project ${projectRef} not found.`);\n\n const [db, lastDeploy, baseDomain] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url)\n ]);\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 [\"Last deploy\", lastDeploy ? `${colorStatus(lastDeploy.status)} · ${fmtDate(lastDeploy.createdAt)}` : \"never\"]\n ]);\n console.log(\"\");\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 args = arg({ \"--yes\": Boolean,\n\"-y\": \"--yes\" }, { argv: rawArgs.slice(2),\npermissive: true });\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.`);\n\n if (!args[\"--yes\"]) {\n const { confirmed } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirmed\",\n default: false,\n message: `Permanently delete project \"${p.name ?? projectRef}\" (${p.subdomain ?? projectRef})? This tears down its deployment.`\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n return;\n }\n }\n\n try {\n await client.data.collection(\"projects\").delete(projectId);\n success(`Deleted project ${chalk.bold(p.name ?? projectId)}`);\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 } from \"child_process\";\nimport type { RebaseBundleManifest } from \"@rebasepro/types\";\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 * Tar a built bundle into a gzipped archive.\n *\n * `node_modules` is excluded on purpose: the bundle ships a `package.json`, and\n * the managed runtime installs the declared dependencies at boot. Uploading an\n * installed `node_modules` would bloat the archive and could carry a\n * platform-specific build that will not run on the runtime image.\n */\nexport function packBundle(bundleDir: string, outPath: string): 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\", \"--exclude\", \"node_modules\", \"-C\", bundleDir, \".\"],\n { stdio: \"inherit\", env: { ...process.env, COPYFILE_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 * 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 */\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}): 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 };\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}`, \"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 * `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 { spawn } from \"child_process\";\nimport {\n requireClient,\n resolveProjectRef,\n colorStatus,\n emit,\n isJsonMode,\n printJson,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\nimport { latestDeployment, fmtDate } from \"./projects\";\nimport { readBundleManifest, packBundle, uploadBundle, bundleDeployBody, declaredAppsFrom } from \"./bundle-deploy\";\nimport { buildBundle } from \"../../bundle\";\nimport { foldFrontendIntoBundle } from \"../../fold-static\";\nimport { loadManifest, findBackendApp } from \"../../manifest\";\nimport { findProjectRoot, requireProjectRoot } from \"../../utils/project\";\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 /** Whether the blocking deployment was triggered by THIS user. */\n mine?: boolean;\n}\n\nconst POLL_INTERVAL_MS = 1500;\nconst POLL_TIMEOUT_MS = 15 * 60 * 1000; // 15 min hard stop\n\n// Keep in sync with the control plane's build-context cap (deploy/upload\n// MAX_BYTES and the backend's maxBodySize). Checked before uploading so an\n// oversized context fails in milliseconds with a hint, not after the upload\n// with a bare 413.\nconst MAX_SOURCE_UPLOAD_BYTES = 100 * 1024 * 1024;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction run(cmd: string, cmdArgs: string[], cwd?: string, env?: NodeJS.ProcessEnv): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, cmdArgs, { cwd,\nenv: env ? { ...process.env, ...env } : undefined,\nstdio: [\"ignore\", \"ignore\", \"pipe\"] });\n let stderr = \"\";\n child.stderr.on(\"data\", (d) => (stderr += d.toString()));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => (code === 0 ? resolve() : reject(new Error(stderr || `${cmd} exited ${code}`))));\n });\n}\n\n/**\n * Package `sourceDir` into a gzipped tarball, honoring `.gitignore`/`.rebaseignore`\n * and always excluding `.git` and `node_modules`. Returns the temp archive path.\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 const tarArgs = [\"-czf\", tarPath, \"--exclude=.git\", \"--exclude=node_modules\"];\n for (const ignore of [\".gitignore\", \".rebaseignore\"]) {\n if (fs.existsSync(path.join(dir, ignore))) tarArgs.push(`--exclude-from=${ignore}`);\n }\n tarArgs.push(\".\");\n\n try {\n // COPYFILE_DISABLE: macOS bsdtar otherwise emits an AppleDouble sidecar\n // (`._foo.ts`) for every file carrying an xattr — and macOS stamps the\n // SIP-protected `com.apple.provenance` xattr routinely, so a stock\n // checkout ships `._*` binary junk that crashes schema generation in\n // the builder. GNU tar ignores the variable, so this is safe everywhere.\n await run(\"tar\", tarArgs, dir, { COPYFILE_DISABLE: \"1\" });\n } catch (e) {\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/** 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 console.log(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 without `node_modules`, uploads it, and triggers a\n * deploy carrying the manifest so the control plane 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 /** Compile without type checking, exactly as `rebase build` does. */\n skipTypeCheck?: boolean;\n}): Promise<void> {\n const { client, url, projectId, projectRef } = opts;\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 const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (!backend) {\n fail(\n \"This repository declares no backend app to deploy as a bundle.\",\n \"A managed deploy runs the backend; declare one in rebase.json, or deploy from the backend's repository.\"\n );\n }\n console.log(chalk.gray(\" Building bundle...\"));\n const result = await buildBundle({\n projectRoot,\n appName: backend!.name,\n app: backend!.app,\n runtimeRange: loaded.manifest.rebase,\n storage: loaded.manifest.storage,\n skipTypeCheck: opts.skipTypeCheck,\n log: (m: string) => console.log(chalk.gray(m))\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. */\n try {\n const folded = await foldFrontendIntoBundle({\n projectRoot,\n manifest: loaded.manifest as never,\n bundleDir,\n log: (m: string) => console.log(m)\n });\n for (const outcome of folded) {\n console.log(chalk.gray(\n ` folded ${outcome.appName} in (${outcome.fileCount} file(s), served at ${outcome.path})`\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 const manifest = readBundleManifest(bundleDir);\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 const token = client.auth.getSession()?.accessToken;\n if (!token) fail(\"Not authenticated.\", \"Run `rebase cloud login`.\");\n\n let bundleId: string;\n try {\n await packBundle(bundleDir, tarPath);\n const sizeMb = (fs.statSync(tarPath).size / 1024 / 1024).toFixed(1);\n console.log(chalk.gray(` Uploading bundle (${sizeMb} MB)...`));\n bundleId = await uploadBundle(url, token!, 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 console.log(\"\");\n console.log(` 🚀 Triggering managed deployment for ${chalk.bold(projectRef)} (schema ${manifest.schemaVersion})...`);\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 declaredApps: ReturnType<typeof declaredAppsFrom> = [];\n try {\n declaredApps = declaredAppsFrom(loadManifest(process.cwd()).manifest as never);\n } catch {\n // A project with no readable rebase.json still deploys; it just cannot\n // describe its other apps.\n }\n\n const body = bundleDeployBody({ projectId, bundleId, manifest, message: opts.message, declaredApps });\n\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string | number };\n managed?: boolean;\n }>(\"deploy\", body);\n if (!res?.deployment?.id) fail(\"Control plane did not return a deployment id.\");\n if (isJsonMode()) {\n printJson({ success: true, deploymentId: String(res.deployment.id), managed: res.managed === true });\n } else {\n console.log(chalk.green(` ✓ Managed deploy started (deployment ${res.deployment.id}).`));\n console.log(chalk.gray(\" Track it with `rebase cloud logs` or in the console.\"));\n }\n } catch (e) {\n reportError(e, \"Managed deploy failed to start\");\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 `--force`\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/** What a `deploy` with nothing attached will build, in the words to print. */\nexport function planBareDeploy(\n project: DeployProjectRow | undefined,\n latest: DeploySourceRow | undefined,\n now: Date\n): BareDeployPlan {\n const projectRow = project as Record<string, unknown> | undefined;\n const deploymentRow = latest as Record<string, unknown> | undefined;\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, source: \"git\", lines: [`Building from git: ${repo}${branch ? ` (${branch})` : \"\"}.`] };\n }\n\n if (pick(deploymentRow, \"sourceRef\", \"source_ref\")) {\n const age = timeAgo((latest?.createdAt ?? latest?.created_at) as string | Date | undefined, now);\n return {\n managed,\n source: \"snapshot\",\n lines: [\n `Rebuilding the stored source archive${latest?.id !== undefined ? ` from deployment ${latest.id}` : \"\"}` +\n `${age ? `, uploaded ${age}` : \"\"}.`,\n \"This directory is NOT uploaded — pass `--source .` to build what is on disk.\"\n ]\n };\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/** The one sentence that says a source build undoes `runtimeMode: managed`. */\nfunction ejectWarning(projectRef: string): string {\n return `⚠ ${projectRef} runs on the managed runtime — a source build ejects it to a custom container.`;\n}\n\n/**\n * Read the two rows the preflight needs.\n *\n * Best effort by construction: a preflight that cannot read is a preflight that\n * says nothing, never a deploy that fails. The managed refusal rides on the same\n * read, so an unreadable project falls through to the old behaviour rather than\n * blocking a deploy on a lookup.\n */\nasync function readDeployContext(\n client: CloudClient,\n projectId: string\n): Promise<{ project?: DeployProjectRow; latest?: DeploySourceRow }> {\n try {\n const [project, latest] = await Promise.all([\n client.data.collection(\"projects\").findById(projectId),\n latestDeployment(client, projectId)\n ]);\n return {\n project: project as unknown as DeployProjectRow | undefined,\n latest: latest as unknown as DeploySourceRow | undefined\n };\n } catch {\n return {};\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(): boolean {\n try {\n const projectRoot = findProjectRoot();\n if (!projectRoot) return false;\n const backend = findBackendApp(loadManifest(projectRoot).manifest);\n return backend?.app.runtime === \"managed\";\n } catch {\n return false;\n }\n}\n\nexport async function deployCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--no-follow\": Boolean,\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/* Deploy a source build even for a project that runs on the managed\n runtime — an eject, done deliberately. See the refusal below. */\n\"--force\": Boolean,\n\"-m\": \"--message\" },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\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 win.\n const declaredManaged = !args[\"--source\"] && !args[\"--bundle\"] && declaresManagedRuntime();\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 skipTypeCheck: args[\"--skip-type-check\"] === true\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, latest } = await readDeployContext(client, projectId);\n const plan = planBareDeploy(project, latest, new Date());\n\n if (!args[\"--source\"]) {\n if (plan.managed && args[\"--force\"] !== true) {\n fail(\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 \"Redeploy it with `rebase cloud deploy --bundle`. To eject on purpose, pass `--source .` \" +\n \"to build this directory, or `--force` to build what the control plane holds.\",\n \"managed_project\"\n );\n }\n if (!isJsonMode()) {\n console.log(\"\");\n if (plan.managed) console.log(chalk.yellow(` ${ejectWarning(projectRef)}`));\n for (const line of plan.lines) console.log(chalk.gray(` ${line}`));\n }\n } else if (plan.managed && !isJsonMode()) {\n // Explicit `--source` is a deliberate build, so it proceeds — but a\n // successful one rewrites `runtimeMode` to `custom` server-side, and\n // that is not something to discover from a runtime version going blank.\n console.log(\"\");\n console.log(chalk.yellow(` ${ejectWarning(projectRef)}`));\n console.log(chalk.gray(\" Use `rebase cloud deploy --bundle` to stay on managed.\"));\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 const token = client.auth.getSession()?.accessToken;\n if (!token) fail(\"Not authenticated.\", \"Run `rebase cloud login`.\");\n source = await uploadSource(url, token, projectId, tarPath);\n } finally {\n fs.rmSync(tarPath, { force: true });\n }\n }\n\n console.log(\"\");\n console.log(` 🚀 Triggering deployment for project ${chalk.bold(projectRef)}${source ? \" from uploaded source\" : \"\"}...`);\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 };\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string | number };\n deduplicated?: boolean;\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 };\n } catch (e) {\n triggered = resolveTriggerFailure(e);\n }\n const { deploymentId, deduplicated } = 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 },\n { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: false }\n );\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 const status = await streamBuildLogs(client, deploymentId, { quiet: isJsonMode() });\n emit(\n () => {},\n { deploymentId,\ndeduplicated,\nframeworkVersion: frameworkVersion ?? null,\nfollowing: true,\nstatus }\n );\n}\n\n/**\n * Turn a failed trigger into either a deployment to follow, or an exit.\n *\n * The 409 is the interesting one. A deploy trigger can reach the control plane\n * twice without anybody asking twice — the SDK transport replays a request once\n * after refreshing an expired token, and any lost response has the same effect\n * — so \"a deployment is already in progress\" was routinely describing the\n * deployment this very command had just created. With no id in the message the\n * only available reading was \"someone else is deploying, back off\", and the\n * build stream was lost either way.\n *\n * So: if the control plane says the blocking deployment is ours, we attach to\n * it. If it is not ours, we still name it, because \"which one, since when, from\n * where\" is the difference between an actionable refusal and a dead end.\n */\nfunction resolveTriggerFailure(e: unknown): { deploymentId: string; deduplicated: boolean } {\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 if (blocking?.id && blocking.mine) {\n return { deploymentId: String(blocking.id),\ndeduplicated: true };\n }\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` +\n `${blocking.triggerSource && blocking.triggerSource !== \"unknown\" ? `, triggered from the ${blocking.triggerSource}` : \"\"}` +\n `${blocking.createdAt ? ` at ${fmtDate(blocking.createdAt)}` : \"\"}.`\n : \"A deployment is already in progress for this project.\",\n blocking?.id\n ? `Follow it with \\`rebase cloud logs -f\\`, or stop it with \\`rebase cloud cancel ${blocking.id}\\`.`\n : \"Follow it with `rebase cloud logs -f`.\",\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 reportError(e, \"Failed to trigger deployment\");\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 */\nasync function streamBuildLogs(\n client: CloudClient,\n deploymentId: string,\n opts: { quiet?: boolean } = {}\n): Promise<string> {\n const quiet = opts.quiet === true;\n let printed = 0;\n const started = Date.now();\n\n for (;;) {\n let dep: Deployment | undefined;\n try {\n dep = (await client.data.collection(\"deployments\").findById(deploymentId)) as unknown as Deployment | undefined;\n } catch (e) {\n reportError(e, \"Failed to read deployment status\");\n }\n if (!dep) fail(`Deployment ${deploymentId} disappeared.`, undefined, \"not_found\");\n\n const logs = dep.logs ?? \"\";\n if (!quiet && logs.length > printed) {\n process.stdout.write(logs.slice(printed));\n }\n printed = logs.length;\n\n if (dep.status && dep.status !== \"deploying\") {\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\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 console.log(\"\");\n }\n return dep.status;\n }\n\n if (Date.now() - started > POLL_TIMEOUT_MS) {\n if (!quiet) console.log(\"\");\n fail(\n \"Timed out waiting for the build to finish.\",\n \"The deployment may still be running — check `rebase cloud logs`.\",\n \"timeout\"\n );\n }\n\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nexport async function logsCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--runtime\": Boolean,\n\"--follow\": Boolean,\n\"-f\": \"--follow\" },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client } = 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 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 } 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 try {\n const dep = (await latestDeployment(client, projectId)) as unknown as Deployment | undefined;\n if (!dep) {\n console.log(\"\");\n console.log(chalk.gray(\" No deployments yet for this project.\"));\n console.log(\"\");\n return;\n }\n\n console.log(\"\");\n console.log(chalk.bold(` 📄 Build logs — deployment ${dep.id}`) + ` ${colorStatus(dep.status)}`);\n console.log(\"\");\n\n if (args[\"--follow\"] && dep.status === \"deploying\") {\n // Hand off to the streamer, which prints from the top and tails live.\n await streamBuildLogs(client, String(dep.id));\n } else {\n console.log(dep.logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to fetch build logs\");\n }\n}\n","/**\n * `rebase cloud orgs` — list / create / members.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n getContextOrg,\n setContextOrg,\n colorStatus,\n success,\n fail,\n reportError\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}`);\n }\n}\n\nasync function listOrgs(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as OrgRow[];\n const active = getContextOrg(url);\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 console.log(chalk.gray(\" ● = active organization. Switch with `rebase cloud use <id>`.\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list organizations\");\n }\n}\n\nasync function createOrg(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--name\": String,\n\"--slug\": String,\n\"-n\": \"--name\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--name\"]) prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Organization name:\" });\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const name = (args[\"--name\"] || (answers as { name?: string }).name || \"\").trim();\n if (!name) fail(\"Organization name is required.\");\n const slug = (args[\"--slug\"] || slugify(name)).trim();\n\n try {\n const created = (await client.data.collection(\"organizations\").create({\n name,\n slug,\n createdAt: new Date().toISOString()\n })) as unknown as OrgRow;\n setContextOrg(url, String(created.id));\n success(`Created organization ${chalk.bold(name)} and set it active`);\n } catch (e) {\n reportError(e, \"Failed to create organization\");\n }\n}\n\nasync function listMembers(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n\n try {\n const members = (await client.data.collection(\"organization-members\").find({\n where: { organization: [\"==\", org] },\n limit: 200\n })).data as unknown as Array<{ id: string | number; userId?: string; role?: string }>;\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 } 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\nfunction printOrgsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud orgs\")} — Manage organizations\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List organizations you belong to\n ${chalk.blue.bold(\"create\")} Create a new organization ${chalk.gray(\"(--name, --slug)\")}\n ${chalk.blue.bold(\"members\")} List members of the active organization\n`);\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 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 displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface DatabaseRow {\n id: string | number;\n type?: string;\n connectionStatus?: string;\n useSshTunnel?: boolean;\n pitrEnabled?: boolean;\n}\n\ninterface BackupRow {\n filename: string;\n size?: number;\n createdAt?: string;\n type?: string;\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 \"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}`);\n }\n}\n\nasync function listDatabases(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const dbs = (await client.data.collection(\"databases\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data as unknown as DatabaseRow[];\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 } catch (e) {\n reportError(e, \"Failed to list databases\");\n }\n}\n\nasync function createDatabase(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--type\": String,\n\"--connection-string\": String,\n\"--project\": String,\n\"-p\": \"--project\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n let type = args[\"--type\"];\n if (!type) {\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 unknown 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 const { cs } = await inquirer.prompt([\n { type: \"input\",\nname: \"cs\",\nmessage: \"PostgreSQL connection string:\" }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n connectionString = (cs as string)?.trim();\n if (!connectionString) fail(\"A connection string is required for bring-your-own databases.\");\n }\n\n try {\n const created = (await client.data.collection(\"databases\").create({\n project: projectId,\n type,\n connectionString: type === \"byodb\" ? connectionString : undefined,\n connectionStatus: \"untested\"\n })) as unknown as DatabaseRow;\n success(`Attached ${type} database to project ${projectRef}`);\n keyValues([[\"ID\", String(created.id)]]);\n if (type === \"byodb\") {\n console.log(chalk.gray(\" Verify it with `rebase cloud db test`.\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to attach database\");\n }\n}\n\nasync function testDatabase(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n console.log(\"\");\n console.log(` Testing database connectivity for project ${chalk.bold(projectId)}...`);\n try {\n const res = await client.functions.invoke<{ success: boolean; logs?: string }>(\"db-test\", { projectId });\n console.log(\"\");\n if (res.logs) console.log(res.logs);\n if (res.success) success(\"Database connection succeeded\");\n else fail(\"Database connection failed. See logs above.\");\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 portForward: { namespace: string; service: string; localPort: number; remotePort: number } | 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 const args = arg({ \"--reveal\": Boolean, \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\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\", path: 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.portForward) {\n const pf = info.portForward;\n console.log(\"\");\n console.log(chalk.gray(` Port-forward: kubectl -n ${pf.namespace} port-forward svc/${pf.service} ${pf.localPort}:${pf.remotePort}`));\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 portForward: info.portForward,\n unavailableReason: info.unavailableReason,\n // Only present when explicitly revealed.\n ...(args[\"--reveal\"] ? { password, connectionString } : {})\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load database info\");\n }\n}\n\n/* ─── backups ──────────────────────────────────────────────────── */\n\nasync function backupCommand(rawArgs: string[]): Promise<void> {\n // `rebase cloud db backup <action>` — action is the 4th positional token.\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2] || \"list\";\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2), permissive: true });\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: ${res.backup?.filename ?? \"(unknown)\"}`),\n { success: true, backup: res.backup ?? null }\n );\n return;\n }\n\n if (action === \"restore\") {\n const filename = cloudPositionals(rawArgs).slice(3)[0];\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, message: 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 = cloudPositionals(rawArgs).slice(3)[0];\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, size: res.size, url: res.url }\n );\n return;\n }\n\n // default: list\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 size = b.size !== undefined ? `${(b.size / 1024 / 1024).toFixed(1)} MB` : \"\";\n console.log(` ${chalk.bold(b.filename)} ${chalk.gray(`${b.type ?? \"\"} ${size}`.trim())}`);\n }\n console.log(\"\");\n },\n { projectId, backups: 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 const args = arg(\n { \"--target\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const action = cloudPositionals(rawArgs).slice(2)[0] || \"status\";\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, targetTime: target, acknowledgeNoCutover: 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 fail(`Unknown pitr command: ${action}`, \"Try status | restore | cutover | discard.\", \"usage\");\n } catch (e) {\n reportError(e, \"PITR operation failed\");\n }\n}\n\nfunction printDbHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud db\")} — Database & backups\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List databases attached to the project\n ${chalk.blue.bold(\"create\")} Attach a managed or bring-your-own database\n ${chalk.blue.bold(\"info\")} ${chalk.gray(\"[--reveal]\")} Connection details ${chalk.gray(\"(password only with --reveal)\")}\n ${chalk.blue.bold(\"test\")} Test database connectivity\n ${chalk.blue.bold(\"backup list\")} List backups\n ${chalk.blue.bold(\"backup create\")} Create a manual backup\n ${chalk.blue.bold(\"backup restore\")} ${chalk.gray(\"<file>\")} Restore a backup\n ${chalk.blue.bold(\"backup status\")} Automated-backup health\n ${chalk.blue.bold(\"backup download\")} ${chalk.gray(\"<file>\")} Signed URL for a backup\n ${chalk.blue.bold(\"pitr status\")} Point-in-time recovery window\n ${chalk.blue.bold(\"pitr restore\")} ${chalk.gray(\"--target <ISO>\")} Stage a recovery ${chalk.gray(\"(does not repoint)\")}\n ${chalk.blue.bold(\"pitr cutover\")} ${chalk.gray(\"-y\")} Repoint the app at the staged recovery\n ${chalk.blue.bold(\"pitr discard\")} ${chalk.gray(\"-y\")} Delete a staged recovery\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n ${chalk.blue(\"--reveal\")} Include the DB password ${chalk.gray(\"(info)\")}\n ${chalk.blue(\"--type\")} managed | byodb ${chalk.gray(\"(create)\")}\n ${chalk.blue(\"--connection-string\")} External DB URL ${chalk.gray(\"(byodb)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\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 arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n isJsonMode,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\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);\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}`, \"Try `rebase cloud env --help`.\");\n }\n}\n\n/** A short human hint about redeploy state (the JSON carries `pendingRedeploy`). */\nfunction pendingHint(pending: boolean | null): string | undefined {\n if (pending === true) return chalk.yellow(\"A variable changed since the last deploy — run `rebase cloud deploy` to apply it.\");\n if (pending === null) return chalk.gray(\"Redeploy state is unknown (deployment history unavailable).\");\n return undefined;\n}\n\nasync function listEnv(rawArgs: string[]): Promise<void> {\n const { 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(), value: first.slice(eq + 1) };\n }\n // `set KEY VALUE` form — VALUE is the next operand (may be absent ⇒ empty).\n return { key: first.trim(), value: 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\nasync function setEnv(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--secret\": Boolean, \"--force\": Boolean, \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const operands = cloudPositionals(rawArgs).slice(2); // after `env set`\n const parsed = parseEnvAssignment(operands);\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 `Put ${buildTimePrefix}* variables in the source you deploy (a committed .env, or your build ` +\n `config), then \\`rebase cloud deploy\\`. 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, value: 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\nasync function unsetEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env unset KEY\", undefined, \"usage\");\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, key, pendingRedeploy: 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 { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env reveal KEY\", undefined, \"usage\");\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 if (!found) fail(`No variable named ${key} in project ${projectRef}.`, undefined, \"not_found\");\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, key },\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, value: res.value }\n );\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n}\n\nasync function pullEnv(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--out\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const outPath = path.resolve(args[\"--out\"] || \".env\");\n\n try {\n const list = await fetchEnvVars(client, projectId);\n\n if (fs.existsSync(outPath)) {\n await confirmDestructive({ yes: Boolean(args[\"--yes\"]), prompt: `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, reason: \"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, key: v.key },\n { path: \"reveal\" }\n );\n // Quote values that contain whitespace or a hash so a dotenv reader\n // keeps them intact.\n const needsQuote = /[\\s#'\"]/.test(revealed.value);\n lines.push(`${v.key}=${needsQuote ? JSON.stringify(revealed.value) : revealed.value}`);\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 console.log(chalk.gray(` Skipped ${skipped.length} secret variable(s): ${skipped.map((s) => s.key).join(\", \")}`));\n console.log(\"\");\n }\n },\n { success: true, path: outPath, written, skipped }\n );\n } catch (e) {\n reportError(e, \"Failed to pull environment variables\");\n }\n}\n\nfunction printEnvHelp(): void {\n if (isJsonMode()) {\n printEnvHelpJson();\n return;\n }\n console.log(`\n${chalk.bold(\"rebase cloud env\")} — Environment variables\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List keys ${chalk.gray(\"(values are never printed)\")}\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"KEY=VALUE [--secret]\")} Create or replace a variable\n ${chalk.blue.bold(\"unset\")} ${chalk.gray(\"KEY\")} Remove a variable\n ${chalk.blue.bold(\"reveal\")} ${chalk.gray(\"KEY\")} Print one non-secret value\n ${chalk.blue.bold(\"pull\")} ${chalk.gray(\"[--out .env] [-y]\")} Write revealable values to a dotenv file\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--secret\")} Mark a variable write-only ${chalk.gray(\"(set)\")}\n ${chalk.blue(\"--force\")} Set a build-time key anyway ${chalk.gray(\"(set)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n\n${chalk.gray(\"Values are encrypted at rest (AES-256-GCM) and only decrypted at deploy time.\")}\n${chalk.gray(\"VITE_* / NEXT_PUBLIC_* / PUBLIC_* / REACT_APP_* are read by your bundler at BUILD time;\")}\n${chalk.gray(\"these are applied at rollout, after the image is built, so they never reach the bundle.\")}\n`);\n}\n\nfunction printEnvHelpJson(): void {\n process.stdout.write(\n JSON.stringify({\n command: \"env\",\n actions: [\"list\", \"set\", \"unset\", \"reveal\", \"pull\"]\n }) + \"\\n\"\n );\n}\n","/**\n * `rebase cloud domains` — a project's custom domain.\n *\n * domains list Current domain + the DNS records it needs\n * domains add <domain> Register a domain (starts, does not finish, setup)\n * domains verify Check the published DNS now; live only if it passes\n * domains remove Detach the custom domain\n *\n * The DNS record set comes from the server (`verify-domain`), never composed\n * here: whether to publish an A or a CNAME depends on apex-vs-subdomain and on\n * the ingress address behind the tenant host, which the CLI cannot know. Adding\n * a domain only registers it — it is unverified until the records are published\n * and `verify` passes.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n keyValues,\n success,\n fail,\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 DomainSetup {\n domain: string | null;\n status: \"none\" | \"pending\" | \"verified\";\n isApex?: boolean;\n tenantHost?: string;\n verifiedAt?: string | null;\n instructions?: {\n pointing?: DomainRecord;\n ownership: DomainRecord;\n };\n}\n\ninterface DomainCheck {\n ok: boolean;\n expected: string[];\n observed: string[];\n error?: string;\n}\n\ninterface VerifyResult extends DomainSetup {\n verified: boolean;\n checks: { ownership: DomainCheck; pointing: DomainCheck };\n}\n\nasync function fetchDomainSetup(client: CloudClient, projectId: string): Promise<DomainSetup> {\n return client.functions.invoke<DomainSetup>(\"verify-domain\", undefined, { method: \"GET\", path: projectId });\n}\n\nfunction printRecords(setup: DomainSetup): void {\n const recs = [setup.instructions?.pointing, setup.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 verifyDomains(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}`, \"Try `rebase cloud domains --help`.\");\n }\n}\n\nasync function listDomains(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🌐 Custom domain — project ${projectRef}`));\n console.log(\"\");\n if (!setup.domain) {\n console.log(chalk.gray(\" No custom domain. Add one with `rebase cloud domains add <domain>`.\"));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Domain\", setup.domain],\n [\"Status\", setup.status === \"verified\" ? chalk.green(setup.status) : chalk.yellow(setup.status)],\n [\"Apex\", setup.isApex === undefined ? undefined : setup.isApex ? \"yes\" : \"no\"],\n [\"Tenant host\", setup.tenantHost],\n [\"Verified at\", setup.verifiedAt ?? undefined]\n ]);\n console.log(\"\");\n if (setup.status !== \"verified\") printRecords(setup);\n },\n { projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to load custom domain\");\n }\n}\n\nasync function addDomain(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const domain = cloudPositionals(rawArgs).slice(2)[0];\n if (!domain) fail(\"Usage: rebase cloud domains add <domain>\", undefined, \"usage\");\n\n try {\n // Registering the domain is a project update; the DNS records to publish\n // then come from the server's setup endpoint.\n await client.data.collection(\"projects\").update(projectId, { customDomain: domain });\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n success(`Registered ${chalk.bold(domain!)} — not yet verified`);\n printRecords(setup);\n console.log(chalk.gray(\" Publish the records above, then run `rebase cloud domains verify`.\"));\n console.log(\"\");\n },\n { success: true, projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to register domain\");\n }\n}\n\nasync function verifyDomains(rawArgs: string[]): Promise<void> {\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<VerifyResult>(\"verify-domain\", {}, { path: projectId });\n emit(\n () => {\n console.log(\"\");\n if (res.verified) success(`${res.domain} is verified and live`);\n else {\n console.log(chalk.yellow(` ⚠ ${res.domain ?? \"domain\"} 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);\n }\n },\n { projectId, verified: res.verified, status: res.status, domain: res.domain, checks: res.checks, instructions: res.instructions }\n );\n if (!res.verified) process.exit(1);\n } catch (e) {\n reportError(e, \"Failed to verify domain\");\n }\n}\n\nasync function removeDomain(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\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: `Remove the custom domain from project ${projectRef}?`\n });\n\n try {\n await client.data.collection(\"projects\").update(projectId, { customDomain: \"\" });\n emit(\n () => success(`Removed the custom domain from project ${projectRef}`),\n { success: true, projectId }\n );\n } catch (e) {\n reportError(e, \"Failed to remove domain\");\n }\n}\n\nfunction printDomainsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud domains\")} — Custom domain\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} Show the domain + DNS records\n ${chalk.blue.bold(\"add\")} ${chalk.gray(\"<domain>\")} Register a custom domain\n ${chalk.blue.bold(\"verify\")} Check DNS and go live\n ${chalk.blue.bold(\"remove\")} ${chalk.gray(\"[-y]\")} Detach the custom domain\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\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 arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\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}`, \"Try `rebase cloud extensions --help`.\");\n }\n}\n\nasync function listExtensions(rawArgs: string[]): Promise<void> {\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, databaseType: res.databaseType, reason: res.reason, source: res.source, extensions: res.extensions }\n );\n } catch (e) {\n reportError(e, \"Failed to list extensions\");\n }\n}\n\nasync function enableExtension(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions enable <name>\", undefined, \"usage\");\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, extensionName: 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 args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions disable <name>\", undefined, \"usage\");\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, extensionName: 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\nfunction printExtensionsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud extensions\")} — Postgres extensions\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List extensions and their state\n ${chalk.blue.bold(\"enable\")} ${chalk.gray(\"<name> [-y]\")} Enable one ${chalk.gray(\"(pgvector alias ⇒ vector)\")}\n ${chalk.blue.bold(\"disable\")} ${chalk.gray(\"<name>\")} Disable one\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--yes, -y\")} Confirm a DB-restarting change\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\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\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 arg from \"arg\";\nimport chalk from \"chalk\";\nimport { requireClient, requireProject, displayProjectRef, emit, 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}\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}`, \"Try `rebase cloud settings --help`.\");\n }\n}\n\nasync function showSettings(rawArgs: string[]): Promise<void> {\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 unknown 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 ]);\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 }\n );\n } catch (e) {\n reportError(e, \"Failed to load settings\");\n }\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}): Record<string, string> {\n const patch: Record<string, string> = {};\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 return patch;\n}\n\nasync function setSettings(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--project\": String,\n \"-p\": \"--project\"\n },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const patch = buildSettingsPatch({\n name: args[\"--name\"],\n subdomain: args[\"--subdomain\"],\n repo: args[\"--repo\"],\n branch: args[\"--branch\"]\n });\n if (Object.keys(patch).length === 0) {\n fail(\"Nothing to update.\", \"Pass --name, --subdomain, --repo, or --branch.\", \"usage\");\n }\n\n try {\n if (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, projectId, updated: patch }\n );\n } catch (e) {\n reportError(e, \"Failed to update settings\");\n }\n}\n\nfunction printSettingsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud settings\")} — Project configuration\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"show\")} Show current settings\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"[flags]\")} Update settings\n\n${chalk.green.bold(\"Set flags\")}\n ${chalk.blue(\"--name\")} ${chalk.gray(\"<name>\")}\n ${chalk.blue(\"--subdomain\")} ${chalk.gray(\"<sub>\")}\n ${chalk.blue(\"--repo\")} ${chalk.gray(\"<git url>\")}\n ${chalk.blue(\"--branch\")} ${chalk.gray(\"<branch>\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\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 image (`status === \"success\" && imageUrl`);\n * anything else 409s `deploy_not_rollbackable` server-side. So this module never\n * offers — and refuses to invoke — a rollback the server would reject, exactly\n * mirroring the console's `isRollbackable`.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\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 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 backend's rule EXACTLY: a rollback is honoured only for a successful\n * deploy that recorded an image. Any other row 409s `deploy_not_rollbackable`.\n */\nexport function isRollbackable(dep: DeploymentRow): boolean {\n return dep.status === \"success\" && deploymentImage(dep) !== null;\n}\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, source, userId: 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 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 version the\n // bundle resolved. 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 message: str(dep, \"deployMessage\", \"deploy_message\"),\n frameworkVersion: str(dep, \"frameworkVersion\", \"framework_version\"),\n commit: {\n hash: str(dep, \"gitCommitHash\", \"gitCommitHash\"),\n message: str(dep, \"gitCommitMessage\", \"gitCommitMessage\")\n }\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 res.data as unknown as DeploymentRow[];\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 const args = arg(\n { \"--limit\": Number, \"--all\": Boolean, \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\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 framework version are what make one row\n // distinguishable from the next; indented under it so the\n // status line stays scannable when they are absent.\n const label = [v.message, v.frameworkVersion ? `@rebasepro/* ${v.frameworkVersion}` : 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, limit, truncated, deployments: views }\n );\n } catch (e) {\n reportError(e, \"Failed to list deployments\");\n }\n}\n\nexport async function rollbackCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // `rollback [deploymentId]` — the id, when given, is the first operand after\n // the `rollback` group token.\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\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 target = rows!.find((d) => String(d.id) === explicitId);\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 (needs a successful deploy that recorded an image).`,\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 (needs a successful deploy that recorded an image).\",\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 imageUrl: string;\n }>(\"deploy\", { projectId, deploymentId: String(target!.id), client: \"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 [\"Image\", res.imageUrl]\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\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 args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\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<{ success: boolean; deploymentId: string; buildJobDeleted: boolean }>(\n \"deploy\",\n explicitId ? { projectId, deploymentId: explicitId } : { projectId },\n { path: \"cancel\" }\n );\n emit(\n () => {\n success(`Cancelled deployment ${chalk.bold(res.deploymentId)}`);\n if (res.buildJobDeleted) console.log(chalk.gray(\" The build job was deleted.\"));\n console.log(\"\");\n },\n { success: true, deploymentId: res.deploymentId, buildJobDeleted: res.buildJobDeleted }\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 arg from \"arg\";\nimport { requireClient, requireProject, displayProjectRef, 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 const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\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, projectId, status: \"stopped\" });\n } else if (action === \"start\") {\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Started project ${projectRef}`), { success: true, projectId, status: \"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, projectId, status: \"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 {\n requireClient,\n requireProject,\n displayProjectRef,\n fetchTenantBaseDomain,\n projectHost,\n colorStatus,\n keyValues,\n emit,\n isJsonMode,\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\", meaning: `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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"auth is mounted and rejected the empty body, as it should\" };\n }\n if (status === 401 || status === 403) {\n return { verdict: \"ok\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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\", meaning: \"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, pod: null, text: line };\n return { ts: m[1] ?? null, pod: m[2] ?? null, text: 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\ninterface RuntimeLogsResponse {\n logs?: string;\n pods?: Array<{ pod: string; state: string; lines: number; message: string | null; hint: string | null }>;\n ordering?: string;\n truncated?: boolean;\n state?: string;\n message?: string | null;\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 if (res.truncated) console.log(chalk.gray(\" (output truncated — narrow the window with --since)\"));\n}\n\n/** Resolve the public origin a project is served at. */\nasync 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), permissive: 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 const parsed = arg(\n { \"--collection\": String, \"--function\": String },\n { argv: rawArgs.slice(3), permissive: true }\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, overall, probes: 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\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. */\n defaultSinceSeconds: number;\n /** Max lines rendered. */\n limit: number;\n title: string;\n}\n\nasync function logView(rawArgs: string[], view: LogViewOptions): Promise<void> {\n const parsed = arg(\n { \"--since\": String, \"--tail\": Number, \"--previous\": Boolean },\n { argv: rawArgs.slice(3), permissive: true }\n );\n\n const sinceArg = parsed[\"--since\"];\n if (sinceArg !== undefined && parseSince(sinceArg) === null) {\n fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n }\n const sinceSeconds = parseSince(sinceArg) ?? view.defaultSinceSeconds;\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,\n tailLines: parsed[\"--tail\"] ?? 500,\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\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` ${view.title} — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` last ${formatDuration(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" (nothing matched in this window)\"));\n console.log(\"\");\n return;\n }\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 {\n sinceSeconds,\n state: res.state ?? null,\n pods: res.pods ?? [],\n truncated: Boolean(res.truncated),\n matched: kept.length,\n lines: shown\n }\n );\n}\n\nasync function requestsCommand(rawArgs: string[]): Promise<void> {\n const parsed = arg({ \"--since\": String, \"--tail\": Number }, { argv: rawArgs.slice(3), permissive: true });\n const sinceArg = parsed[\"--since\"];\n if (sinceArg !== undefined && parseSince(sinceArg) === null) {\n fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n }\n const sinceSeconds = parseSince(sinceArg) ?? 900;\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, tailLines: parsed[\"--tail\"] ?? 1000 });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const entries = (res.logs ?? \"\")\n .split(\"\\n\")\n .filter((l) => l !== \"\")\n .map((l) => parseRequestLine(parseLogLine(l).text))\n .filter((e): e is RequestLogEntry => e !== null);\n const shown = entries.slice(-40);\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 🌐 Requests — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` last ${formatDuration(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" No structured request lines in this window.\"));\n console.log(chalk.gray(\" (this view needs the server's request logging; try `debug logs`)\"));\n console.log(\"\");\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 },\n { sinceSeconds, requests: shown }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: pod\n ═══════════════════════════════════════════════════════════════ */\n\nasync function podCommand(rawArgs: string[]): Promise<void> {\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, placement: p }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: db\n ═══════════════════════════════════════════════════════════════ */\n\nasync function dbDebugCommand(rawArgs: string[]): Promise<void> {\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 portForward?: { namespace: string; service: string; localPort: number; remotePort: number } | null;\n }\n\n let info: DbInfo;\n try {\n info = await client.functions.invoke<DbInfo>(\"db-info\", undefined, { method: \"GET\", path: projectId });\n } catch (e) {\n reportError(e, \"Failed to read database connection info\");\n }\n\n const pf = info.portForward;\n const forwardCmd = pf\n ? `kubectl port-forward -n ${pf.namespace} svc/${pf.service} ${pf.localPort}:${pf.remotePort}`\n : null;\n const psqlCmd =\n pf && info.username && info.database\n ? `psql -h 127.0.0.1 -p ${pf.localPort} -U ${info.username} -d ${info.database}`\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 (forwardCmd) {\n // Printed rather than run. Opening a tunnel and a superuser shell\n // is not something a command called `debug` should do implicitly.\n console.log(chalk.gray(\" A managed database is only reachable inside its cluster. To connect:\"));\n console.log(\"\");\n console.log(` ${forwardCmd}`);\n if (psqlCmd) console.log(` ${psqlCmd}`);\n console.log(\"\");\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 portForwardCommand: forwardCmd,\n psqlCommand: psqlCmd\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\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 await logView(rawArgs, { defaultSinceSeconds: 900, limit: 200, title: \"📄 Logs\" });\n break;\n case \"errors\":\n await logView(rawArgs, {\n filter: isErrorLine,\n defaultSinceSeconds: 3600,\n limit: 40,\n title: \"🔥 Errors\"\n });\n break;\n case \"boot\":\n await logView(rawArgs, {\n filter: isBootLine,\n // The whole log, not a window: startup happened when the pod\n // started, which may have been days ago.\n defaultSinceSeconds: 7 * 24 * 3600,\n limit: 25,\n title: \"🚀 Boot\"\n });\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 if (isJsonMode()) fail(`Unknown debug command: ${action}`, undefined, \"unknown_command\");\n console.error(chalk.red(`Unknown debug command: ${action}`));\n console.log(\"\");\n printDebugHelp();\n process.exit(1);\n }\n}\n\nfunction printDebugHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud debug\")} — Find out why a deployed project is misbehaving\n\n${chalk.green.bold(\"Usage\")}\n rebase cloud debug ${chalk.blue(\"<subcommand>\")} [options]\n\n${chalk.green.bold(\"End-to-end\")}\n ${chalk.blue.bold(\"health\")} Probe the live URL and explain every status code ${chalk.gray(\"(default)\")}\n\n${chalk.green.bold(\"Runtime\")}\n ${chalk.blue.bold(\"logs\")} ${chalk.gray(\"[--since 15m]\")} Recent application logs\n ${chalk.blue.bold(\"errors\")} ${chalk.gray(\"[--since 1h]\")} Error and warning lines only\n ${chalk.blue.bold(\"requests\")} ${chalk.gray(\"[--since 15m]\")} HTTP requests the server logged ${chalk.gray(\"(status, path, latency)\")}\n ${chalk.blue.bold(\"boot\")} What the server decided at startup ${chalk.gray(\"(storage, functions, auth)\")}\n ${chalk.blue.bold(\"pod\")} Replicas, image, namespace, cluster placement\n\n${chalk.green.bold(\"Data\")}\n ${chalk.blue.bold(\"db\")} Connection shape + the port-forward recipe ${chalk.gray(\"(no password)\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--since <dur>\")} Lookback window: ${chalk.gray(\"90s, 15m, 2h, 1d\")}\n ${chalk.blue(\"--tail <n>\")} Lines to read per pod ${chalk.gray(\"(default 500)\")}\n ${chalk.blue(\"--previous\")} Read the CRASHED container instance ${chalk.gray(\"(where the reason lives)\")}\n ${chalk.blue(\"--host <hostname>\")} Probe this address instead of the project's own\n ${chalk.blue(\"--collection <name>\")} Collection for the unauth-read probe ${chalk.gray(\"(default: users)\")}\n ${chalk.blue(\"--function <name>\")} Also assert this function loaded ${chalk.gray(\"(checked against the listing)\")}\n ${chalk.blue(\"--project, -p <slug>\")} Operate on a project without linking\n\n${chalk.gray(\"Everything here is read-only. `health` exits non-zero when a check fails,\")}\n${chalk.gray(\"so it works in a deploy script. To restart a workload, use `rebase cloud restart`.\")}\n`);\n}\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 keyValues,\n fetchTenantBaseDomain,\n projectHost,\n openUrl,\n success,\n fail,\n reportError\n} from \"./context\";\nimport { firstRow, latestDeployment, fmtDate } from \"./projects\";\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/**\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 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 // 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(` · framework ${framework}`) : \"\";\n return `managed ${version}${frameworkPart}${pin}`;\n}\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\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\", path: 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\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 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 url: projectHost(project, baseDomain) ?? null,\n branch: project.gitBranch ?? null,\n lastDeploy: deploy ? { id: String(deploy.id), status: deploy.status ?? null, createdAt: deploy.createdAt ?? null } : null,\n runtime: {\n mode: project.runtimeMode ?? \"custom\",\n version: project.runtimeVersion ?? null,\n frameworkVersion: 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, connectionStatus: 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\nexport async function metricsCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const m = await client.functions.invoke<{\n status?: string;\n cpu?: string;\n memory?: string;\n memoryPercent?: string;\n disk?: string;\n }>(\"metrics\", undefined, { method: \"GET\",\npath: projectId });\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 [\"CPU\", m.cpu],\n [\"Memory\", m.memory ? `${m.memory}${m.memoryPercent ? ` (${m.memoryPercent})` : \"\"}` : undefined],\n [\"Disk\", m.disk]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch metrics\");\n }\n}\n\n/* ─── webhooks ─────────────────────────────────────────────────── */\n\nexport async function webhooksCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n if (subcommand === \"create\") {\n const args = arg(\n { \"--name\": String,\n\"--table\": String,\n\"--url\": String,\n\"--events\": String },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const name = args[\"--name\"] || fail(\"--name is required.\");\n const table = args[\"--table\"] || fail(\"--table is required.\");\n const url = args[\"--url\"] || fail(\"--url (endpoint) is required.\");\n const events = (args[\"--events\"] || \"insert,update,delete\").split(\",\").map((s) => s.trim());\n\n const created = (await client.data.collection(\"webhooks\").create({\n project: projectId,\n name,\n table,\n url,\n events,\n enabled: true\n })) as unknown as { id: string | number };\n success(`Created webhook ${chalk.bold(name)} [${created.id}]`);\n return;\n }\n\n if (subcommand === \"delete\") {\n const id = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2];\n if (!id) fail(\"Usage: rebase cloud webhooks delete <id>\");\n await client.data.collection(\"webhooks\").delete(id);\n success(`Deleted webhook ${id}`);\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 unknown as Array<{ id: string | number; name?: string; table?: string; url?: string; enabled?: boolean; events?: string[] }>;\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 } catch (e) {\n reportError(e, \"Webhook operation failed\");\n }\n}\n\n/* ─── storage ──────────────────────────────────────────────────── */\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\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 unknown as Array<{ id: string | number; type?: string; provider?: string; bucketName?: string; status?: string }>;\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 console.log(` ${chalk.bold(s.bucketName ?? s.type ?? \"bucket\")} ${chalk.gray(`[${s.id}]`)} ${colorStatus(s.status)}`);\n keyValues([[\"Provider\", s.provider], [\"Type\", s.type]]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list storage\");\n }\n}\n\nfunction printStorageHelp(): void {\n console.log(\"\");\n console.log(chalk.bold(\" rebase cloud storage\"));\n console.log(\"\");\n console.log(\" \" + chalk.blue.bold(\"storage\") + \" List this project's storage\");\n console.log(\" \" + chalk.blue.bold(\"storage create\") + \" Provision platform-managed storage\");\n console.log(\" \" + chalk.blue.bold(\"storage attach\") + \" Attach your own S3-compatible bucket\");\n console.log(\"\");\n console.log(chalk.gray(\" attach options:\"));\n console.log(chalk.gray(\" --bucket <name> Bucket name (required)\"));\n console.log(chalk.gray(\" --access-key-id <id> Access key ID (required)\"));\n console.log(chalk.gray(\" --secret-access-key <s> Secret access key (required)\"));\n console.log(chalk.gray(\" --endpoint <url> S3 endpoint; omit for AWS\"));\n console.log(chalk.gray(\" --region <region> Region\"));\n console.log(chalk.gray(\" --force-path-style Required by MinIO and some gateways\"));\n console.log(\"\");\n console.log(chalk.gray(\" Without either, file storage stays off: uploads are refused with\"));\n console.log(chalk.gray(\" 501 STORAGE_NOT_CONFIGURED rather than written to a container\"));\n console.log(chalk.gray(\" filesystem that is erased on the next restart.\"));\n console.log(\"\");\n}\n\n/* ─── storage create: platform-managed ─────────────────────────── */\n\nasync function storageCreateCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n console.log(\"\");\n console.log(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 }>(`storage-provision/${encodeURIComponent(projectId)}`, undefined, { method: \"POST\" });\n\n const info = (res as unknown as { data?: typeof res.data }).data ?? res.data;\n\n success(`Managed storage provisioned for ${displayProjectRef(rawArgs)}.`);\n keyValues([\n [\"Bucket\", info.bucketName],\n [\"Region\", info.region],\n [\"Endpoint\", info.endpoint],\n [\"Access key\", info.accessKeyId]\n ]);\n console.log(\"\");\n // The secret is never returned by the endpoint — it goes to the row and\n // to the tenant's environment. Say so, or the absence reads as a bug.\n console.log(chalk.gray(\" The secret key is stored encrypted and injected at deploy time; it is not displayed.\"));\n console.log(chalk.gray(\" Redeploy for the tenant to pick it up: \") + chalk.bold(\"rebase cloud deploy\"));\n console.log(\"\");\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 const parsed = arg(\n {\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 },\n { argv: rawArgs.slice(3), permissive: true }\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 );\n }\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n const existing = (await client.data.collection(\"storages\").find({\n where: { project: [\"==\", projectId] },\n limit: 1\n })).data[0] as { id?: string | number } | undefined;\n\n const row: Record<string, unknown> = {\n project: projectId,\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 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 keyValues([\n [\"Bucket\", bucket],\n [\"Endpoint\", parsed[\"--endpoint\"] ?? \"AWS S3\"],\n [\"Region\", parsed[\"--region\"] ?? \"(default)\"]\n ]);\n console.log(\"\");\n console.log(chalk.gray(\" Redeploy for the tenant to pick it up: \") + chalk.bold(\"rebase cloud deploy\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to attach storage\");\n }\n}\n\n/* ─── clusters ─────────────────────────────────────────────────── */\n\nexport async function clustersCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n try {\n const clusters = (await client.data.collection(\"clusters\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n provider?: string;\n region?: string;\n status?: string;\n }>;\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 } catch (e) {\n reportError(e, \"Failed to list clusters\");\n }\n}\n\n/* ─── billing ──────────────────────────────────────────────────── */\n\nexport async function billingCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\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.\");\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.\");\n openUrl(res.url, \"Add a payment method in your browser:\");\n if (res.simulated) {\n console.log(chalk.gray(\" (dev mode — Stripe not configured; complete setup from the console)\"));\n console.log(\"\");\n } else {\n console.log(chalk.gray(\" Once you've added a card, `rebase cloud deploy` runs without further prompts.\"));\n console.log(\"\");\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.\");\n console.log(\"\");\n console.log(\" Complete checkout in your browser:\");\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\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.\");\n try {\n const orgRow = (await client.data.collection(\"organizations\").findById(org)) as\n | { billing_account_id?: string | number; billingAccount?: string | number }\n | undefined;\n const billingId = orgRow?.billing_account_id ?? orgRow?.billingAccount;\n if (!billingId) {\n console.log(\"\");\n console.log(chalk.gray(` Organization ${org} has no billing account yet.`));\n console.log(\"\");\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: show which plan the linked/`--project` project is on.\n // BYO-cluster projects pay a flat platform fee; the rest pay managed compute.\n let plan: 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 | { cluster_id?: string | number; cluster?: unknown; provider?: string; vmSize?: string }\n | undefined;\n const hasCluster = proj?.cluster_id != null || proj?.cluster != null;\n plan = hasCluster ? \"platform fee (own cluster)\" : \"managed compute\";\n\n // Best-effort: append the resolved monthly amount from Stripe (via\n // the control plane's /api/functions/pricing). Keep working if the\n // endpoint is unreachable — the label alone is still useful.\n try {\n const pricing = await client.functions.invoke<{\n items: Array<{ lookupKey: string; amountEur: number }>;\n }>(\"pricing\", undefined, { method: \"GET\" });\n const key = hasCluster\n ? \"platform_byo\"\n : `compute_${proj?.provider || \"hetzner\"}_${proj?.vmSize || \"cx21\"}`;\n const item = pricing.items?.find((i) => i.lookupKey === key);\n if (item) plan = `${plan} — €${item.amountEur.toFixed(2)}/mo`;\n } catch {\n // pricing endpoint unreachable — keep the plan label without an amount\n }\n }\n } catch {\n // no linked/resolvable project — skip the Plan line\n }\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 [\"Plan\", plan],\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 } catch (e) {\n reportError(e, \"Failed to load billing\");\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 { linkCommand, unlinkCommand, selectOrgCommand, openCommand } from \"./link\";\nimport { listProjects, createProject, projectInfo, deleteProject } from \"./projects\";\nimport { deployCommand, logsCommand } from \"./deploy\";\nimport { orgsCommand } from \"./orgs\";\nimport { dbCommand } from \"./databases\";\nimport { envCommand } from \"./env\";\nimport { domainsCommand } from \"./domains\";\nimport { extensionsCommand } from \"./extensions\";\nimport { settingsCommand } from \"./settings\";\nimport { deploymentsListCommand, rollbackCommand, cancelCommand } from \"./deployments\";\nimport { powerCommand } from \"./power\";\nimport { debugCommand } from \"./debug\";\nimport {\n statusCommand,\n metricsCommand,\n webhooksCommand,\n storageCommand,\n clustersCommand,\n billingCommand\n} from \"./resources\";\nimport { requireProjectRef, initOutputMode } from \"./context\";\n\n/** Positional tokens after `rebase cloud` (group, action, …). */\nfunction positionals(rawArgs: string[]): string[] {\n return arg({}, { argv: rawArgs.slice(3),\npermissive: true })._;\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 const group = subcommand && subcommand !== \"--help\" ? subcommand : pos[0];\n const action = pos[1];\n\n if (!group || subcommand === \"--help\") {\n 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\n /* context / link */\n case \"link\":\n await linkCommand(rawArgs);\n break;\n case \"unlink\":\n unlinkCommand();\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\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 \"clusters\":\n await clustersCommand(rawArgs);\n break;\n case \"billing\":\n await billingCommand(rawArgs);\n break;\n\n default:\n console.error(chalk.red(`Unknown cloud command: ${group}`));\n console.log(\"\");\n printCloudHelp();\n process.exit(1);\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 case \"info\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await projectInfo(rawArgs, id);\n break;\n }\n case \"delete\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await deleteProject(rawArgs, id);\n break;\n }\n case \"--help\":\n printCloudHelp();\n break;\n default:\n console.error(chalk.red(`Unknown projects command: ${action}`));\n process.exit(1);\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 console.error(chalk.red(`Unknown deployments command: ${action}`));\n process.exit(1);\n }\n}\n\nfunction printCloudHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud\")} — Manage your apps on Rebase Cloud\n\n${chalk.green.bold(\"Usage\")}\n rebase cloud ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"login\")} Sign in to the control plane\n ${chalk.blue.bold(\"logout\")} Sign out\n ${chalk.blue.bold(\"whoami\")} Show the current session\n\n${chalk.green.bold(\"Project link\")}\n ${chalk.blue.bold(\"link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"unlink\")} Remove the link\n ${chalk.blue.bold(\"use\")} ${chalk.gray(\"[org]\")} Select the active organization\n ${chalk.blue.bold(\"open\")} Open the dashboard in a browser\n\n${chalk.green.bold(\"Projects\")}\n ${chalk.blue.bold(\"projects list\")} List projects\n ${chalk.blue.bold(\"projects create\")} Create a project ${chalk.gray(\"(--link to link it)\")}\n ${chalk.blue.bold(\"projects info\")} ${chalk.gray(\"[id]\")} Show project details\n ${chalk.blue.bold(\"projects delete\")} ${chalk.gray(\"[id]\")} Delete a project\n\n${chalk.green.bold(\"Deploy & observe\")}\n ${chalk.blue.bold(\"deploy\")} ${chalk.gray(\"[--bundle|--source .]\")} Deploy the linked project + stream build logs\n ${chalk.blue.bold(\"logs\")} ${chalk.gray(\"[--runtime] [-f]\")} Show build (or runtime) logs\n ${chalk.blue.bold(\"deployments list\")} ${chalk.gray(\"[--limit N|--all]\")} Deployment history ${chalk.gray(\"(status, duration, trigger)\")}\n ${chalk.blue.bold(\"rollback\")} ${chalk.gray(\"[id] [-y]\")} Roll back to a successful deploy\n ${chalk.blue.bold(\"cancel\")} ${chalk.gray(\"[-y]\")} Cancel the in-flight build\n ${chalk.blue.bold(\"start|stop|restart\")} ${chalk.gray(\"[-y]\")} Power ops ${chalk.gray(\"(stop/restart need -y)\")}\n ${chalk.blue.bold(\"status\")} One-glance project status\n ${chalk.blue.bold(\"metrics\")} Live CPU / memory / disk\n ${chalk.blue.bold(\"debug\")} ${chalk.gray(\"[health|logs|…]\")} Diagnose a misbehaving deployment ${chalk.gray(\"(read-only)\")}\n\n${chalk.green.bold(\"Config\")}\n ${chalk.blue.bold(\"env list|set|unset|reveal|pull\")}\n ${chalk.blue.bold(\"domains list|add|verify|remove\")}\n ${chalk.blue.bold(\"extensions list|enable|disable\")}\n ${chalk.blue.bold(\"settings show|set\")} Name / branch / repo / subdomain\n\n${chalk.green.bold(\"Organizations\")}\n ${chalk.blue.bold(\"orgs list|create|members\")}\n\n${chalk.green.bold(\"Databases\")}\n ${chalk.blue.bold(\"db list|create|info|test\")}\n ${chalk.blue.bold(\"db backup list|create|restore|status|download\")}\n ${chalk.blue.bold(\"db pitr status|restore|cutover|discard\")}\n\n${chalk.green.bold(\"Other resources\")}\n ${chalk.blue.bold(\"webhooks list|create|delete\")}\n ${chalk.blue.bold(\"storage\")} List storage buckets\n ${chalk.blue.bold(\"storage create\")} Provision platform-managed storage\n ${chalk.blue.bold(\"storage attach\")} Attach your own S3-compatible bucket\n ${chalk.blue.bold(\"clusters\")} List compute clusters\n ${chalk.blue.bold(\"billing setup\")} Attach a card to the org ${chalk.gray(\"(one-time, opens browser)\")}\n ${chalk.blue.bold(\"billing\")} Show billing account + card on file\n\n${chalk.green.bold(\"Global options\")}\n ${chalk.blue(\"--json\")} Machine-readable output ${chalk.gray(\"(also when piped, or REBASE_JSON=1)\")}\n ${chalk.blue(\"--url <origin>\")} Target a specific control plane ${chalk.gray(\"(or REBASE_CLOUD_URL)\")}\n ${chalk.blue(\"--project, -p <id>\")} Operate on a project without linking\n\n${chalk.gray(\"Most commands act on the linked project (.rebase/cloud.json) unless --project is given.\")}\n${chalk.gray(\"Docs: https://rebase.pro/docs\")}\n`);\n}\n","/**\n * CLI command: rebase apps\n *\n * Inspect the apps this repository contributes to a project, adopt a\n * `rebase.json` for a project that predates it, and print the client bootstrap\n * an app needs to reach its backend.\n *\n * The distinction that runs through all of this: a *repository* declares apps,\n * a *project* owns them. Two repositories can contribute to the same project and\n * never know about each other, which is what makes a separate frontend repo — or\n * a mobile app with no repo relationship at all — an ordinary thing rather than\n * a special case.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport type { RebaseAppConfig } from \"@rebasepro/types\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport {\n assessManagedCompatibility,\n loadManifest,\n ManifestError,\n manifestExists,\n synthesizeManifest,\n writeManifest\n} from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase apps\")} — the apps this repository contributes\n\n${chalk.bold(\"Usage\")}\n rebase apps list List declared apps and their build outputs\n rebase apps init Write a rebase.json inferred from this project\n rebase apps config <app> Print the client configuration for an app\n\n${chalk.bold(\"Options\")}\n --json Machine-readable output\n --force Overwrite an existing rebase.json (apps init)\n -h, --help Show this help\n`.trim());\n}\n\nexport async function appsCommand(subcommand: string | undefined, rawArgs: string[] = []): Promise<void> {\n const args = arg(\n {\n \"--json\": Boolean,\n \"--force\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n },\n { argv: rawArgs.slice(3),\npermissive: true }\n );\n\n if (args[\"--help\"] || !subcommand || subcommand === \"--help\") {\n printHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listApps(Boolean(args[\"--json\"]));\n break;\n case \"init\":\n await initManifest(Boolean(args[\"--force\"]));\n break;\n case \"config\":\n await printAppConfig(args._[1], Boolean(args[\"--json\"]));\n break;\n default:\n console.error(chalk.red(`Unknown subcommand: ${subcommand}`));\n console.log(\"\");\n printHelp();\n process.exit(1);\n }\n}\n\nfunction describeApp(app: RebaseAppConfig): string {\n switch (app.type) {\n case \"backend\":\n return app.runtime === \"custom\"\n ? `custom runtime — ${app.dockerfile ?? \"Dockerfile\"}`\n : `managed runtime, config: ${app.config ?? \"config\"}`;\n case \"static\":\n return `${app.root} → ${app.output} @ ${app.path ?? \"/\"}`;\n default:\n return \"\";\n }\n}\n\nasync function listApps(asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot);\n const compatibility = assessManagedCompatibility(loaded.manifest);\n\n if (asJson) {\n console.log(JSON.stringify(\n {\n source: loaded.source,\n rebase: loaded.manifest.rebase,\n apps: loaded.manifest.apps,\n managed: compatibility\n },\n null,\n 2\n ));\n return;\n }\n\n if (loaded.source === \"synthesized\") {\n console.log(chalk.dim(\"No rebase.json — showing the layout inferred from this project.\"));\n console.log(chalk.dim(`Run ${chalk.cyan(\"rebase apps init\")} to write it down.\\n`));\n }\n\n console.log(chalk.bold(`Rebase ${loaded.manifest.rebase}`));\n console.log(\"\");\n\n const entries = Object.entries(loaded.manifest.apps);\n if (entries.length === 0) {\n console.log(chalk.yellow(\"No apps declared.\"));\n return;\n }\n\n const width = Math.max(...entries.map(([name]) => name.length));\n for (const [name, app] of entries) {\n console.log(\n ` ${chalk.cyan(name.padEnd(width))} ${chalk.dim(app.type.padEnd(8))} ${describeApp(app)}`\n );\n }\n\n console.log(\"\");\n if (compatibility.eligible) {\n console.log(chalk.green(\"✓ Eligible for the managed runtime.\"));\n } else {\n console.log(chalk.yellow(\"• Uses the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\nasync function initManifest(force: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n\n if (manifestExists(projectRoot) && !force) {\n console.error(chalk.red(\"✗ rebase.json already exists.\"));\n console.error(chalk.dim(\" Pass --force to overwrite it.\"));\n process.exit(1);\n }\n\n const manifest = synthesizeManifest(projectRoot);\n const filePath = writeManifest(projectRoot, manifest);\n\n console.log(chalk.green(`✓ Wrote ${path.relative(projectRoot, filePath)}`));\n console.log(\"\");\n for (const [name, app] of Object.entries(manifest.apps)) {\n console.log(` ${chalk.cyan(name)} ${chalk.dim(`(${app.type})`)}`);\n }\n\n const compatibility = assessManagedCompatibility(manifest);\n if (!compatibility.eligible) {\n console.log(\"\");\n console.log(chalk.yellow(\"This project will use the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/**\n * Print what a client needs to reach this project.\n *\n * Never prints a secret. The API URL and an app's publishable identity are meant\n * to ship inside a client bundle; anything that is not safe there does not belong\n * in output that will inevitably be pasted into a `.env` that gets committed.\n */\nasync function printAppConfig(appName: string | undefined, asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot);\n\n if (!appName) {\n console.error(chalk.red(\"✗ Which app? Usage: rebase apps config <app>\"));\n process.exit(1);\n }\n\n const app = loaded.manifest.apps[appName];\n if (!app) {\n console.error(chalk.red(`✗ No app named \"${appName}\" in rebase.json.`));\n console.error(chalk.dim(` Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n\n const link = readLink(projectRoot);\n const apiUrl = resolveApiUrl(projectRoot, link);\n\n const config = {\n app: appName,\n type: app.type,\n apiUrl: apiUrl ?? null,\n project: link?.projectId ?? link?.slug ?? null\n };\n\n if (asJson) {\n console.log(JSON.stringify(config, null, 2));\n return;\n }\n\n if (!apiUrl) {\n console.log(chalk.yellow(\"This checkout is not linked to a project yet.\"));\n console.log(chalk.dim(` Run ${chalk.cyan(\"rebase link\")} (cloud) or ${chalk.cyan(\"rebase link <url>\")} (self-hosted).`));\n console.log(\"\");\n }\n\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n console.log(`VITE_API_URL=${apiUrl ?? \"http://localhost:3001\"}`);\n console.log(\"\");\n console.log(chalk.dim(\"Then, in the app:\"));\n console.log(chalk.dim(\" const rebase = createRebaseClient({ baseUrl: import.meta.env.VITE_API_URL });\"));\n}\n\n/**\n * Work out the API base URL for this checkout.\n *\n * Prefers an explicit link, then the dev server's own record of where it bound.\n * The dev port is chosen dynamically, so a hardcoded default would be wrong on\n * any machine running more than one project.\n */\nfunction resolveApiUrl(projectRoot: string, link: ReturnType<typeof readLink>): string | undefined {\n if (link?.apiUrl) return link.apiUrl;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as { baseUrl?: string };\n if (state.baseUrl) return state.baseUrl;\n } catch {\n // Stale or partially written state file: fall through.\n }\n }\n\n return undefined;\n}\n\nfunction loadManifestOrExit(projectRoot: string): ReturnType<typeof loadManifest> {\n try {\n return loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.red(` ${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n}\n","import chalk from \"chalk\";\nimport arg from \"arg\";\nimport { createRebaseApp } from \"./commands/init\";\nimport { generateSdkCommand } from \"./commands/generate_sdk\";\nimport { schemaCommand } from \"./commands/schema\";\nimport { dbCommand } from \"./commands/db\";\nimport { devCommand } from \"./commands/dev\";\nimport { buildCommand } from \"./commands/build\";\nimport { ejectCommand } from \"./commands/eject\";\nimport { startCommand } from \"./commands/start\";\nimport { authCommand } from \"./commands/auth\";\nimport { doctorCommand } from \"./commands/doctor\";\nimport { skillsCommand } from \"./commands/skills\";\nimport { apiKeysCommand } from \"./commands/api-keys\";\nimport { cloudCommand } from \"./commands/cloud\";\nimport { appsCommand } from \"./commands/apps\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction getVersion(): string {\n try {\n // Try to read version from package.json\n const pkgPath = path.resolve(__dirname, \"../package.json\");\n if (fs.existsSync(pkgPath)) {\n return JSON.parse(fs.readFileSync(pkgPath, \"utf-8\")).version;\n }\n } catch {\n // ignore\n }\n return \"unknown\";\n}\n\nexport async function entry(args: string[]) {\n const parsedArgs = arg(\n {\n \"--version\": Boolean,\n \"--help\": Boolean,\n \"-v\": \"--version\",\n \"-h\": \"--help\"\n },\n {\n argv: args.slice(2),\n permissive: true\n }\n );\n\n if (parsedArgs[\"--version\"]) {\n console.log(getVersion());\n return;\n }\n\n const command = parsedArgs._[0];\n const subcommand = parsedArgs._[1];\n\n // Show global help only when no command given, or --help with no recognized command\n const namespacedCommands = [\"init\", \"schema\", \"db\", \"dev\", \"build\", \"start\", \"auth\", \"doctor\", \"skills\", \"api-keys\", \"cloud\", \"apps\", \"eject\", \"generate-sdk\"];\n if (!command || (parsedArgs[\"--help\"] && !namespacedCommands.includes(command))) {\n printHelp();\n return;\n }\n\n // For namespaced commands with --help, pass it through as subcommand\n const effectiveSubcommand = parsedArgs[\"--help\"] ? \"--help\" : subcommand;\n\n switch (command) {\n case \"init\":\n await createRebaseApp(args);\n break;\n\n case \"generate-sdk\": {\n const sdkArgs = arg(\n {\n \"--collections-dir\": String,\n \"--output\": String,\n \"--from\": String,\n \"--token\": String,\n \"--help\": Boolean,\n \"-c\": \"--collections-dir\",\n \"-o\": \"--output\",\n \"-h\": \"--help\"\n },\n {\n argv: args.slice(3),\n permissive: true\n }\n );\n await generateSdkCommand({\n collectionsDir: sdkArgs[\"--collections-dir\"] || \"./config/collections\",\n output: sdkArgs[\"--output\"] || \"./generated/sdk\",\n from: sdkArgs[\"--from\"],\n token: sdkArgs[\"--token\"],\n help: sdkArgs[\"--help\"],\n cwd: process.cwd()\n });\n break;\n }\n\n case \"schema\":\n await schemaCommand(effectiveSubcommand, args);\n break;\n\n case \"db\":\n await dbCommand(effectiveSubcommand, args);\n break;\n\n case \"dev\":\n await devCommand(args);\n break;\n\n case \"build\":\n await buildCommand(args);\n break;\n\n case \"start\":\n await startCommand(args);\n break;\n\n case \"apps\":\n await appsCommand(effectiveSubcommand, args);\n break;\n\n case \"eject\":\n await ejectCommand(args);\n break;\n\n case \"auth\":\n await authCommand(effectiveSubcommand, args);\n break;\n\n case \"doctor\":\n await doctorCommand(args);\n break;\n\n case \"skills\":\n await skillsCommand(effectiveSubcommand, args);\n break;\n\n case \"api-keys\":\n await apiKeysCommand(effectiveSubcommand, args);\n break;\n\n case \"cloud\":\n await cloudCommand(effectiveSubcommand, args);\n break;\n\n default:\n console.error(chalk.red(`Unknown command: ${command}`));\n console.log(\"\");\n printHelp();\n // A mistyped command must not look like success to a shell or CI.\n process.exit(1);\n }\n}\n\nfunction printHelp() {\n console.log(`\n${chalk.bold(\"Rebase CLI\")} — Developer tools for Rebase projects\n\n${chalk.green.bold(\"Usage\")}\n rebase ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"init\")} Create a new Rebase project\n ${chalk.blue.bold(\"dev\")} Start the development server\n ${chalk.blue.bold(\"build\")} Build all workspace packages\n ${chalk.blue.bold(\"start\")} Start the backend server ${chalk.gray(\"(production)\")}\n ${chalk.blue.bold(\"apps list\")} Show the apps this repository declares\n ${chalk.blue.bold(\"eject\")} Take ownership of the server process and image\n\n${chalk.green.bold(\"Schema\")}\n ${chalk.blue.bold(\"schema generate\")} Generate Drizzle schema from collections\n ${chalk.blue.bold(\"schema introspect\")} Introspect database → Rebase collections\n ${chalk.blue.bold(\"schema\")} ${chalk.gray(\"--help\")} Show schema command help\n\n${chalk.green.bold(\"Database\")}\n ${chalk.blue.bold(\"db push\")} Apply schema directly to database ${chalk.gray(\"(dev)\")}\n ${chalk.blue.bold(\"db generate\")} Generate SQL migration files\n ${chalk.blue.bold(\"db migrate\")} Run pending migrations\n ${chalk.blue.bold(\"db\")} ${chalk.gray(\"--help\")} Show database command help\n\n${chalk.green.bold(\"SDK\")}\n ${chalk.blue.bold(\"generate-sdk\")} Generate a typed TypeScript SDK from collections\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"auth reset-password\")} Reset a user's password\n ${chalk.blue.bold(\"auth\")} ${chalk.gray(\"--help\")} Show auth command help\n\n${chalk.green.bold(\"Diagnostics\")}\n ${chalk.blue.bold(\"doctor\")} Detect schema drift between collections, schema, and DB\n\n${chalk.green.bold(\"AI Agent Skills\")}\n ${chalk.blue.bold(\"skills install\")} Install Rebase agent skills for your AI coding assistant\n\n${chalk.green.bold(\"API Keys\")}\n ${chalk.blue.bold(\"api-keys list\")} List all service API keys\n ${chalk.blue.bold(\"api-keys create\")} Create a new scoped API key\n ${chalk.blue.bold(\"api-keys revoke\")} Revoke an existing API key\n ${chalk.blue.bold(\"api-keys\")} ${chalk.gray(\"--help\")} Show API key command help\n\n${chalk.green.bold(\"Rebase Cloud\")}\n ${chalk.blue.bold(\"cloud login\")} Sign in to the hosted control plane\n ${chalk.blue.bold(\"cloud link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"cloud deploy\")} Deploy the linked project + stream logs\n ${chalk.blue.bold(\"cloud\")} ${chalk.gray(\"--help\")} Show all cloud commands\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--version, -v\")}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