@rebasepro/cli 0.34.0 → 0.34.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-setup-CGeAuP0Q.js → agent-setup-kjdKozkF.js} +3 -3
- package/dist/{agent-setup-CGeAuP0Q.js.map → agent-setup-kjdKozkF.js.map} +1 -1
- package/dist/{api-zx1wSK5a.js → api-CQh_qTyQ.js} +2 -2
- package/dist/{api-zx1wSK5a.js.map → api-CQh_qTyQ.js.map} +1 -1
- package/dist/{api-keys-DaWN8dyI.js → api-keys-CG2IpknI.js} +5 -5
- package/dist/{api-keys-DaWN8dyI.js.map → api-keys-CG2IpknI.js.map} +1 -1
- package/dist/{apps-D6vtDrkJ.js → apps-DaaWvv3o.js} +6 -6
- package/dist/{apps-D6vtDrkJ.js.map → apps-DaaWvv3o.js.map} +1 -1
- package/dist/{atlas-dev-database-D6h65f2x.js → atlas-dev-database-BiDMUr9W.js} +2 -2
- package/dist/{atlas-dev-database-D6h65f2x.js.map → atlas-dev-database-BiDMUr9W.js.map} +1 -1
- package/dist/{auth-DY7kU0z-.js → auth-bi8x2YX1.js} +12 -12
- package/dist/{auth-DY7kU0z-.js.map → auth-bi8x2YX1.js.map} +1 -1
- package/dist/{auth-session-DCG96UGH.js → auth-session-BVoxE5tp.js} +4 -4
- package/dist/{auth-session-DCG96UGH.js.map → auth-session-BVoxE5tp.js.map} +1 -1
- package/dist/{backend-guard-Cf8eMK_f.js → backend-guard--SW3MTSh.js} +2 -2
- package/dist/{backend-guard-Cf8eMK_f.js.map → backend-guard--SW3MTSh.js.map} +1 -1
- package/dist/{branch-pointer-BJOF2Ubv.js → branch-pointer-BjKUoENm.js} +1 -1
- package/dist/{build-D0egCUfU.js → build-D-0VCmbU.js} +11 -11
- package/dist/build-D-0VCmbU.js.map +1 -0
- package/dist/{bundle-DhdhtD8K.js → bundle-BDTVS9XE.js} +6 -6
- package/dist/{bundle-DhdhtD8K.js.map → bundle-BDTVS9XE.js.map} +1 -1
- package/dist/{cloud-DOR7bxDw.js → cloud-CR6Hps3B.js} +12 -12
- package/dist/{cloud-DOR7bxDw.js.map → cloud-CR6Hps3B.js.map} +1 -1
- package/dist/{cms-directories-BaV-Is9a.js → cms-directories-AGHvFwH7.js} +2 -2
- package/dist/{cms-directories-BaV-Is9a.js.map → cms-directories-AGHvFwH7.js.map} +1 -1
- package/dist/{command-BzSP5gBh.js → command-nWgittn1.js} +3 -3
- package/dist/{command-BzSP5gBh.js.map → command-nWgittn1.js.map} +1 -1
- package/dist/commands/build.d.ts +2 -1
- package/dist/{consent-UV6ObCME.js → consent-C8_Ik_GK.js} +3 -3
- package/dist/{consent-UV6ObCME.js.map → consent-C8_Ik_GK.js.map} +1 -1
- package/dist/{console-BVoYOLAO.js → console-BBGRHOFg.js} +5 -5
- package/dist/{console-BVoYOLAO.js.map → console-BBGRHOFg.js.map} +1 -1
- package/dist/{context-xt20FMFA.js → context-C9lz1vTS.js} +2 -2
- package/dist/{context-xt20FMFA.js.map → context-C9lz1vTS.js.map} +1 -1
- package/dist/{cron-CJ6Xk42E.js → cron-BzzNxkBH.js} +3 -3
- package/dist/{cron-CJ6Xk42E.js.map → cron-BzzNxkBH.js.map} +1 -1
- package/dist/{cron-BGkXIB1N.js → cron-DuZ3Svjq.js} +4 -4
- package/dist/{cron-BGkXIB1N.js.map → cron-DuZ3Svjq.js.map} +1 -1
- package/dist/{daemon-D5gdG7gx.js → daemon-BCBMn8hE.js} +2 -2
- package/dist/{daemon-D5gdG7gx.js.map → daemon-BCBMn8hE.js.map} +1 -1
- package/dist/{data-BpkvtCUe.js → data-1eipHbxJ.js} +3 -3
- package/dist/{data-BpkvtCUe.js.map → data-1eipHbxJ.js.map} +1 -1
- package/dist/{db-D_iF4E-v.js → db-DAotpOxs.js} +28 -28
- package/dist/{db-D_iF4E-v.js.map → db-DAotpOxs.js.map} +1 -1
- package/dist/{debug-C7Ss34XB.js → debug-CkiOcfsU.js} +2 -2
- package/dist/{debug-C7Ss34XB.js.map → debug-CkiOcfsU.js.map} +1 -1
- package/dist/{derive-ChP6vgfi.js → derive-BU5kvcOP.js} +2 -2
- package/dist/{derive-ChP6vgfi.js.map → derive-BU5kvcOP.js.map} +1 -1
- package/dist/{dev-C7n36E6f.js → dev-Ce9PVQS8.js} +13 -13
- package/dist/{dev-C7n36E6f.js.map → dev-Ce9PVQS8.js.map} +1 -1
- package/dist/{dev-preflight-BMOf2N6r.js → dev-preflight-DROlafgr.js} +2 -2
- package/dist/{dev-preflight-BMOf2N6r.js.map → dev-preflight-DROlafgr.js.map} +1 -1
- package/dist/{dev-server-2XHSHM_q.js → dev-server-dsabI0UT.js} +2 -2
- package/dist/{dev-server-2XHSHM_q.js.map → dev-server-dsabI0UT.js.map} +1 -1
- package/dist/{doctor-D0o54XSQ.js → doctor-Cdu3Llrw.js} +7 -7
- package/dist/{doctor-D0o54XSQ.js.map → doctor-Cdu3Llrw.js.map} +1 -1
- package/dist/{eject-DK_M9kor.js → eject-Dy-qRYhW.js} +3 -3
- package/dist/{eject-DK_M9kor.js.map → eject-Dy-qRYhW.js.map} +1 -1
- package/dist/{fold-static-DTpaqbB0.js → fold-static-DzV3EJZm.js} +4 -4
- package/dist/{fold-static-DTpaqbB0.js.map → fold-static-DzV3EJZm.js.map} +1 -1
- package/dist/{functions-DLuuldt2.js → functions-BCEJnISw.js} +4 -4
- package/dist/{functions-DLuuldt2.js.map → functions-BCEJnISw.js.map} +1 -1
- package/dist/{generate-view-BMaLQm8H.js → generate-view-CZ0SmsJc.js} +4 -4
- package/dist/{generate-view-BMaLQm8H.js.map → generate-view-CZ0SmsJc.js.map} +1 -1
- package/dist/{generate_sdk-UT1lwwRT.js → generate_sdk-MAbUUZoK.js} +6 -6
- package/dist/{generate_sdk-UT1lwwRT.js.map → generate_sdk-MAbUUZoK.js.map} +1 -1
- package/dist/index.es.js +54 -54
- package/dist/{init-u5Xmr1Ct.js → init-BctfWO3w.js} +44 -24
- package/dist/init-BctfWO3w.js.map +1 -0
- package/dist/last-dev-database-w-r9T5Xm.js +2 -0
- package/dist/{legacy-layout-DI2VeQSV.js → legacy-layout-CiXWalS6.js} +2 -2
- package/dist/{legacy-layout-DI2VeQSV.js.map → legacy-layout-CiXWalS6.js.map} +1 -1
- package/dist/{logs-DBYRSs6W.js → logs-B_mS4gCn.js} +4 -4
- package/dist/{logs-DBYRSs6W.js.map → logs-B_mS4gCn.js.map} +1 -1
- package/dist/{manifest-RjqxfCpb.js → manifest-D6B4LA8x.js} +3 -3
- package/dist/{manifest-RjqxfCpb.js.map → manifest-D6B4LA8x.js.map} +1 -1
- package/dist/{migrate-Cw1FkvUK.js → migrate-DdcgLMyL.js} +3 -3
- package/dist/{migrate-Cw1FkvUK.js.map → migrate-DdcgLMyL.js.map} +1 -1
- package/dist/{normalize-imports-E4yA1HfW.js → normalize-imports-CVjOssZ2.js} +2 -2
- package/dist/{normalize-imports-E4yA1HfW.js.map → normalize-imports-CVjOssZ2.js.map} +1 -1
- package/dist/{package-manager-DSEOwTqM.js → package-manager-DTNNGHyK.js} +29 -12
- package/dist/package-manager-DTNNGHyK.js.map +1 -0
- package/dist/{path-flags-ekLdkbra.js → path-flags-B7Ydt5nv.js} +2 -2
- package/dist/{path-flags-ekLdkbra.js.map → path-flags-B7Ydt5nv.js.map} +1 -1
- package/dist/{prepare-BaJe0Zik.js → prepare-CFpYl1Nt.js} +4 -4
- package/dist/{prepare-BaJe0Zik.js.map → prepare-CFpYl1Nt.js.map} +1 -1
- package/dist/{project-DALmhb5R.js → project-CQ5nKddJ.js} +2 -2
- package/dist/{project-DALmhb5R.js.map → project-CQ5nKddJ.js.map} +1 -1
- package/dist/{project-command-7EGMemEy.js → project-command-5wM_bJQt.js} +7 -7
- package/dist/{project-command-7EGMemEy.js.map → project-command-5wM_bJQt.js.map} +1 -1
- package/dist/resolve-GDRel2ne.js +2 -0
- package/dist/{resources-CE6BeL94.js → resources-ecA0MEjy.js} +4 -4
- package/dist/{resources-CE6BeL94.js.map → resources-ecA0MEjy.js.map} +1 -1
- package/dist/{rls-BxWLfEKl.js → rls-B4zGbTKY.js} +3 -3
- package/dist/{rls-BxWLfEKl.js.map → rls-B4zGbTKY.js.map} +1 -1
- package/dist/{schema-D8xFSBbN.js → schema-CWzzn0cY.js} +11 -11
- package/dist/{schema-D8xFSBbN.js.map → schema-CWzzn0cY.js.map} +1 -1
- package/dist/{schema-dir-ChcYfWjP.js → schema-dir-Dd1Pzqq5.js} +2 -2
- package/dist/{schema-dir-ChcYfWjP.js.map → schema-dir-Dd1Pzqq5.js.map} +1 -1
- package/dist/schema-reconcile-DGEMmYJI.js +2 -0
- package/dist/{schema-show-C7bY7SgE.js → schema-show-DwYtOp4S.js} +5 -5
- package/dist/{schema-show-C7bY7SgE.js.map → schema-show-DwYtOp4S.js.map} +1 -1
- package/dist/{skills-C8WdRTFg.js → skills-CWmBTCRW.js} +5 -5
- package/dist/{skills-C8WdRTFg.js.map → skills-CWmBTCRW.js.map} +1 -1
- package/dist/{start-CN_9C205.js → start-4uhCu_md.js} +6 -6
- package/dist/{start-CN_9C205.js.map → start-4uhCu_md.js.map} +1 -1
- package/dist/{status-HWlZbY1E.js → status-CVEzoSwX.js} +7 -7
- package/dist/{status-HWlZbY1E.js.map → status-CVEzoSwX.js.map} +1 -1
- package/dist/{storage-DBE8lgH-.js → storage-Dqf5tyhs.js} +9 -9
- package/dist/{storage-DBE8lgH-.js.map → storage-Dqf5tyhs.js.map} +1 -1
- package/dist/{storage-objects-ljDmtuH7.js → storage-objects-DbFsemMV.js} +3 -3
- package/dist/{storage-objects-ljDmtuH7.js.map → storage-objects-DbFsemMV.js.map} +1 -1
- package/dist/{telemetry-DZU2-NCm.js → telemetry-B5RSeQIc.js} +3 -3
- package/dist/{telemetry-DZU2-NCm.js.map → telemetry-B5RSeQIc.js.map} +1 -1
- package/dist/{telemetry-EVtASbKb.js → telemetry-CJbrRuG3.js} +2 -2
- package/dist/{telemetry-EVtASbKb.js.map → telemetry-CJbrRuG3.js.map} +1 -1
- package/dist/{upgrade-ZASvgxWM.js → upgrade-CepjhRrz.js} +6 -6
- package/dist/{upgrade-ZASvgxWM.js.map → upgrade-CepjhRrz.js.map} +1 -1
- package/dist/{users-DrJEtL9k.js → users-Cx5HuaTn.js} +3 -3
- package/dist/{users-DrJEtL9k.js.map → users-Cx5HuaTn.js.map} +1 -1
- package/dist/utils/package-manager.d.ts +12 -13
- package/dist/{verify-BdeqNb-V.js → verify-D-1y5HQS.js} +8 -8
- package/dist/{verify-BdeqNb-V.js.map → verify-D-1y5HQS.js.map} +1 -1
- package/package.json +10 -10
- package/templates/template/npmrc +5 -7
- package/dist/build-D0egCUfU.js.map +0 -1
- package/dist/init-u5Xmr1Ct.js.map +0 -1
- package/dist/last-dev-database-CBVkEUEl.js +0 -2
- package/dist/package-manager-DSEOwTqM.js.map +0 -1
- package/dist/resolve-C36px9tR.js +0 -2
- package/dist/schema-reconcile-D_wvZY91.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-command-7EGMemEy.js","names":[],"sources":["../src/utils/project-target.ts","../src/utils/project-command.ts"],"sourcesContent":["/**\n * Which server a project command talks to, and as whom.\n *\n * Every command that acts on a running Rebase app — `rebase api`, `data`,\n * `users`, `cron`, `logs`, `functions`, `storage`, `api-keys`, `schema\n * reconcile` — resolves its target here, so they all accept the same flags,\n * refuse the same way, and never disagree about where the service key may go.\n *\n * ## Targets\n *\n * 1. `--project <slug>` (or `--cloud`, the project this directory is linked\n * to) — a Rebase Cloud project. The default transport is the console's\n * Studio proxy (`/api/functions/studio/<id>/proxy/*` on the control\n * plane): the CLI presents its `rebase cloud login` session there and the\n * control plane attaches the app's service key on its own side, so no\n * static secret ever reaches this machine. It answers an organization\n * owner or admin, on a project whose Studio switch is on — the gate the\n * console's Studio tab has. A command that only needs cron asks for a\n * platform token instead (see {@link ProjectTargetOptions.platformScopes}),\n * which any member with log access holds.\n * 2. `--url <server>` — a server the developer names.\n * 3. `REBASE_BASE_URL`, in the shell or in `.env`.\n * 4. The `rebase dev` this checkout is running (`.rebase/state.json`, while\n * the pid it names is alive).\n *\n * Nothing else: an address the CLI only guessed is one it would hand the\n * service key to without knowing whose server answers.\n *\n * ## Credentials, on a server target\n *\n * The service key from `.env` (`REBASE_SERVICE_KEY`, or the older\n * `SERVICE_KEY`; the shell's `REBASE_SERVICE_KEY` wins) unless the line says\n * otherwise: `--token <bearer>` sends that bearer (an `rk_` key, a user's\n * access token), `--session` sends the person session `rebase auth login`\n * stored for that server, and `--anon` sends nothing. On a cloud target the\n * same three flags skip the proxy and go to the app's public address directly.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport chalk from \"chalk\";\n\nimport { findProjectRoot, readEnvFile } from \"./project\";\nimport { cliUserAgent } from \"./version\";\nimport { serverUnreachableHint } from \"./dev-server\";\n\n/* ═══════════════════════════════════════════════════════════════\n Flags\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The flags every project command accepts, merged into its own spec.\n *\n * `--json` and `--yes` are here because the output mode and the confirmation\n * prompt are shared too (`commands/cloud/context.ts`): one JSON value on\n * stdout when piped or asked for, and a refusal rather than a prompt when\n * there is nobody to answer one.\n */\nexport const PROJECT_TARGET_FLAGS = {\n \"--project\": String,\n \"-p\": \"--project\",\n \"--cloud\": Boolean,\n \"--url\": String,\n \"--token\": String,\n \"--session\": Boolean,\n \"--anon\": Boolean,\n \"--json\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} as const;\n\n/** The same flags, as every project command's help page lists them. */\nexport const PROJECT_TARGET_HELP: Array<[string, string]> = [\n [\"--project, -p <slug>\", \"Act on a Rebase Cloud project, through the console's Studio proxy\"],\n [\"--cloud\", \"Act on the Rebase Cloud project this directory is linked to\"],\n [\"--url <server>\", \"Act on the server at this address (else REBASE_BASE_URL, then `rebase dev`)\"],\n [\"--token <bearer>\", \"Send this bearer instead of the service key (an rk_ key, a user's token)\"],\n [\"--session\", \"Send the session `rebase auth login` stored for this server\"],\n [\"--anon\", \"Send no credential at all\"],\n [\"--json\", \"Machine-readable output (also when piped, or REBASE_JSON=1)\"],\n [\"--yes, -y\", \"Skip confirmation prompts\"]\n];\n\n/** The values {@link PROJECT_TARGET_FLAGS} resolves to, as a command's parsed flags hold them. */\nexport type ProjectTargetFlags = {\n \"--project\"?: string;\n \"--cloud\"?: boolean;\n \"--url\"?: string;\n \"--token\"?: string;\n \"--session\"?: boolean;\n \"--anon\"?: boolean;\n};\n\n/* ═══════════════════════════════════════════════════════════════\n Where the local backend is\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Where this project's backend is — or why the CLI will not say.\n *\n * `configured` is an address the developer named; `running` is the one this\n * project's backend recorded when it bound, and is still serving on. There is\n * no third, guessed, answer.\n */\nexport type BackendAddress =\n | {\n url: string;\n source: \"configured\" | \"running\";\n /**\n * Set when the address came from `.env` and is the cloud project this\n * directory is linked to — which `rebase cloud init --claim` writes\n * there for the app and the SDK, not as a choice of where local\n * commands go. The command still goes there; {@link cloudTargetNote}\n * says so.\n */\n cloudProject?: string;\n }\n | { url: null; reason: string };\n\n/** Whether a process with this pid is alive and ours to signal. */\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n // ESRCH: gone. EPERM: alive, but another user's — not this project's backend.\n return false;\n }\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 * The address the service key may be sent to, from the project alone.\n *\n * In order: `REBASE_BASE_URL` in the shell or in `.env`, then the\n * `.rebase/state.json` this project's backend writes when it binds — and only\n * while the pid it names is alive, because a backend that was killed leaves\n * the file behind. `.env`'s `PORT` was once the fallback, and every scaffold\n * writes `PORT=3001`: with `rebase dev` stopped, the key went to whatever\n * listened on 3001.\n */\nexport function resolveBackendAddress(env: Record<string, string>, projectRoot: string): BackendAddress {\n const fromShell = process.env.REBASE_BASE_URL?.trim();\n const configured = fromShell || env.REBASE_BASE_URL?.trim();\n if (configured) {\n const cloudProject = fromShell ? undefined : linkedCloudProjectAt(projectRoot, configured);\n return cloudProject ? { url: configured, source: \"configured\", cloudProject } : { url: configured, source: \"configured\" };\n }\n\n const state = readBackendState(projectRoot);\n if (state && isAlive(state.pid)) return { url: state.url, source: \"running\" };\n\n const last = state ? ` The last one recorded here, at ${state.url} (pid ${state.pid}), has stopped.` : \"\";\n return {\n url: null,\n reason: `This project's server is not running, so the service key was not sent anywhere.${last} ` +\n \"Start it with `rebase dev`. If it runs some other way — `rebase start`, a container — \" +\n \"set REBASE_BASE_URL in .env to its address, or pass --url. For a Rebase Cloud project, pass --project <slug>.\"\n };\n}\n\n/** The slug of the cloud project `.rebase/cloud.json` links, when `url` is its address. */\nfunction linkedCloudProjectAt(projectRoot: string, url: string): string | undefined {\n const link = readJsonFile(path.join(projectRoot, \".rebase\", \"cloud.json\"));\n if (!isRecord(link) || link.mode === \"direct\" || typeof link.apiUrl !== \"string\") return undefined;\n const bare = (u: string) => u.trim().replace(/\\/+$/, \"\");\n if (bare(link.apiUrl) !== bare(url)) return undefined;\n if (typeof link.slug === \"string\" && link.slug) return link.slug;\n return typeof link.projectId === \"string\" && link.projectId ? link.projectId : undefined;\n}\n\n/**\n * What to say before sending a request to the address of a cloud project\n * `.env` names: it goes there, and that project does not take this\n * project's local service key.\n */\nexport function cloudTargetNote(address: BackendAddress): string | undefined {\n if (address.url === null || !address.cloudProject) return undefined;\n return `Sending this to ${address.url}: REBASE_BASE_URL in .env is the address of cloud project ${address.cloudProject} `\n + \"(`rebase cloud init --claim` writes it there for the app, the SDK and the MCP server), and that project does not \"\n + \"take this project's local service key. To reach it with your Cloud login, pass --project \"\n + `${address.cloudProject}; to reach the local backend, run the command with REBASE_BASE_URL set to it in the shell, `\n + \"e.g. REBASE_BASE_URL=http://localhost:3001.\";\n}\n\nfunction readJsonFile(file: string): unknown {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf-8\"));\n } catch {\n return null;\n }\n}\n\n/** What `.rebase/state.json` says about the backend that wrote it, or null. */\nfunction readBackendState(projectRoot: string): { url: string; pid: number } | null {\n const parsed = readJsonFile(path.join(projectRoot, \".rebase\", \"state.json\"));\n if (!isRecord(parsed) || typeof parsed.pid !== \"number\" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return null;\n const url = typeof parsed.baseUrl === \"string\" && parsed.baseUrl.trim()\n ? parsed.baseUrl.trim()\n : typeof parsed.port === \"number\" ? `http://localhost:${parsed.port}` : null;\n return url ? { url, pid: parsed.pid } : null;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Person sessions (`rebase auth login`)\n ═══════════════════════════════════════════════════════════════ */\n\n/** One person's session on one server, as `rebase auth login` stores it. */\nexport interface StoredSession {\n accessToken: string;\n refreshToken?: string;\n /** Epoch milliseconds. */\n expiresAt: number;\n email?: string;\n uid?: string;\n}\n\ninterface SessionsFile {\n sessions: Record<string, StoredSession>;\n}\n\n/**\n * `~/.rebase/sessions.json`: the person sessions `rebase auth login` keeps,\n * keyed by server origin. Never the project directory — a token there is one\n * `git add .` from a repository — and never the cloud credentials file, which\n * holds control-plane sessions a different command family manages.\n * `REBASE_SESSIONS_FILE` moves it, for tests.\n */\nexport function sessionsPath(): string {\n return process.env.REBASE_SESSIONS_FILE || path.join(os.homedir(), \".rebase\", \"sessions.json\");\n}\n\nfunction readSessions(): SessionsFile {\n const parsed = readJsonFile(sessionsPath());\n if (!isRecord(parsed) || !isRecord(parsed.sessions)) return { sessions: {} };\n const sessions: Record<string, StoredSession> = {};\n for (const [origin, value] of Object.entries(parsed.sessions)) {\n if (isRecord(value) && typeof value.accessToken === \"string\" && typeof value.expiresAt === \"number\") {\n sessions[origin] = {\n accessToken: value.accessToken,\n expiresAt: value.expiresAt,\n ...(typeof value.refreshToken === \"string\" ? { refreshToken: value.refreshToken } : {}),\n ...(typeof value.email === \"string\" ? { email: value.email } : {}),\n ...(typeof value.uid === \"string\" ? { uid: value.uid } : {})\n };\n }\n }\n return { sessions };\n}\n\n/** Write the file beside itself, then rename it over: a concurrent reader sees the old file or the new one. */\nfunction writeSessions(data: SessionsFile): void {\n const file = sessionsPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(temporary, JSON.stringify(data, null, 2), { mode: 0o600 });\n try {\n fs.chmodSync(temporary, 0o600);\n } catch {\n // best effort on platforms without chmod semantics\n }\n fs.renameSync(temporary, file);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\n/** The origin a session is filed under: scheme, host and port, no path. */\nexport function sessionKey(baseUrl: string): string {\n try {\n return new URL(baseUrl).origin;\n } catch {\n return baseUrl.replace(/\\/+$/, \"\");\n }\n}\n\nexport function storedSession(baseUrl: string): StoredSession | undefined {\n return readSessions().sessions[sessionKey(baseUrl)];\n}\n\nexport function saveSession(baseUrl: string, session: StoredSession): void {\n const data = readSessions();\n data.sessions[sessionKey(baseUrl)] = session;\n writeSessions(data);\n}\n\n/** Forget a server's session. Returns whether there was one. */\nexport function forgetSession(baseUrl: string): boolean {\n const data = readSessions();\n const key = sessionKey(baseUrl);\n if (!data.sessions[key]) return false;\n delete data.sessions[key];\n writeSessions(data);\n return true;\n}\n\n/** Two minutes of head-room before an access token is treated as expired. */\nconst SESSION_EXPIRY_BUFFER_MS = 120_000;\n\n/**\n * The session's access token, refreshed first when it is close to expiry —\n * through the server's own `POST /api/auth/refresh`, which rotates the refresh\n * token, so the new pair is written back.\n */\nasync function freshSessionToken(baseUrl: string): Promise<string> {\n const session = storedSession(baseUrl);\n if (!session) {\n throw new TargetError(\n `No session is stored for ${sessionKey(baseUrl)}.`,\n \"Sign in first with `rebase auth login` (it takes the same --url / --project flags).\",\n \"not_logged_in\"\n );\n }\n if (session.expiresAt > Date.now() + SESSION_EXPIRY_BUFFER_MS) return session.accessToken;\n if (!session.refreshToken) {\n throw new TargetError(`Your session for ${sessionKey(baseUrl)} has expired.`, \"Run `rebase auth login` again.\", \"session_expired\");\n }\n let res: Response;\n try {\n res = await fetch(`${baseUrl.replace(/\\/+$/, \"\")}/api/auth/refresh`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"User-Agent\": cliUserAgent() },\n body: JSON.stringify({ refreshToken: session.refreshToken })\n });\n } catch (e) {\n throw new TargetError(`Could not reach ${sessionKey(baseUrl)} to refresh your session: ${errorText(e)}`, undefined, \"network_error\");\n }\n const body: unknown = await res.json().catch(() => null);\n const tokens = sessionTokensOf(body);\n if (!res.ok || !tokens) {\n forgetSession(baseUrl);\n throw new TargetError(`Your session for ${sessionKey(baseUrl)} has expired.`, \"Run `rebase auth login` again.\", \"session_expired\");\n }\n saveSession(baseUrl, { ...session, ...tokens });\n return tokens.accessToken;\n}\n\n/**\n * The token pair out of an auth response — `{ tokens: { accessToken,\n * refreshToken, accessTokenExpiresAt } }`, the shape login, refresh and the\n * device grant all answer.\n */\nexport function sessionTokensOf(body: unknown): Pick<StoredSession, \"accessToken\" | \"refreshToken\" | \"expiresAt\"> | undefined {\n if (!isRecord(body)) return undefined;\n const tokens = isRecord(body.tokens) ? body.tokens : body;\n if (typeof tokens.accessToken !== \"string\" || !tokens.accessToken) return undefined;\n const expiresRaw = tokens.accessTokenExpiresAt ?? tokens.expiresAt;\n const expiresAt = typeof expiresRaw === \"number\"\n ? (expiresRaw < 1e12 ? expiresRaw * 1000 : expiresRaw)\n : typeof expiresRaw === \"string\" ? Date.parse(expiresRaw) : Date.now() + 15 * 60_000;\n return {\n accessToken: tokens.accessToken,\n ...(typeof tokens.refreshToken === \"string\" ? { refreshToken: tokens.refreshToken } : {}),\n expiresAt: Number.isFinite(expiresAt) ? expiresAt : Date.now() + 15 * 60_000\n };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n The target\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * A refusal while resolving or reaching a target: what happened, what to do\n * about it, and a stable code. Commands report it through the shared `fail`,\n * so it is one JSON value when piped.\n */\nexport class TargetError extends Error {\n constructor(message: string, readonly hint?: string, readonly code: string = \"error\") {\n super(message);\n this.name = \"TargetError\";\n }\n}\n\n/** How a request reaches the app, and as whom — for messages and `--json` output. */\nexport type TargetCredential =\n | \"service-key\"\n | \"token\"\n | \"session\"\n | \"none\"\n | \"studio-proxy\"\n | \"platform-token\";\n\nexport interface RequestOptions {\n method?: string;\n /** Query parameters. Repeated values (`string[]`) become repeated keys. */\n query?: Record<string, string | number | boolean | readonly string[] | undefined>;\n /** A JSON body, stringified here. */\n json?: unknown;\n /** A raw body, sent as it is. */\n body?: BodyInit;\n headers?: Record<string, string>;\n /** Abort after this many milliseconds; unset means no limit (a stream, an upload). */\n timeoutMs?: number;\n}\n\nexport interface ProjectTarget {\n kind: \"server\" | \"cloud\";\n /** Where requests go, for messages: `http://localhost:3001 (rebase dev)`, `cloud project acme`. */\n label: string;\n credential: TargetCredential;\n /** The app's own origin when it is reached directly; for the Studio proxy, the proxy's base. */\n baseUrl: string;\n /** The cloud project id, on a cloud target. */\n projectId?: string;\n /** Send a request to `path` on the app (`/api/admin/users`), with the credential. */\n request(path: string, options?: RequestOptions): Promise<Response>;\n /**\n * The bearer a request carries, for the clients that open their own\n * connection (the SDK's realtime socket). On the Studio proxy this is the\n * control-plane session, which only the proxy accepts.\n */\n bearer(): Promise<string | undefined>;\n}\n\nexport interface ProjectTargetOptions {\n /** Names the command in messages: `data query`. */\n command: string;\n /**\n * On a cloud target, ask the control plane for a platform token holding\n * these scopes and call the app directly, instead of the Studio proxy.\n * Only scopes the control plane issues (`cron:read`, `cron:write`), and\n * only when no credential flag was given.\n */\n platformScopes?: readonly string[];\n /**\n * The credential the command needs when the line names none. `person`:\n * the session `rebase auth login` stored (the RLS simulator and personal\n * keys refuse machines). Default: the service key on a server target.\n */\n defaultCredential?: \"service-key\" | \"person\";\n}\n\n/** One line of query string out of {@link RequestOptions.query}. */\nexport function queryString(query: RequestOptions[\"query\"]): string {\n if (!query) return \"\";\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) for (const item of value) params.append(key, String(item));\n else params.append(key, String(value));\n }\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nfunction errorText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * A `fetch` that sends one request with a bearer, refusing redirects: a 3xx\n * that crosses origins drops `Authorization` in some runtimes and keeps it in\n * others, and neither is what the caller meant.\n */\nasync function send(url: string, bearer: string | undefined, options: RequestOptions, label: string): Promise<Response> {\n const headers: Record<string, string> = {\n \"User-Agent\": cliUserAgent(),\n Accept: \"application/json\",\n ...(options.headers ?? {})\n };\n if (bearer) headers.Authorization = `Bearer ${bearer}`;\n let body = options.body;\n if (options.json !== undefined) {\n body = JSON.stringify(options.json);\n headers[\"Content-Type\"] = \"application/json\";\n }\n const controller = options.timeoutMs ? new AbortController() : undefined;\n const timer = controller ? setTimeout(() => controller.abort(), options.timeoutMs) : undefined;\n // `duplex` is required by undici for a streamed request body, and is not\n // in the DOM lib's RequestInit yet.\n const init: RequestInit & { duplex?: \"half\" } = {\n method: options.method ?? \"GET\",\n headers,\n body,\n redirect: \"manual\",\n signal: controller?.signal\n };\n if (body instanceof ReadableStream) init.duplex = \"half\";\n try {\n return await fetch(url, init);\n } catch (e) {\n if (controller?.signal.aborted) {\n throw new TargetError(`${label} did not answer within ${Math.round((options.timeoutMs ?? 0) / 1000)}s.`, undefined, \"timeout\");\n }\n throw new TargetError(`Could not reach ${label}: ${errorText(e)}`, undefined, \"network_error\");\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * The service key this project's `.env` holds, and the variable it came from.\n * The shell's `REBASE_SERVICE_KEY` wins over the file.\n */\nexport function projectServiceKey(projectRoot: string | null): { key: string; variable: string } | undefined {\n const shell = process.env.REBASE_SERVICE_KEY?.trim();\n if (shell) return { key: shell, variable: \"REBASE_SERVICE_KEY\" };\n if (!projectRoot) return undefined;\n const env = readEnvFile(projectRoot);\n if (env.SERVICE_KEY) return { key: env.SERVICE_KEY, variable: \"SERVICE_KEY\" };\n if (env.REBASE_SERVICE_KEY) return { key: env.REBASE_SERVICE_KEY, variable: \"REBASE_SERVICE_KEY\" };\n return undefined;\n}\n\n/** At most one of these may be on a line. */\nfunction chosenCredential(flags: ProjectTargetFlags): \"token\" | \"session\" | \"anon\" | undefined {\n const picked = [\n flags[\"--token\"] !== undefined ? \"token\" : undefined,\n flags[\"--session\"] ? \"session\" : undefined,\n flags[\"--anon\"] ? \"anon\" : undefined\n ].filter((c): c is \"token\" | \"session\" | \"anon\" => c !== undefined);\n if (picked.length > 1) {\n throw new TargetError(\"--token, --session and --anon each pick the credential; give one of them.\", undefined, \"usage\");\n }\n return picked[0];\n}\n\n/**\n * Resolve a project command's target from its parsed flags.\n *\n * @throws TargetError with a hint and a code; the caller reports it.\n */\nexport async function resolveProjectTarget(flags: ProjectTargetFlags, options: ProjectTargetOptions): Promise<ProjectTarget> {\n const cloudRef = flags[\"--project\"]?.trim() || (flags[\"--cloud\"] ? \"\" : undefined);\n if (cloudRef !== undefined && flags[\"--url\"]) {\n throw new TargetError(\"--url names a server and --project/--cloud a Rebase Cloud project; give one of them.\", undefined, \"usage\");\n }\n const credential = chosenCredential(flags);\n if (cloudRef !== undefined) return resolveCloudTarget(cloudRef, credential, flags, options);\n return resolveServerTarget(credential, flags, options);\n}\n\nasync function resolveServerTarget(\n credential: \"token\" | \"session\" | \"anon\" | undefined,\n flags: ProjectTargetFlags,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n const projectRoot = findProjectRoot();\n let baseUrl: string;\n let label: string;\n if (flags[\"--url\"]) {\n baseUrl = normalizeOrigin(flags[\"--url\"]);\n label = baseUrl;\n } else {\n if (!projectRoot) {\n throw new TargetError(\n \"No server to send the request to: this is not a Rebase project, and the line names none.\",\n \"Pass --url <server> or --project <slug>, or run this inside a project.\",\n \"no_target\"\n );\n }\n const address = resolveBackendAddress(readEnvFile(projectRoot), projectRoot);\n if (address.url === null) throw new TargetError(\"No server to send the request to.\", address.reason, \"no_target\");\n const note = cloudTargetNote(address);\n if (note) process.stderr.write(chalk.yellow(` ⚠ ${note}\\n`));\n baseUrl = normalizeOrigin(address.url);\n label = address.source === \"running\" ? `${baseUrl} (rebase dev)` : baseUrl;\n }\n\n const wantsPerson = options.defaultCredential === \"person\";\n let bearer: () => Promise<string | undefined>;\n let used: TargetCredential;\n if (credential === \"anon\") {\n bearer = async () => undefined;\n used = \"none\";\n } else if (credential === \"token\") {\n const token = flags[\"--token\"] ?? \"\";\n if (!token.trim()) throw new TargetError(\"--token was given an empty value.\", undefined, \"usage\");\n bearer = async () => token;\n used = \"token\";\n } else if (credential === \"session\" || wantsPerson) {\n bearer = () => freshSessionToken(baseUrl);\n used = \"session\";\n } else {\n const found = projectServiceKey(projectRoot);\n if (!found) {\n throw new TargetError(\n `No credential for ${label}: REBASE_SERVICE_KEY is not in .env or the shell.`,\n \"`rebase \" + options.command + \"` sends the project's service key by default. Pass --token <bearer>, \"\n + \"--session (after `rebase auth login`) or --anon instead.\",\n \"no_credential\"\n );\n }\n bearer = async () => found.key;\n used = \"service-key\";\n }\n\n return {\n kind: \"server\",\n label,\n credential: used,\n baseUrl,\n bearer,\n async request(requestPath, requestOptions = {}) {\n return send(`${baseUrl}${requestPath}${queryString(requestOptions.query)}`, await bearer(), requestOptions, label);\n }\n };\n}\n\n/** `https://x.example/` and `x.example` both become `https://x.example`; a path is kept. */\nexport function normalizeOrigin(raw: string): string {\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n const local = /^(localhost|127\\.|\\[::1\\]|0\\.0\\.0\\.0)/i.test(trimmed);\n return `${local ? \"http\" : \"https\"}://${trimmed}`;\n}\n\nasync function resolveCloudTarget(\n ref: string,\n credential: \"token\" | \"session\" | \"anon\" | undefined,\n flags: ProjectTargetFlags,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n // Imported here, not at the top: the cloud context pulls in the credential\n // store and inquirer, which a local `rebase data query` never needs.\n const cloud = await import(\"../commands/cloud/context\");\n const link = cloud.readLink();\n const projectRef = ref || link?.projectId;\n if (!projectRef) {\n throw new TargetError(\n \"--cloud acts on the project this directory is linked to, and it is not linked.\",\n \"Pass --project <slug>, or run `rebase cloud link`.\",\n \"no_project\"\n );\n }\n // The control plane the cloud family would use here: REBASE_CLOUD_URL, the\n // link, the current context. `--url` is this command's server flag, so it\n // is never read as the control plane's.\n const cloudArgs = [\"node\", \"rebase\", \"--project\", projectRef];\n const { client, url } = await cloud.requireClient(cloudArgs);\n let projectId: string;\n try {\n projectId = await cloud.resolveProjectRef(projectRef, client);\n } catch (e) {\n throw new TargetError(`Rebase Cloud project ${projectRef} not found: ${errorText(e)}`, \"`rebase cloud projects list` shows the projects you can reach.\", \"not_found\");\n }\n const label = `cloud project ${projectRef}`;\n\n // Direct to the app's public address: with a bearer the line names, with\n // none, or with a platform token for the scopes the command needs.\n const direct = credential !== undefined || (options.platformScopes !== undefined && options.platformScopes.length > 0);\n if (direct) {\n const { resolveOrigin } = await import(\"../commands/cloud/debug\");\n const origin = await resolveOrigin(cloudArgs, client, url, projectId);\n let bearer: () => Promise<string | undefined>;\n let used: TargetCredential;\n if (credential === \"anon\") {\n bearer = async () => undefined;\n used = \"none\";\n } else if (credential === \"token\") {\n const token = flags[\"--token\"] ?? \"\";\n bearer = async () => token;\n used = \"token\";\n } else if (credential === \"session\") {\n bearer = () => freshSessionToken(origin);\n used = \"session\";\n } else {\n const { mintRuntimeToken } = await import(\"../commands/cloud/cron\");\n const minted = await mintRuntimeToken(client, projectId, [...(options.platformScopes ?? [])]);\n bearer = async () => minted.token;\n used = \"platform-token\";\n }\n return {\n kind: \"cloud\",\n label: `${label} (${origin})`,\n credential: used,\n baseUrl: origin,\n projectId,\n bearer,\n async request(requestPath, requestOptions = {}) {\n return send(`${origin}${requestPath}${queryString(requestOptions.query)}`, await bearer(), requestOptions, label);\n }\n };\n }\n\n const proxyBase = `${url.replace(/\\/+$/, \"\")}/api/functions/studio/${encodeURIComponent(projectId)}/proxy`;\n return {\n kind: \"cloud\",\n label,\n credential: \"studio-proxy\",\n baseUrl: proxyBase,\n projectId,\n bearer: () => cloud.freshAccessToken(client),\n async request(requestPath, requestOptions = {}) {\n const bearer = await cloud.freshAccessToken(client);\n const res = await send(`${proxyBase}${requestPath}${queryString(requestOptions.query)}`, bearer, requestOptions, label);\n await explainProxyRefusal(res, projectRef);\n return res;\n }\n };\n}\n\n/**\n * The Studio proxy's own refusals, in the words of what to do about them.\n *\n * The proxy answers 401/403 itself — before the app sees anything — when the\n * caller is not an owner or admin, when the token holds no `project:studio`,\n * or when the project's Studio switch is off; the app's own refusals come back\n * in its error envelope and are left to the caller. Read from a clone so the\n * caller still has the body.\n */\nasync function explainProxyRefusal(res: Response, projectRef: string): Promise<void> {\n if (res.status !== 401 && res.status !== 403) return;\n const body: unknown = await res.clone().json().catch(() => null);\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = typeof error?.message === \"string\" ? error.message : \"\";\n if (/Studio access is switched off/i.test(message)) {\n throw new TargetError(\n `Studio access is switched off for ${projectRef}, and this command reaches the app through the console's Studio proxy.`,\n `An organization owner or admin can turn it on: \\`rebase cloud settings set --studio on --project ${projectRef}\\`.`,\n \"studio_disabled\"\n );\n }\n if (error && typeof error.code === \"string\" && /^(forbidden|unauthorized|scope_missing)$/i.test(error.code)) {\n throw new TargetError(\n `The control plane refused the Studio proxy for ${projectRef}: ${message || error.code}`,\n \"It answers organization owners and admins signed in with `rebase cloud login`; a token needs the project:studio scope. \"\n + \"Pass --token <bearer> to call the app's public address with a credential of its own instead.\",\n \"proxy_refused\"\n );\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Reading answers\n ═══════════════════════════════════════════════════════════════ */\n\n/** The app's error envelope: `{ error: { code, message, details } }`. */\nexport interface ApiErrorBody {\n code?: string;\n message?: string;\n details?: unknown;\n}\n\nexport function apiErrorOf(body: unknown): ApiErrorBody | undefined {\n if (!isRecord(body) || !isRecord(body.error)) return undefined;\n const e = body.error;\n return {\n ...(typeof e.code === \"string\" ? { code: e.code } : {}),\n ...(typeof e.message === \"string\" ? { message: e.message } : {}),\n ...(e.details !== undefined ? { details: e.details } : {})\n };\n}\n\n/**\n * Read a JSON answer, or throw a {@link TargetError} carrying the app's own\n * code and message — and, on a 401, which credential was refused, since that\n * is the question the next command will be about.\n */\nexport async function readJson(res: Response, target: ProjectTarget, action: string): Promise<unknown> {\n const text = await res.text();\n let body: unknown = null;\n if (text) {\n try {\n body = JSON.parse(text);\n } catch {\n body = text;\n }\n }\n if (res.ok) return body;\n throw failureOf(res.status, body, target, action);\n}\n\n/** The refusal a non-2xx answer becomes. Exported for commands that read streams. */\nexport function failureOf(status: number, body: unknown, target: ProjectTarget, action: string): TargetError {\n const error = apiErrorOf(body);\n const what = error?.message ?? (typeof body === \"string\" && body.trim() ? body.trim().slice(0, 300) : `HTTP ${status}`);\n const code = error?.code ?? (status === 404 ? \"not_found\" : status === 401 ? \"unauthenticated\" : status === 403 ? \"forbidden\" : \"error\");\n let hint: string | undefined;\n if (status === 401) {\n hint = target.credential === \"service-key\"\n ? `${target.label} did not accept REBASE_SERVICE_KEY — is it this project's server?`\n : target.credential === \"session\"\n ? \"The stored session was refused; run `rebase auth login` again.\"\n : target.credential === \"none\" ? \"This route needs a credential; drop --anon.\" : undefined;\n } else if (status === 501 && error?.code) {\n hint = \"The server does not offer this here (see the message); a newer @rebasepro/server may.\";\n }\n return new TargetError(`${action} — ${code} (${status}): ${what}`, hint, code);\n}\n\n/** Lines that say why a server could not be reached — `rebase dev` not running, and where it would be. */\nexport function unreachableHint(target: ProjectTarget): string | undefined {\n if (target.kind !== \"server\") return undefined;\n return serverUnreachableHint(target.baseUrl).map(line => line.trim()).join(\" \");\n}\n","/**\n * What every project command shares besides its target: the output mode, the\n * help page, the parse refusal and the way a failed request is reported.\n *\n * The output contract is the cloud family's (`commands/cloud/context.ts`),\n * reused rather than copied: one JSON value on stdout when `--json` is given,\n * `REBASE_JSON=1` is set or stdout is not a terminal; everything else on\n * stderr; a refusal is `{ \"error\": { message, code, hint } }` and exit 1; a\n * destructive action refuses rather than prompts when nobody can answer.\n *\n * Help is the one difference: a project command's `--help` is the page a\n * person reads even when piped (`rebase data --help | less`), and JSON only\n * when `--json` asks for it.\n */\nimport {\n emit,\n fail,\n initOutputMode,\n isJsonMode,\n printGroupHelp,\n type GroupHelp,\n type HelpAction\n} from \"../commands/cloud/context\";\nimport { wantsHelp } from \"./args\";\nimport {\n PROJECT_TARGET_HELP,\n TargetError,\n readJson,\n resolveProjectTarget,\n unreachableHint,\n type ProjectTarget,\n type ProjectTargetFlags,\n type ProjectTargetOptions,\n type RequestOptions\n} from \"./project-target\";\n\nexport { emit, fail, isJsonMode, type HelpAction };\n\n/** Latch the output mode for this run. Call first, before anything prints. */\nexport function startProjectCommand(rawArgs: string[]): void {\n initOutputMode(rawArgs, { whenPiped: wantsHelp(rawArgs) ? \"human\" : \"json\" });\n}\n\n/** A project group's help page, with the target flags as its global options. */\nexport function printProjectHelp(page: Omit<GroupHelp, \"globalFlags\">): void {\n printGroupHelp({ ...page, globalFlags: PROJECT_TARGET_HELP });\n}\n\n/**\n * Run a parse, and report its refusal through {@link fail} — one JSON value\n * when piped — rather than as a throw, which `bin/rebase.js` prints as text.\n */\nexport function parsedLine<T>(parse: () => T): T {\n try {\n return parse();\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e), undefined, \"usage\");\n }\n}\n\n/** Report a {@link TargetError} through {@link fail}; rethrow anything else. */\nexport function reportTargetError(e: unknown, target?: ProjectTarget): never {\n if (e instanceof TargetError) {\n const hint = e.code === \"network_error\" && target ? (unreachableHint(target) ?? e.hint) : e.hint;\n fail(e.message, hint, e.code);\n }\n throw e;\n}\n\n/** Resolve the target, or end the command with why not. */\nexport async function projectTarget(\n flags: Readonly<Record<string, unknown>>,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n try {\n return await resolveProjectTarget(targetFlagsOf(flags), options);\n } catch (e) {\n reportTargetError(e);\n }\n}\n\n/** The target flags out of a command's parsed flags, whatever else its spec declares. */\nfunction targetFlagsOf(flags: Record<string, unknown>): ProjectTargetFlags {\n const str = (key: string): string | undefined => (typeof flags[key] === \"string\" ? String(flags[key]) : undefined);\n const bool = (key: string): boolean | undefined => (flags[key] === true ? true : undefined);\n return {\n \"--project\": str(\"--project\"),\n \"--cloud\": bool(\"--cloud\"),\n \"--url\": str(\"--url\"),\n \"--token\": str(\"--token\"),\n \"--session\": bool(\"--session\"),\n \"--anon\": bool(\"--anon\")\n };\n}\n\n/** Send one request and read its JSON answer, or end the command with the app's own refusal. */\nexport async function requestJson(\n target: ProjectTarget,\n path: string,\n action: string,\n options: RequestOptions = {}\n): Promise<unknown> {\n try {\n const res = await target.request(path, { timeoutMs: 60_000, ...options });\n return await readJson(res, target, action);\n } catch (e) {\n reportTargetError(e, target);\n }\n}\n\n/** Narrowing helpers for the answers commands read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function recordsOf(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nexport function stringOf(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : undefined;\n}\n\n/** A cell's text for a table: strings as they are, everything else as compact JSON. */\nexport function cellText(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,IAAa,uBAAuB;CAChC,aAAa;CACb,MAAM;CACN,WAAW;CACX,SAAS;CACT,WAAW;CACX,aAAa;CACb,UAAU;CACV,UAAU;CACV,SAAS;CACT,MAAM;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AgB,UAAU,OAA2C;CACjE,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,OAAO,QAAQ,IAAI,CAAC;AAC5D;AAEA,SAAgB,SAAS,OAAoC;CACzD,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI,KAAA;AAC3F;;AAGA,SAAgB,SAAS,OAAwB;CAC7C,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO,OAAO,KAAK;CAChF,OAAO,KAAK,UAAU,KAAK;AAC/B"}
|
|
1
|
+
{"version":3,"file":"project-command-5wM_bJQt.js","names":[],"sources":["../src/utils/project-target.ts","../src/utils/project-command.ts"],"sourcesContent":["/**\n * Which server a project command talks to, and as whom.\n *\n * Every command that acts on a running Rebase app — `rebase api`, `data`,\n * `users`, `cron`, `logs`, `functions`, `storage`, `api-keys`, `schema\n * reconcile` — resolves its target here, so they all accept the same flags,\n * refuse the same way, and never disagree about where the service key may go.\n *\n * ## Targets\n *\n * 1. `--project <slug>` (or `--cloud`, the project this directory is linked\n * to) — a Rebase Cloud project. The default transport is the console's\n * Studio proxy (`/api/functions/studio/<id>/proxy/*` on the control\n * plane): the CLI presents its `rebase cloud login` session there and the\n * control plane attaches the app's service key on its own side, so no\n * static secret ever reaches this machine. It answers an organization\n * owner or admin, on a project whose Studio switch is on — the gate the\n * console's Studio tab has. A command that only needs cron asks for a\n * platform token instead (see {@link ProjectTargetOptions.platformScopes}),\n * which any member with log access holds.\n * 2. `--url <server>` — a server the developer names.\n * 3. `REBASE_BASE_URL`, in the shell or in `.env`.\n * 4. The `rebase dev` this checkout is running (`.rebase/state.json`, while\n * the pid it names is alive).\n *\n * Nothing else: an address the CLI only guessed is one it would hand the\n * service key to without knowing whose server answers.\n *\n * ## Credentials, on a server target\n *\n * The service key from `.env` (`REBASE_SERVICE_KEY`, or the older\n * `SERVICE_KEY`; the shell's `REBASE_SERVICE_KEY` wins) unless the line says\n * otherwise: `--token <bearer>` sends that bearer (an `rk_` key, a user's\n * access token), `--session` sends the person session `rebase auth login`\n * stored for that server, and `--anon` sends nothing. On a cloud target the\n * same three flags skip the proxy and go to the app's public address directly.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport chalk from \"chalk\";\n\nimport { findProjectRoot, readEnvFile } from \"./project\";\nimport { cliUserAgent } from \"./version\";\nimport { serverUnreachableHint } from \"./dev-server\";\n\n/* ═══════════════════════════════════════════════════════════════\n Flags\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The flags every project command accepts, merged into its own spec.\n *\n * `--json` and `--yes` are here because the output mode and the confirmation\n * prompt are shared too (`commands/cloud/context.ts`): one JSON value on\n * stdout when piped or asked for, and a refusal rather than a prompt when\n * there is nobody to answer one.\n */\nexport const PROJECT_TARGET_FLAGS = {\n \"--project\": String,\n \"-p\": \"--project\",\n \"--cloud\": Boolean,\n \"--url\": String,\n \"--token\": String,\n \"--session\": Boolean,\n \"--anon\": Boolean,\n \"--json\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} as const;\n\n/** The same flags, as every project command's help page lists them. */\nexport const PROJECT_TARGET_HELP: Array<[string, string]> = [\n [\"--project, -p <slug>\", \"Act on a Rebase Cloud project, through the console's Studio proxy\"],\n [\"--cloud\", \"Act on the Rebase Cloud project this directory is linked to\"],\n [\"--url <server>\", \"Act on the server at this address (else REBASE_BASE_URL, then `rebase dev`)\"],\n [\"--token <bearer>\", \"Send this bearer instead of the service key (an rk_ key, a user's token)\"],\n [\"--session\", \"Send the session `rebase auth login` stored for this server\"],\n [\"--anon\", \"Send no credential at all\"],\n [\"--json\", \"Machine-readable output (also when piped, or REBASE_JSON=1)\"],\n [\"--yes, -y\", \"Skip confirmation prompts\"]\n];\n\n/** The values {@link PROJECT_TARGET_FLAGS} resolves to, as a command's parsed flags hold them. */\nexport type ProjectTargetFlags = {\n \"--project\"?: string;\n \"--cloud\"?: boolean;\n \"--url\"?: string;\n \"--token\"?: string;\n \"--session\"?: boolean;\n \"--anon\"?: boolean;\n};\n\n/* ═══════════════════════════════════════════════════════════════\n Where the local backend is\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Where this project's backend is — or why the CLI will not say.\n *\n * `configured` is an address the developer named; `running` is the one this\n * project's backend recorded when it bound, and is still serving on. There is\n * no third, guessed, answer.\n */\nexport type BackendAddress =\n | {\n url: string;\n source: \"configured\" | \"running\";\n /**\n * Set when the address came from `.env` and is the cloud project this\n * directory is linked to — which `rebase cloud init --claim` writes\n * there for the app and the SDK, not as a choice of where local\n * commands go. The command still goes there; {@link cloudTargetNote}\n * says so.\n */\n cloudProject?: string;\n }\n | { url: null; reason: string };\n\n/** Whether a process with this pid is alive and ours to signal. */\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n // ESRCH: gone. EPERM: alive, but another user's — not this project's backend.\n return false;\n }\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 * The address the service key may be sent to, from the project alone.\n *\n * In order: `REBASE_BASE_URL` in the shell or in `.env`, then the\n * `.rebase/state.json` this project's backend writes when it binds — and only\n * while the pid it names is alive, because a backend that was killed leaves\n * the file behind. `.env`'s `PORT` was once the fallback, and every scaffold\n * writes `PORT=3001`: with `rebase dev` stopped, the key went to whatever\n * listened on 3001.\n */\nexport function resolveBackendAddress(env: Record<string, string>, projectRoot: string): BackendAddress {\n const fromShell = process.env.REBASE_BASE_URL?.trim();\n const configured = fromShell || env.REBASE_BASE_URL?.trim();\n if (configured) {\n const cloudProject = fromShell ? undefined : linkedCloudProjectAt(projectRoot, configured);\n return cloudProject ? { url: configured, source: \"configured\", cloudProject } : { url: configured, source: \"configured\" };\n }\n\n const state = readBackendState(projectRoot);\n if (state && isAlive(state.pid)) return { url: state.url, source: \"running\" };\n\n const last = state ? ` The last one recorded here, at ${state.url} (pid ${state.pid}), has stopped.` : \"\";\n return {\n url: null,\n reason: `This project's server is not running, so the service key was not sent anywhere.${last} ` +\n \"Start it with `rebase dev`. If it runs some other way — `rebase start`, a container — \" +\n \"set REBASE_BASE_URL in .env to its address, or pass --url. For a Rebase Cloud project, pass --project <slug>.\"\n };\n}\n\n/** The slug of the cloud project `.rebase/cloud.json` links, when `url` is its address. */\nfunction linkedCloudProjectAt(projectRoot: string, url: string): string | undefined {\n const link = readJsonFile(path.join(projectRoot, \".rebase\", \"cloud.json\"));\n if (!isRecord(link) || link.mode === \"direct\" || typeof link.apiUrl !== \"string\") return undefined;\n const bare = (u: string) => u.trim().replace(/\\/+$/, \"\");\n if (bare(link.apiUrl) !== bare(url)) return undefined;\n if (typeof link.slug === \"string\" && link.slug) return link.slug;\n return typeof link.projectId === \"string\" && link.projectId ? link.projectId : undefined;\n}\n\n/**\n * What to say before sending a request to the address of a cloud project\n * `.env` names: it goes there, and that project does not take this\n * project's local service key.\n */\nexport function cloudTargetNote(address: BackendAddress): string | undefined {\n if (address.url === null || !address.cloudProject) return undefined;\n return `Sending this to ${address.url}: REBASE_BASE_URL in .env is the address of cloud project ${address.cloudProject} `\n + \"(`rebase cloud init --claim` writes it there for the app, the SDK and the MCP server), and that project does not \"\n + \"take this project's local service key. To reach it with your Cloud login, pass --project \"\n + `${address.cloudProject}; to reach the local backend, run the command with REBASE_BASE_URL set to it in the shell, `\n + \"e.g. REBASE_BASE_URL=http://localhost:3001.\";\n}\n\nfunction readJsonFile(file: string): unknown {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf-8\"));\n } catch {\n return null;\n }\n}\n\n/** What `.rebase/state.json` says about the backend that wrote it, or null. */\nfunction readBackendState(projectRoot: string): { url: string; pid: number } | null {\n const parsed = readJsonFile(path.join(projectRoot, \".rebase\", \"state.json\"));\n if (!isRecord(parsed) || typeof parsed.pid !== \"number\" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return null;\n const url = typeof parsed.baseUrl === \"string\" && parsed.baseUrl.trim()\n ? parsed.baseUrl.trim()\n : typeof parsed.port === \"number\" ? `http://localhost:${parsed.port}` : null;\n return url ? { url, pid: parsed.pid } : null;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Person sessions (`rebase auth login`)\n ═══════════════════════════════════════════════════════════════ */\n\n/** One person's session on one server, as `rebase auth login` stores it. */\nexport interface StoredSession {\n accessToken: string;\n refreshToken?: string;\n /** Epoch milliseconds. */\n expiresAt: number;\n email?: string;\n uid?: string;\n}\n\ninterface SessionsFile {\n sessions: Record<string, StoredSession>;\n}\n\n/**\n * `~/.rebase/sessions.json`: the person sessions `rebase auth login` keeps,\n * keyed by server origin. Never the project directory — a token there is one\n * `git add .` from a repository — and never the cloud credentials file, which\n * holds control-plane sessions a different command family manages.\n * `REBASE_SESSIONS_FILE` moves it, for tests.\n */\nexport function sessionsPath(): string {\n return process.env.REBASE_SESSIONS_FILE || path.join(os.homedir(), \".rebase\", \"sessions.json\");\n}\n\nfunction readSessions(): SessionsFile {\n const parsed = readJsonFile(sessionsPath());\n if (!isRecord(parsed) || !isRecord(parsed.sessions)) return { sessions: {} };\n const sessions: Record<string, StoredSession> = {};\n for (const [origin, value] of Object.entries(parsed.sessions)) {\n if (isRecord(value) && typeof value.accessToken === \"string\" && typeof value.expiresAt === \"number\") {\n sessions[origin] = {\n accessToken: value.accessToken,\n expiresAt: value.expiresAt,\n ...(typeof value.refreshToken === \"string\" ? { refreshToken: value.refreshToken } : {}),\n ...(typeof value.email === \"string\" ? { email: value.email } : {}),\n ...(typeof value.uid === \"string\" ? { uid: value.uid } : {})\n };\n }\n }\n return { sessions };\n}\n\n/** Write the file beside itself, then rename it over: a concurrent reader sees the old file or the new one. */\nfunction writeSessions(data: SessionsFile): void {\n const file = sessionsPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(temporary, JSON.stringify(data, null, 2), { mode: 0o600 });\n try {\n fs.chmodSync(temporary, 0o600);\n } catch {\n // best effort on platforms without chmod semantics\n }\n fs.renameSync(temporary, file);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\n/** The origin a session is filed under: scheme, host and port, no path. */\nexport function sessionKey(baseUrl: string): string {\n try {\n return new URL(baseUrl).origin;\n } catch {\n return baseUrl.replace(/\\/+$/, \"\");\n }\n}\n\nexport function storedSession(baseUrl: string): StoredSession | undefined {\n return readSessions().sessions[sessionKey(baseUrl)];\n}\n\nexport function saveSession(baseUrl: string, session: StoredSession): void {\n const data = readSessions();\n data.sessions[sessionKey(baseUrl)] = session;\n writeSessions(data);\n}\n\n/** Forget a server's session. Returns whether there was one. */\nexport function forgetSession(baseUrl: string): boolean {\n const data = readSessions();\n const key = sessionKey(baseUrl);\n if (!data.sessions[key]) return false;\n delete data.sessions[key];\n writeSessions(data);\n return true;\n}\n\n/** Two minutes of head-room before an access token is treated as expired. */\nconst SESSION_EXPIRY_BUFFER_MS = 120_000;\n\n/**\n * The session's access token, refreshed first when it is close to expiry —\n * through the server's own `POST /api/auth/refresh`, which rotates the refresh\n * token, so the new pair is written back.\n */\nasync function freshSessionToken(baseUrl: string): Promise<string> {\n const session = storedSession(baseUrl);\n if (!session) {\n throw new TargetError(\n `No session is stored for ${sessionKey(baseUrl)}.`,\n \"Sign in first with `rebase auth login` (it takes the same --url / --project flags).\",\n \"not_logged_in\"\n );\n }\n if (session.expiresAt > Date.now() + SESSION_EXPIRY_BUFFER_MS) return session.accessToken;\n if (!session.refreshToken) {\n throw new TargetError(`Your session for ${sessionKey(baseUrl)} has expired.`, \"Run `rebase auth login` again.\", \"session_expired\");\n }\n let res: Response;\n try {\n res = await fetch(`${baseUrl.replace(/\\/+$/, \"\")}/api/auth/refresh`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"User-Agent\": cliUserAgent() },\n body: JSON.stringify({ refreshToken: session.refreshToken })\n });\n } catch (e) {\n throw new TargetError(`Could not reach ${sessionKey(baseUrl)} to refresh your session: ${errorText(e)}`, undefined, \"network_error\");\n }\n const body: unknown = await res.json().catch(() => null);\n const tokens = sessionTokensOf(body);\n if (!res.ok || !tokens) {\n forgetSession(baseUrl);\n throw new TargetError(`Your session for ${sessionKey(baseUrl)} has expired.`, \"Run `rebase auth login` again.\", \"session_expired\");\n }\n saveSession(baseUrl, { ...session, ...tokens });\n return tokens.accessToken;\n}\n\n/**\n * The token pair out of an auth response — `{ tokens: { accessToken,\n * refreshToken, accessTokenExpiresAt } }`, the shape login, refresh and the\n * device grant all answer.\n */\nexport function sessionTokensOf(body: unknown): Pick<StoredSession, \"accessToken\" | \"refreshToken\" | \"expiresAt\"> | undefined {\n if (!isRecord(body)) return undefined;\n const tokens = isRecord(body.tokens) ? body.tokens : body;\n if (typeof tokens.accessToken !== \"string\" || !tokens.accessToken) return undefined;\n const expiresRaw = tokens.accessTokenExpiresAt ?? tokens.expiresAt;\n const expiresAt = typeof expiresRaw === \"number\"\n ? (expiresRaw < 1e12 ? expiresRaw * 1000 : expiresRaw)\n : typeof expiresRaw === \"string\" ? Date.parse(expiresRaw) : Date.now() + 15 * 60_000;\n return {\n accessToken: tokens.accessToken,\n ...(typeof tokens.refreshToken === \"string\" ? { refreshToken: tokens.refreshToken } : {}),\n expiresAt: Number.isFinite(expiresAt) ? expiresAt : Date.now() + 15 * 60_000\n };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n The target\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * A refusal while resolving or reaching a target: what happened, what to do\n * about it, and a stable code. Commands report it through the shared `fail`,\n * so it is one JSON value when piped.\n */\nexport class TargetError extends Error {\n constructor(message: string, readonly hint?: string, readonly code: string = \"error\") {\n super(message);\n this.name = \"TargetError\";\n }\n}\n\n/** How a request reaches the app, and as whom — for messages and `--json` output. */\nexport type TargetCredential =\n | \"service-key\"\n | \"token\"\n | \"session\"\n | \"none\"\n | \"studio-proxy\"\n | \"platform-token\";\n\nexport interface RequestOptions {\n method?: string;\n /** Query parameters. Repeated values (`string[]`) become repeated keys. */\n query?: Record<string, string | number | boolean | readonly string[] | undefined>;\n /** A JSON body, stringified here. */\n json?: unknown;\n /** A raw body, sent as it is. */\n body?: BodyInit;\n headers?: Record<string, string>;\n /** Abort after this many milliseconds; unset means no limit (a stream, an upload). */\n timeoutMs?: number;\n}\n\nexport interface ProjectTarget {\n kind: \"server\" | \"cloud\";\n /** Where requests go, for messages: `http://localhost:3001 (rebase dev)`, `cloud project acme`. */\n label: string;\n credential: TargetCredential;\n /** The app's own origin when it is reached directly; for the Studio proxy, the proxy's base. */\n baseUrl: string;\n /** The cloud project id, on a cloud target. */\n projectId?: string;\n /** Send a request to `path` on the app (`/api/admin/users`), with the credential. */\n request(path: string, options?: RequestOptions): Promise<Response>;\n /**\n * The bearer a request carries, for the clients that open their own\n * connection (the SDK's realtime socket). On the Studio proxy this is the\n * control-plane session, which only the proxy accepts.\n */\n bearer(): Promise<string | undefined>;\n}\n\nexport interface ProjectTargetOptions {\n /** Names the command in messages: `data query`. */\n command: string;\n /**\n * On a cloud target, ask the control plane for a platform token holding\n * these scopes and call the app directly, instead of the Studio proxy.\n * Only scopes the control plane issues (`cron:read`, `cron:write`), and\n * only when no credential flag was given.\n */\n platformScopes?: readonly string[];\n /**\n * The credential the command needs when the line names none. `person`:\n * the session `rebase auth login` stored (the RLS simulator and personal\n * keys refuse machines). Default: the service key on a server target.\n */\n defaultCredential?: \"service-key\" | \"person\";\n}\n\n/** One line of query string out of {@link RequestOptions.query}. */\nexport function queryString(query: RequestOptions[\"query\"]): string {\n if (!query) return \"\";\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) for (const item of value) params.append(key, String(item));\n else params.append(key, String(value));\n }\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nfunction errorText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * A `fetch` that sends one request with a bearer, refusing redirects: a 3xx\n * that crosses origins drops `Authorization` in some runtimes and keeps it in\n * others, and neither is what the caller meant.\n */\nasync function send(url: string, bearer: string | undefined, options: RequestOptions, label: string): Promise<Response> {\n const headers: Record<string, string> = {\n \"User-Agent\": cliUserAgent(),\n Accept: \"application/json\",\n ...(options.headers ?? {})\n };\n if (bearer) headers.Authorization = `Bearer ${bearer}`;\n let body = options.body;\n if (options.json !== undefined) {\n body = JSON.stringify(options.json);\n headers[\"Content-Type\"] = \"application/json\";\n }\n const controller = options.timeoutMs ? new AbortController() : undefined;\n const timer = controller ? setTimeout(() => controller.abort(), options.timeoutMs) : undefined;\n // `duplex` is required by undici for a streamed request body, and is not\n // in the DOM lib's RequestInit yet.\n const init: RequestInit & { duplex?: \"half\" } = {\n method: options.method ?? \"GET\",\n headers,\n body,\n redirect: \"manual\",\n signal: controller?.signal\n };\n if (body instanceof ReadableStream) init.duplex = \"half\";\n try {\n return await fetch(url, init);\n } catch (e) {\n if (controller?.signal.aborted) {\n throw new TargetError(`${label} did not answer within ${Math.round((options.timeoutMs ?? 0) / 1000)}s.`, undefined, \"timeout\");\n }\n throw new TargetError(`Could not reach ${label}: ${errorText(e)}`, undefined, \"network_error\");\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * The service key this project's `.env` holds, and the variable it came from.\n * The shell's `REBASE_SERVICE_KEY` wins over the file.\n */\nexport function projectServiceKey(projectRoot: string | null): { key: string; variable: string } | undefined {\n const shell = process.env.REBASE_SERVICE_KEY?.trim();\n if (shell) return { key: shell, variable: \"REBASE_SERVICE_KEY\" };\n if (!projectRoot) return undefined;\n const env = readEnvFile(projectRoot);\n if (env.SERVICE_KEY) return { key: env.SERVICE_KEY, variable: \"SERVICE_KEY\" };\n if (env.REBASE_SERVICE_KEY) return { key: env.REBASE_SERVICE_KEY, variable: \"REBASE_SERVICE_KEY\" };\n return undefined;\n}\n\n/** At most one of these may be on a line. */\nfunction chosenCredential(flags: ProjectTargetFlags): \"token\" | \"session\" | \"anon\" | undefined {\n const picked = [\n flags[\"--token\"] !== undefined ? \"token\" : undefined,\n flags[\"--session\"] ? \"session\" : undefined,\n flags[\"--anon\"] ? \"anon\" : undefined\n ].filter((c): c is \"token\" | \"session\" | \"anon\" => c !== undefined);\n if (picked.length > 1) {\n throw new TargetError(\"--token, --session and --anon each pick the credential; give one of them.\", undefined, \"usage\");\n }\n return picked[0];\n}\n\n/**\n * Resolve a project command's target from its parsed flags.\n *\n * @throws TargetError with a hint and a code; the caller reports it.\n */\nexport async function resolveProjectTarget(flags: ProjectTargetFlags, options: ProjectTargetOptions): Promise<ProjectTarget> {\n const cloudRef = flags[\"--project\"]?.trim() || (flags[\"--cloud\"] ? \"\" : undefined);\n if (cloudRef !== undefined && flags[\"--url\"]) {\n throw new TargetError(\"--url names a server and --project/--cloud a Rebase Cloud project; give one of them.\", undefined, \"usage\");\n }\n const credential = chosenCredential(flags);\n if (cloudRef !== undefined) return resolveCloudTarget(cloudRef, credential, flags, options);\n return resolveServerTarget(credential, flags, options);\n}\n\nasync function resolveServerTarget(\n credential: \"token\" | \"session\" | \"anon\" | undefined,\n flags: ProjectTargetFlags,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n const projectRoot = findProjectRoot();\n let baseUrl: string;\n let label: string;\n if (flags[\"--url\"]) {\n baseUrl = normalizeOrigin(flags[\"--url\"]);\n label = baseUrl;\n } else {\n if (!projectRoot) {\n throw new TargetError(\n \"No server to send the request to: this is not a Rebase project, and the line names none.\",\n \"Pass --url <server> or --project <slug>, or run this inside a project.\",\n \"no_target\"\n );\n }\n const address = resolveBackendAddress(readEnvFile(projectRoot), projectRoot);\n if (address.url === null) throw new TargetError(\"No server to send the request to.\", address.reason, \"no_target\");\n const note = cloudTargetNote(address);\n if (note) process.stderr.write(chalk.yellow(` ⚠ ${note}\\n`));\n baseUrl = normalizeOrigin(address.url);\n label = address.source === \"running\" ? `${baseUrl} (rebase dev)` : baseUrl;\n }\n\n const wantsPerson = options.defaultCredential === \"person\";\n let bearer: () => Promise<string | undefined>;\n let used: TargetCredential;\n if (credential === \"anon\") {\n bearer = async () => undefined;\n used = \"none\";\n } else if (credential === \"token\") {\n const token = flags[\"--token\"] ?? \"\";\n if (!token.trim()) throw new TargetError(\"--token was given an empty value.\", undefined, \"usage\");\n bearer = async () => token;\n used = \"token\";\n } else if (credential === \"session\" || wantsPerson) {\n bearer = () => freshSessionToken(baseUrl);\n used = \"session\";\n } else {\n const found = projectServiceKey(projectRoot);\n if (!found) {\n throw new TargetError(\n `No credential for ${label}: REBASE_SERVICE_KEY is not in .env or the shell.`,\n \"`rebase \" + options.command + \"` sends the project's service key by default. Pass --token <bearer>, \"\n + \"--session (after `rebase auth login`) or --anon instead.\",\n \"no_credential\"\n );\n }\n bearer = async () => found.key;\n used = \"service-key\";\n }\n\n return {\n kind: \"server\",\n label,\n credential: used,\n baseUrl,\n bearer,\n async request(requestPath, requestOptions = {}) {\n return send(`${baseUrl}${requestPath}${queryString(requestOptions.query)}`, await bearer(), requestOptions, label);\n }\n };\n}\n\n/** `https://x.example/` and `x.example` both become `https://x.example`; a path is kept. */\nexport function normalizeOrigin(raw: string): string {\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n const local = /^(localhost|127\\.|\\[::1\\]|0\\.0\\.0\\.0)/i.test(trimmed);\n return `${local ? \"http\" : \"https\"}://${trimmed}`;\n}\n\nasync function resolveCloudTarget(\n ref: string,\n credential: \"token\" | \"session\" | \"anon\" | undefined,\n flags: ProjectTargetFlags,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n // Imported here, not at the top: the cloud context pulls in the credential\n // store and inquirer, which a local `rebase data query` never needs.\n const cloud = await import(\"../commands/cloud/context\");\n const link = cloud.readLink();\n const projectRef = ref || link?.projectId;\n if (!projectRef) {\n throw new TargetError(\n \"--cloud acts on the project this directory is linked to, and it is not linked.\",\n \"Pass --project <slug>, or run `rebase cloud link`.\",\n \"no_project\"\n );\n }\n // The control plane the cloud family would use here: REBASE_CLOUD_URL, the\n // link, the current context. `--url` is this command's server flag, so it\n // is never read as the control plane's.\n const cloudArgs = [\"node\", \"rebase\", \"--project\", projectRef];\n const { client, url } = await cloud.requireClient(cloudArgs);\n let projectId: string;\n try {\n projectId = await cloud.resolveProjectRef(projectRef, client);\n } catch (e) {\n throw new TargetError(`Rebase Cloud project ${projectRef} not found: ${errorText(e)}`, \"`rebase cloud projects list` shows the projects you can reach.\", \"not_found\");\n }\n const label = `cloud project ${projectRef}`;\n\n // Direct to the app's public address: with a bearer the line names, with\n // none, or with a platform token for the scopes the command needs.\n const direct = credential !== undefined || (options.platformScopes !== undefined && options.platformScopes.length > 0);\n if (direct) {\n const { resolveOrigin } = await import(\"../commands/cloud/debug\");\n const origin = await resolveOrigin(cloudArgs, client, url, projectId);\n let bearer: () => Promise<string | undefined>;\n let used: TargetCredential;\n if (credential === \"anon\") {\n bearer = async () => undefined;\n used = \"none\";\n } else if (credential === \"token\") {\n const token = flags[\"--token\"] ?? \"\";\n bearer = async () => token;\n used = \"token\";\n } else if (credential === \"session\") {\n bearer = () => freshSessionToken(origin);\n used = \"session\";\n } else {\n const { mintRuntimeToken } = await import(\"../commands/cloud/cron\");\n const minted = await mintRuntimeToken(client, projectId, [...(options.platformScopes ?? [])]);\n bearer = async () => minted.token;\n used = \"platform-token\";\n }\n return {\n kind: \"cloud\",\n label: `${label} (${origin})`,\n credential: used,\n baseUrl: origin,\n projectId,\n bearer,\n async request(requestPath, requestOptions = {}) {\n return send(`${origin}${requestPath}${queryString(requestOptions.query)}`, await bearer(), requestOptions, label);\n }\n };\n }\n\n const proxyBase = `${url.replace(/\\/+$/, \"\")}/api/functions/studio/${encodeURIComponent(projectId)}/proxy`;\n return {\n kind: \"cloud\",\n label,\n credential: \"studio-proxy\",\n baseUrl: proxyBase,\n projectId,\n bearer: () => cloud.freshAccessToken(client),\n async request(requestPath, requestOptions = {}) {\n const bearer = await cloud.freshAccessToken(client);\n const res = await send(`${proxyBase}${requestPath}${queryString(requestOptions.query)}`, bearer, requestOptions, label);\n await explainProxyRefusal(res, projectRef);\n return res;\n }\n };\n}\n\n/**\n * The Studio proxy's own refusals, in the words of what to do about them.\n *\n * The proxy answers 401/403 itself — before the app sees anything — when the\n * caller is not an owner or admin, when the token holds no `project:studio`,\n * or when the project's Studio switch is off; the app's own refusals come back\n * in its error envelope and are left to the caller. Read from a clone so the\n * caller still has the body.\n */\nasync function explainProxyRefusal(res: Response, projectRef: string): Promise<void> {\n if (res.status !== 401 && res.status !== 403) return;\n const body: unknown = await res.clone().json().catch(() => null);\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = typeof error?.message === \"string\" ? error.message : \"\";\n if (/Studio access is switched off/i.test(message)) {\n throw new TargetError(\n `Studio access is switched off for ${projectRef}, and this command reaches the app through the console's Studio proxy.`,\n `An organization owner or admin can turn it on: \\`rebase cloud settings set --studio on --project ${projectRef}\\`.`,\n \"studio_disabled\"\n );\n }\n if (error && typeof error.code === \"string\" && /^(forbidden|unauthorized|scope_missing)$/i.test(error.code)) {\n throw new TargetError(\n `The control plane refused the Studio proxy for ${projectRef}: ${message || error.code}`,\n \"It answers organization owners and admins signed in with `rebase cloud login`; a token needs the project:studio scope. \"\n + \"Pass --token <bearer> to call the app's public address with a credential of its own instead.\",\n \"proxy_refused\"\n );\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Reading answers\n ═══════════════════════════════════════════════════════════════ */\n\n/** The app's error envelope: `{ error: { code, message, details } }`. */\nexport interface ApiErrorBody {\n code?: string;\n message?: string;\n details?: unknown;\n}\n\nexport function apiErrorOf(body: unknown): ApiErrorBody | undefined {\n if (!isRecord(body) || !isRecord(body.error)) return undefined;\n const e = body.error;\n return {\n ...(typeof e.code === \"string\" ? { code: e.code } : {}),\n ...(typeof e.message === \"string\" ? { message: e.message } : {}),\n ...(e.details !== undefined ? { details: e.details } : {})\n };\n}\n\n/**\n * Read a JSON answer, or throw a {@link TargetError} carrying the app's own\n * code and message — and, on a 401, which credential was refused, since that\n * is the question the next command will be about.\n */\nexport async function readJson(res: Response, target: ProjectTarget, action: string): Promise<unknown> {\n const text = await res.text();\n let body: unknown = null;\n if (text) {\n try {\n body = JSON.parse(text);\n } catch {\n body = text;\n }\n }\n if (res.ok) return body;\n throw failureOf(res.status, body, target, action);\n}\n\n/** The refusal a non-2xx answer becomes. Exported for commands that read streams. */\nexport function failureOf(status: number, body: unknown, target: ProjectTarget, action: string): TargetError {\n const error = apiErrorOf(body);\n const what = error?.message ?? (typeof body === \"string\" && body.trim() ? body.trim().slice(0, 300) : `HTTP ${status}`);\n const code = error?.code ?? (status === 404 ? \"not_found\" : status === 401 ? \"unauthenticated\" : status === 403 ? \"forbidden\" : \"error\");\n let hint: string | undefined;\n if (status === 401) {\n hint = target.credential === \"service-key\"\n ? `${target.label} did not accept REBASE_SERVICE_KEY — is it this project's server?`\n : target.credential === \"session\"\n ? \"The stored session was refused; run `rebase auth login` again.\"\n : target.credential === \"none\" ? \"This route needs a credential; drop --anon.\" : undefined;\n } else if (status === 501 && error?.code) {\n hint = \"The server does not offer this here (see the message); a newer @rebasepro/server may.\";\n }\n return new TargetError(`${action} — ${code} (${status}): ${what}`, hint, code);\n}\n\n/** Lines that say why a server could not be reached — `rebase dev` not running, and where it would be. */\nexport function unreachableHint(target: ProjectTarget): string | undefined {\n if (target.kind !== \"server\") return undefined;\n return serverUnreachableHint(target.baseUrl).map(line => line.trim()).join(\" \");\n}\n","/**\n * What every project command shares besides its target: the output mode, the\n * help page, the parse refusal and the way a failed request is reported.\n *\n * The output contract is the cloud family's (`commands/cloud/context.ts`),\n * reused rather than copied: one JSON value on stdout when `--json` is given,\n * `REBASE_JSON=1` is set or stdout is not a terminal; everything else on\n * stderr; a refusal is `{ \"error\": { message, code, hint } }` and exit 1; a\n * destructive action refuses rather than prompts when nobody can answer.\n *\n * Help is the one difference: a project command's `--help` is the page a\n * person reads even when piped (`rebase data --help | less`), and JSON only\n * when `--json` asks for it.\n */\nimport {\n emit,\n fail,\n initOutputMode,\n isJsonMode,\n printGroupHelp,\n type GroupHelp,\n type HelpAction\n} from \"../commands/cloud/context\";\nimport { wantsHelp } from \"./args\";\nimport {\n PROJECT_TARGET_HELP,\n TargetError,\n readJson,\n resolveProjectTarget,\n unreachableHint,\n type ProjectTarget,\n type ProjectTargetFlags,\n type ProjectTargetOptions,\n type RequestOptions\n} from \"./project-target\";\n\nexport { emit, fail, isJsonMode, type HelpAction };\n\n/** Latch the output mode for this run. Call first, before anything prints. */\nexport function startProjectCommand(rawArgs: string[]): void {\n initOutputMode(rawArgs, { whenPiped: wantsHelp(rawArgs) ? \"human\" : \"json\" });\n}\n\n/** A project group's help page, with the target flags as its global options. */\nexport function printProjectHelp(page: Omit<GroupHelp, \"globalFlags\">): void {\n printGroupHelp({ ...page, globalFlags: PROJECT_TARGET_HELP });\n}\n\n/**\n * Run a parse, and report its refusal through {@link fail} — one JSON value\n * when piped — rather than as a throw, which `bin/rebase.js` prints as text.\n */\nexport function parsedLine<T>(parse: () => T): T {\n try {\n return parse();\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e), undefined, \"usage\");\n }\n}\n\n/** Report a {@link TargetError} through {@link fail}; rethrow anything else. */\nexport function reportTargetError(e: unknown, target?: ProjectTarget): never {\n if (e instanceof TargetError) {\n const hint = e.code === \"network_error\" && target ? (unreachableHint(target) ?? e.hint) : e.hint;\n fail(e.message, hint, e.code);\n }\n throw e;\n}\n\n/** Resolve the target, or end the command with why not. */\nexport async function projectTarget(\n flags: Readonly<Record<string, unknown>>,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n try {\n return await resolveProjectTarget(targetFlagsOf(flags), options);\n } catch (e) {\n reportTargetError(e);\n }\n}\n\n/** The target flags out of a command's parsed flags, whatever else its spec declares. */\nfunction targetFlagsOf(flags: Record<string, unknown>): ProjectTargetFlags {\n const str = (key: string): string | undefined => (typeof flags[key] === \"string\" ? String(flags[key]) : undefined);\n const bool = (key: string): boolean | undefined => (flags[key] === true ? true : undefined);\n return {\n \"--project\": str(\"--project\"),\n \"--cloud\": bool(\"--cloud\"),\n \"--url\": str(\"--url\"),\n \"--token\": str(\"--token\"),\n \"--session\": bool(\"--session\"),\n \"--anon\": bool(\"--anon\")\n };\n}\n\n/** Send one request and read its JSON answer, or end the command with the app's own refusal. */\nexport async function requestJson(\n target: ProjectTarget,\n path: string,\n action: string,\n options: RequestOptions = {}\n): Promise<unknown> {\n try {\n const res = await target.request(path, { timeoutMs: 60_000, ...options });\n return await readJson(res, target, action);\n } catch (e) {\n reportTargetError(e, target);\n }\n}\n\n/** Narrowing helpers for the answers commands read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function recordsOf(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nexport function stringOf(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : undefined;\n}\n\n/** A cell's text for a table: strings as they are, everything else as compact JSON. */\nexport function cellText(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,IAAa,uBAAuB;CAChC,aAAa;CACb,MAAM;CACN,WAAW;CACX,SAAS;CACT,WAAW;CACX,aAAa;CACb,UAAU;CACV,UAAU;CACV,SAAS;CACT,MAAM;AACV;;AAGA,IAAa,sBAA+C;CACxD,CAAC,wBAAwB,mEAAmE;CAC5F,CAAC,WAAW,6DAA6D;CACzE,CAAC,kBAAkB,6EAA6E;CAChG,CAAC,oBAAoB,0EAA0E;CAC/F,CAAC,aAAa,6DAA6D;CAC3E,CAAC,UAAU,2B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AI,KAAA;AAC3F;;AAGA,SAAgB,SAAS,OAAwB;CAC7C,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO,OAAO,KAAK;CAChF,OAAO,KAAK,UAAU,KAAK;AAC/B"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as wantsHelp, n as parseCommandArgs } from "./args-DHyrshtI.js";
|
|
2
|
-
import { i as failAsJson, p as requireProjectRoot } from "./project-
|
|
3
|
-
import { _ as findBackendApp, b as loadManifest, l as ManifestError } from "./manifest-
|
|
4
|
-
import { a as projectResourceGraph, l as writeResourceGraphFile, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-
|
|
2
|
+
import { i as failAsJson, p as requireProjectRoot } from "./project-CQ5nKddJ.js";
|
|
3
|
+
import { _ as findBackendApp, b as loadManifest, l as ManifestError } from "./manifest-D6B4LA8x.js";
|
|
4
|
+
import { a as projectResourceGraph, l as writeResourceGraphFile, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-BU5kvcOP.js";
|
|
5
5
|
import chalk from "chalk";
|
|
6
6
|
import path from "path";
|
|
7
7
|
import { declaredSubscriptions } from "@rebasepro/types";
|
|
@@ -180,4 +180,4 @@ async function resourcesCommand(rawArgs) {
|
|
|
180
180
|
//#endregion
|
|
181
181
|
export { resourcesCommand };
|
|
182
182
|
|
|
183
|
-
//# sourceMappingURL=resources-
|
|
183
|
+
//# sourceMappingURL=resources-ecA0MEjy.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources-CE6BeL94.js","names":[],"sources":["../src/commands/resources.ts"],"sourcesContent":["/**\n * CLI command: rebase resources\n *\n * Shows what a project declares, and keeps the committed graph honest.\n *\n * The graph is generated, so it can drift the moment somebody adds a bucket and\n * does not regenerate. Drift here is not cosmetic: the committed file is what a\n * host reads to decide what to provision, so a stale one means the console\n * offers a project one set of resources while the runtime asks for another.\n * `--check` is the gate that makes that impossible to land.\n */\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport { failAsJson, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError } from \"../manifest\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport {\n RESOURCE_GRAPH_FILENAME,\n deriveOptionsFor, deriveResourceGraph,\n projectResourceGraph,\n readResourceGraphFile,\n serializeResourceGraph,\n writeResourceGraphFile,\n type ProjectedResource\n} from \"../resources/derive\";\nimport { declaredSubscriptions, type RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase resources\")} — what this project needs\n\n ${chalk.blue(\"rebase resources\")} List them, declared and implicit\n ${chalk.blue(\"rebase resources --write\")} Regenerate ${RESOURCE_GRAPH_FILENAME}\n ${chalk.blue(\"rebase resources --check\")} Fail if the committed graph is stale\n ${chalk.blue(\"rebase resources --json\")} The same set, machine-readable; with --check or --write,\n their result too (a failed check is an error envelope, exit 1)\n\nA resource is declared in config code — ${chalk.gray('database(\"analytics\"), bucket(\"media\"), topic(\"signups\")')} —\nand never in ${RESOURCE_GRAPH_FILENAME}, which is generated from those declarations so a host\ncan read what a project needs without building it. A backend also has a default\ndatabase and a default storage source nobody declared; both are listed here,\nmarked ${chalk.gray(\"implicit\")}, and neither is written to that file — the host supplies them.\n`);\n}\n\n/**\n * Render the projection the way somebody reads it: grouped by kind, key first.\n *\n * The projection, not the raw graph. `rebase status` has always included the\n * implicit default database and bucket and this listing did not, so the two\n * commands answered \"what does this project need\" differently on the same stock\n * scaffold. There is no \"no resources declared\" case any more: a backend has a\n * database and a storage source whether or not anyone wrote them down.\n */\nfunction print(resources: ProjectedResource[]): void {\n // Infrastructure first, then code: what needs binding is what a reader\n // is here to check.\n const order = [\"database\", \"bucket\", \"topic\", \"queue\", \"cron\", \"function\"];\n const kinds = [...new Set(resources.map(r => r.kind))]\n .sort((a, b) => (order.indexOf(a) === -1 ? 99 : order.indexOf(a)) - (order.indexOf(b) === -1 ? 99 : order.indexOf(b)));\n for (const kind of kinds) {\n console.log(`\\n ${chalk.bold(kind)}`);\n for (const r of resources.filter(x => x.kind === kind)) {\n const bits: string[] = [];\n if (kind === \"cron\") {\n bits.push(chalk.cyan(String(r.options.schedule)));\n bits.push(chalk.gray(r.options.timezone ? String(r.options.timezone) : \"local time\"));\n } else if (kind === \"function\") {\n bits.push(chalk.gray(String(r.options.file ?? \"\")));\n if (r.options.portable === false) bits.push(chalk.yellow(\"node-only\"));\n } else {\n bits.push(chalk.gray(r.engine));\n if (r.transport !== \"server\") bits.push(chalk.yellow(r.transport));\n for (const [k, v] of Object.entries(r.options)) bits.push(chalk.gray(`${k}=${String(v)}`));\n }\n // Marked, not hidden: a declared resource is recorded in\n // `rebase.resources.json` for a host to provision, and an implicit\n // one is a default the runtime supplies regardless.\n if (r.implicit) bits.push(chalk.gray(\"implicit\"));\n console.log(` ${r.key.padEnd(24)} ${bits.join(\" · \")}`);\n if (kind === \"topic\") {\n for (const sub of declaredSubscriptions(r.key)) {\n console.log(` ${chalk.gray(\"→\")} ${sub.name}`);\n }\n }\n if (r.usedBy && r.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(r.usedBy.join(\", \"))}`);\n }\n }\n }\n console.log(\"\");\n}\n\nexport async function resourcesCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: {\n \"--write\": Boolean,\n \"--check\": Boolean,\n \"--json\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"resources\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, for the reason in `failAsJson`:\n // `--json` is a promise about stdout, and a promise kept on one exit of a\n // command and broken on the next is not one.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backendApp: RebaseBackendAppConfig;\n try {\n const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (!backend) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backendApp = backend.app;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The projection, so this and `rebase status --json` describe the same\n // set. `version` is kept so a reader of either can tell them apart from a\n // future shape. `--check` and `--write` add what they did to it: `--json`\n // changes how the answer is printed, never which question is answered — it\n // used to return here, so `--check --json` exited 0 on any drift and\n // `--write --json` wrote nothing.\n const projection = () => ({ version: graph.version, resources: projectResourceGraph(graph) });\n\n if (flags[\"--check\"]) {\n const committed = readResourceGraphFile(projectRoot);\n const expected = serializeResourceGraph(graph);\n // Declaring nothing and having no file is a consistent state, not a\n // stale one. The file records declarations; a project with none has\n // nothing to record, and its default database and bucket are implicit\n // by design — that is the overwhelmingly common project and it must not\n // be required to commit an empty file saying so.\n //\n // This mattered the moment the check was put in a gate: it would have\n // failed this repository's own reference app, which declares nothing,\n // and every scaffolded project until someone declared a second bucket.\n const status = committed === expected\n ? \"current\"\n : committed === null && graph.resources.length === 0 ? \"nothing-declared\" : null;\n\n if (status !== null) {\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), check: { file: RESOURCE_GRAPH_FILENAME, status } }, null, 2));\n return;\n }\n console.log(status === \"current\"\n ? chalk.green(`✓ ${RESOURCE_GRAPH_FILENAME} matches the declarations.`)\n : chalk.gray(\"✓ Nothing declared, so there is nothing to record.\"));\n return;\n }\n\n const state = committed === null ? \"missing\" : \"stale\";\n if (asJson) {\n failAsJson(\n `${RESOURCE_GRAPH_FILENAME} is ${state}.`,\n `resource_graph_${state}`,\n \"Regenerate it with `rebase resources --write`, and commit it.\"\n );\n }\n console.error(chalk.red(`\\n✗ ${RESOURCE_GRAPH_FILENAME} is ${state}.\\n`));\n console.error(\n \" A host reads this file to decide what to provision, so a stale one means the\\n\" +\n \" console offers one set of resources while the runtime asks for another.\\n\"\n );\n console.error(` Regenerate it: ${chalk.blue(\"rebase resources --write\")}\\n`);\n process.exitCode = 1;\n return;\n }\n\n if (flags[\"--write\"]) {\n const { changed, file } = writeResourceGraphFile(projectRoot, graph);\n const relative = path.relative(projectRoot, file);\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), written: { file: relative, changed } }, null, 2));\n return;\n }\n console.log(changed\n ? chalk.green(`✓ Wrote ${relative}`)\n : chalk.gray(`${relative} already matched the declarations.`));\n return;\n }\n\n if (asJson) {\n console.log(JSON.stringify(projection(), null, 2));\n return;\n }\n\n print(projectResourceGraph(graph));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,SAAS,QAAc;CACnB,QAAQ,IAAI;EACd,MAAM,KAAK,kBAAkB,EAAE;;IAE7B,MAAM,KAA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AEA,MAAM,QAAQ,cAAc,OAAO,YAAY;EAC/C,IAAI,QACA,WACI,GAAG,wBAAwB,MAAM,MAAM,IACvC,kBAAkB,SAClB,+DACJ;EAEJ,QAAQ,MAAM,MAAM,IAAI,OAAO,wBAAwB,MAAM,MAAM,IAAI,CAAC;EACxE,QAAQ,MACJ,6JAEJ;EACA,QAAQ,MAAM,qBAAqB,MAAM,KAAK,0BAA0B,EAAE,GAAG;EAC7E,QAAQ,WAAW;EACnB;CACJ;CAEA,IAAI,MAAM,YAAY;EAClB,MAAM,EAAE,SAAS,SAAS,uBAAuB,aAAa,KAAK;EACnE,MAAM,WAAW,KAAK,SAAS,aAAa,IAAI;EAChD,IAAI,QAAQ;GACR,QAAQ,IAAI,KAAK,UAAU;IAAE,GAAG,WAAW;IAAG,SAAS;KAAE,MAAM;KAAU;IAAQ;GAAE,GAAG,MAAM,CAAC,CAAC;GAC9F;EACJ;EACA,QAAQ,IAAI,UACN,MAAM,MAAM,WAAW,UAAU,IACjC,MAAM,KAAK,GAAG,SAAS,mCAAmC,CAAC;EACjE;CACJ;CAEA,IAAI,QAAQ;EACR,QAAQ,IAAI,KAAK,UAAU,WAAW,GAAG,MAAM,CAAC,CAAC;EACjD;CACJ;CAEA,MAAM,qBAAqB,KAAK,CAAC;AACrC"}
|
|
1
|
+
{"version":3,"file":"resources-ecA0MEjy.js","names":[],"sources":["../src/commands/resources.ts"],"sourcesContent":["/**\n * CLI command: rebase resources\n *\n * Shows what a project declares, and keeps the committed graph honest.\n *\n * The graph is generated, so it can drift the moment somebody adds a bucket and\n * does not regenerate. Drift here is not cosmetic: the committed file is what a\n * host reads to decide what to provision, so a stale one means the console\n * offers a project one set of resources while the runtime asks for another.\n * `--check` is the gate that makes that impossible to land.\n */\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport { failAsJson, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError } from \"../manifest\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport {\n RESOURCE_GRAPH_FILENAME,\n deriveOptionsFor, deriveResourceGraph,\n projectResourceGraph,\n readResourceGraphFile,\n serializeResourceGraph,\n writeResourceGraphFile,\n type ProjectedResource\n} from \"../resources/derive\";\nimport { declaredSubscriptions, type RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase resources\")} — what this project needs\n\n ${chalk.blue(\"rebase resources\")} List them, declared and implicit\n ${chalk.blue(\"rebase resources --write\")} Regenerate ${RESOURCE_GRAPH_FILENAME}\n ${chalk.blue(\"rebase resources --check\")} Fail if the committed graph is stale\n ${chalk.blue(\"rebase resources --json\")} The same set, machine-readable; with --check or --write,\n their result too (a failed check is an error envelope, exit 1)\n\nA resource is declared in config code — ${chalk.gray('database(\"analytics\"), bucket(\"media\"), topic(\"signups\")')} —\nand never in ${RESOURCE_GRAPH_FILENAME}, which is generated from those declarations so a host\ncan read what a project needs without building it. A backend also has a default\ndatabase and a default storage source nobody declared; both are listed here,\nmarked ${chalk.gray(\"implicit\")}, and neither is written to that file — the host supplies them.\n`);\n}\n\n/**\n * Render the projection the way somebody reads it: grouped by kind, key first.\n *\n * The projection, not the raw graph. `rebase status` has always included the\n * implicit default database and bucket and this listing did not, so the two\n * commands answered \"what does this project need\" differently on the same stock\n * scaffold. There is no \"no resources declared\" case any more: a backend has a\n * database and a storage source whether or not anyone wrote them down.\n */\nfunction print(resources: ProjectedResource[]): void {\n // Infrastructure first, then code: what needs binding is what a reader\n // is here to check.\n const order = [\"database\", \"bucket\", \"topic\", \"queue\", \"cron\", \"function\"];\n const kinds = [...new Set(resources.map(r => r.kind))]\n .sort((a, b) => (order.indexOf(a) === -1 ? 99 : order.indexOf(a)) - (order.indexOf(b) === -1 ? 99 : order.indexOf(b)));\n for (const kind of kinds) {\n console.log(`\\n ${chalk.bold(kind)}`);\n for (const r of resources.filter(x => x.kind === kind)) {\n const bits: string[] = [];\n if (kind === \"cron\") {\n bits.push(chalk.cyan(String(r.options.schedule)));\n bits.push(chalk.gray(r.options.timezone ? String(r.options.timezone) : \"local time\"));\n } else if (kind === \"function\") {\n bits.push(chalk.gray(String(r.options.file ?? \"\")));\n if (r.options.portable === false) bits.push(chalk.yellow(\"node-only\"));\n } else {\n bits.push(chalk.gray(r.engine));\n if (r.transport !== \"server\") bits.push(chalk.yellow(r.transport));\n for (const [k, v] of Object.entries(r.options)) bits.push(chalk.gray(`${k}=${String(v)}`));\n }\n // Marked, not hidden: a declared resource is recorded in\n // `rebase.resources.json` for a host to provision, and an implicit\n // one is a default the runtime supplies regardless.\n if (r.implicit) bits.push(chalk.gray(\"implicit\"));\n console.log(` ${r.key.padEnd(24)} ${bits.join(\" · \")}`);\n if (kind === \"topic\") {\n for (const sub of declaredSubscriptions(r.key)) {\n console.log(` ${chalk.gray(\"→\")} ${sub.name}`);\n }\n }\n if (r.usedBy && r.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(r.usedBy.join(\", \"))}`);\n }\n }\n }\n console.log(\"\");\n}\n\nexport async function resourcesCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: {\n \"--write\": Boolean,\n \"--check\": Boolean,\n \"--json\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"resources\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, for the reason in `failAsJson`:\n // `--json` is a promise about stdout, and a promise kept on one exit of a\n // command and broken on the next is not one.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backendApp: RebaseBackendAppConfig;\n try {\n const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (!backend) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backendApp = backend.app;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The projection, so this and `rebase status --json` describe the same\n // set. `version` is kept so a reader of either can tell them apart from a\n // future shape. `--check` and `--write` add what they did to it: `--json`\n // changes how the answer is printed, never which question is answered — it\n // used to return here, so `--check --json` exited 0 on any drift and\n // `--write --json` wrote nothing.\n const projection = () => ({ version: graph.version, resources: projectResourceGraph(graph) });\n\n if (flags[\"--check\"]) {\n const committed = readResourceGraphFile(projectRoot);\n const expected = serializeResourceGraph(graph);\n // Declaring nothing and having no file is a consistent state, not a\n // stale one. The file records declarations; a project with none has\n // nothing to record, and its default database and bucket are implicit\n // by design — that is the overwhelmingly common project and it must not\n // be required to commit an empty file saying so.\n //\n // This mattered the moment the check was put in a gate: it would have\n // failed this repository's own reference app, which declares nothing,\n // and every scaffolded project until someone declared a second bucket.\n const status = committed === expected\n ? \"current\"\n : committed === null && graph.resources.length === 0 ? \"nothing-declared\" : null;\n\n if (status !== null) {\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), check: { file: RESOURCE_GRAPH_FILENAME, status } }, null, 2));\n return;\n }\n console.log(status === \"current\"\n ? chalk.green(`✓ ${RESOURCE_GRAPH_FILENAME} matches the declarations.`)\n : chalk.gray(\"✓ Nothing declared, so there is nothing to record.\"));\n return;\n }\n\n const state = committed === null ? \"missing\" : \"stale\";\n if (asJson) {\n failAsJson(\n `${RESOURCE_GRAPH_FILENAME} is ${state}.`,\n `resource_graph_${state}`,\n \"Regenerate it with `rebase resources --write`, and commit it.\"\n );\n }\n console.error(chalk.red(`\\n✗ ${RESOURCE_GRAPH_FILENAME} is ${state}.\\n`));\n console.error(\n \" A host reads this file to decide what to provision, so a stale one means the\\n\" +\n \" console offers one set of resources while the runtime asks for another.\\n\"\n );\n console.error(` Regenerate it: ${chalk.blue(\"rebase resources --write\")}\\n`);\n process.exitCode = 1;\n return;\n }\n\n if (flags[\"--write\"]) {\n const { changed, file } = writeResourceGraphFile(projectRoot, graph);\n const relative = path.relative(projectRoot, file);\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), written: { file: relative, changed } }, null, 2));\n return;\n }\n console.log(changed\n ? chalk.green(`✓ Wrote ${relative}`)\n : chalk.gray(`${relative} already matched the declarations.`));\n return;\n }\n\n if (asJson) {\n console.log(JSON.stringify(projection(), null, 2));\n return;\n }\n\n print(projectResourceGraph(graph));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,SAAS,QAAc;CACnB,QAAQ,IAAI;EACd,MAAM,KAAK,kBAAkB,EAAE;;IAE7B,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,0BAA0B,EAAE,iBAAiB,wBAAwB;IAChF,MAAM,KAAK,0BAA0B,EAAE;IACvC,MAAM,KAAK,yBAAyB,EAAE;;;0CAGA,MAAM,KAAK,gEAA0D,EAAE;eAClG,wBAAwB;;;SAG9B,MAAM,KAAK,UAAU,EAAE;CAC/B;AACD;;;;;;;;;;AAWA,SAAS,MAAM,WAAsC;CAGjD,MAAM,QAAQ;EAAC;EAAY;EAAU;EAAS;EAAS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,MAAM,YAAY;EAClB,MAAM,EAAE,SAAS,SAAS,uBAAuB,aAAa,KAAK;EACnE,MAAM,WAAW,KAAK,SAAS,aAAa,IAAI;EAChD,IAAI,QAAQ;GACR,QAAQ,IAAI,KAAK,UAAU;IAAE,GAAG,WAAW;IAAG,SAAS;KAAE,MAAM;KAAU;IAAQ;GAAE,GAAG,MAAM,CAAC,CAAC;GAC9F;EACJ;EACA,QAAQ,IAAI,UACN,MAAM,MAAM,WAAW,UAAU,IACjC,MAAM,KAAK,GAAG,SAAS,mCAAmC,CAAC;EACjE;CACJ;CAEA,IAAI,QAAQ;EACR,QAAQ,IAAI,KAAK,UAAU,WAAW,GAAG,MAAM,CAAC,CAAC;EACjD;CACJ;CAEA,MAAM,qBAAqB,KAAK,CAAC;AACrC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
|
|
2
2
|
import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
|
|
3
|
-
import { a as projectTarget, c as requestJson, d as PROJECT_TARGET_FLAGS, i as printProjectHelp, l as startProjectCommand, n as isRecord, o as recordsOf, r as parsedLine, u as stringOf } from "./project-command-
|
|
4
|
-
import { M as note, m as emit } from "./context-
|
|
3
|
+
import { a as projectTarget, c as requestJson, d as PROJECT_TARGET_FLAGS, i as printProjectHelp, l as startProjectCommand, n as isRecord, o as recordsOf, r as parsedLine, u as stringOf } from "./project-command-5wM_bJQt.js";
|
|
4
|
+
import { M as note, m as emit } from "./context-C9lz1vTS.js";
|
|
5
5
|
import chalk from "chalk";
|
|
6
6
|
//#region src/commands/rls.ts
|
|
7
7
|
/** Everything the switch below dispatches, for the did-you-mean. */
|
|
@@ -130,4 +130,4 @@ function printRlsHelp() {
|
|
|
130
130
|
//#endregion
|
|
131
131
|
export { RLS_SUBCOMMANDS, rlsCommand };
|
|
132
132
|
|
|
133
|
-
//# sourceMappingURL=rls-
|
|
133
|
+
//# sourceMappingURL=rls-B4zGbTKY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rls-BxWLfEKl.js","names":[],"sources":["../src/commands/rls.ts"],"sourcesContent":["/**\n * CLI command: rebase rls <action>\n *\n * What another identity would see: the app's RLS simulator\n * (`/api/admin/rls-simulator`), the one Studio's \"view as\" uses. For a role,\n * a user or a service key it answers, table by table, how many rows that\n * identity reads against how many you read, which tables its scopes shut it\n * out of, and which columns it cannot read. Read-only: nothing is written.\n *\n * The simulator answers an administrator's own session, never a key — a\n * machine credential could otherwise borrow anyone's view. So this command\n * sends the session `rebase auth login` stored for the server, and says so\n * when there is none.\n *\n * `rebase verify --live` is the static half: policies checked against the\n * schema with no identity in mind.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { PROJECT_TARGET_FLAGS } from \"../utils/project-target\";\nimport {\n emit,\n isRecord,\n parsedLine,\n printProjectHelp,\n projectTarget,\n recordsOf,\n requestJson,\n startProjectCommand,\n stringOf,\n type HelpAction\n} from \"../utils/project-command\";\nimport { note } from \"./cloud/context\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const RLS_SUBCOMMANDS = [\"simulate\", \"options\"] as const;\n\nconst SIMULATOR = \"/api/admin/rls-simulator\";\n\nexport async function rlsCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printRlsHelp();\n return;\n }\n switch (subcommand) {\n case \"simulate\":\n await simulate(rawArgs);\n break;\n case \"options\":\n await options(rawArgs);\n break;\n default:\n unknownCommand(subcommand, RLS_SUBCOMMANDS, \"rls\");\n }\n}\n\nexport const RLS_OPTIONS_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nasync function options(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: RLS_OPTIONS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"rls options\",\n maxPositionals: 0\n }));\n const target = await projectTarget(flags, { command: \"rls options\", defaultCredential: \"person\" });\n const body = await requestJson(target, `${SIMULATOR}/options`, \"Failed to read what can be simulated\");\n emit(() => {\n const roles = recordsOf(isRecord(body) ? body.roles : undefined);\n const keys = recordsOf(isRecord(body) ? body.apiKeys : undefined);\n console.log(chalk.bold(\" Roles\"));\n for (const role of roles) console.log(` ${stringOf(role.id) ?? \"?\"}`);\n console.log(chalk.bold(\" Service keys\"));\n if (keys.length === 0) console.log(chalk.gray(\" none\"));\n for (const key of keys) console.log(` ${stringOf(key.id) ?? \"?\"} ${stringOf(key.name) ?? \"\"} ${chalk.gray(`[${stringOf(key.keyPrefix) ?? \"\"}•••]`)}`);\n }, body);\n}\n\nexport const RLS_SIMULATE_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--role\": String,\n \"--user\": String,\n \"--key\": String,\n \"--table\": String\n} satisfies arg.Spec;\n\nasync function simulate(rawArgs: string[]): Promise<void> {\n const { flags, simulation } = parsedLine(() => {\n const parsed = parseCommandArgs({\n spec: RLS_SIMULATE_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"rls simulate\",\n maxPositionals: 0\n });\n const given = [parsed.flags[\"--role\"], parsed.flags[\"--user\"], parsed.flags[\"--key\"]].filter(v => v !== undefined);\n if (given.length !== 1) throw new UsageError(\"Name one identity: --role <role>, --user <uid> or --key <api-key-id> (`rebase rls options` lists them).\");\n return {\n flags: parsed.flags,\n simulation: {\n ...(parsed.flags[\"--role\"] ? { role: parsed.flags[\"--role\"] } : {}),\n ...(parsed.flags[\"--user\"] ? { userId: parsed.flags[\"--user\"] } : {}),\n ...(parsed.flags[\"--key\"] ? { apiKeyId: parsed.flags[\"--key\"] } : {})\n }\n };\n });\n const target = await projectTarget(flags, { command: \"rls simulate\", defaultCredential: \"person\" });\n const body = await requestJson(target, `${SIMULATOR}/preview`, \"Failed to simulate\", { method: \"POST\", json: simulation });\n const tables = recordsOf(isRecord(body) ? body.collections : undefined)\n .filter(view => !flags[\"--table\"] || view.slug === flags[\"--table\"]);\n emit(() => {\n const identity = isRecord(body) && isRecord(body.identity) ? body.identity : undefined;\n const who = stringOf(simulation.role) ?? stringOf(simulation.userId) ?? stringOf(simulation.apiKeyId) ?? \"?\";\n const roles = identity && Array.isArray(identity.roles) ? identity.roles.map(String).join(\", \") : \"\";\n console.log(chalk.bold(` As ${who}`) + (roles ? chalk.gray(` roles: ${roles}`) : \"\"));\n if (tables.length === 0) return note(flags[\"--table\"] ? `No table named ${flags[\"--table\"]}.` : \"No tables.\");\n const width = Math.max(5, ...tables.map(view => (stringOf(view.slug) ?? \"\").length));\n for (const view of tables) {\n const slug = stringOf(view.slug) ?? \"?\";\n const hidden = stringOf(view.hiddenBy);\n const visible = typeof view.visibleRows === \"number\" ? view.visibleRows : undefined;\n const total = typeof view.totalRows === \"number\" ? view.totalRows : undefined;\n const rows = hidden === \"scope\"\n ? chalk.gray(\"shut out by the key's scopes\")\n : hidden === \"error\"\n ? chalk.red(`read fails: ${stringOf(view.error) ?? \"unknown error\"}`)\n : `${visible ?? \"?\"} of ${total ?? \"?\"} rows${hidden === \"rls\" ? chalk.yellow(\" (policies hide every row)\") : \"\"}`;\n const masked = Array.isArray(view.maskedColumns) && view.maskedColumns.length > 0\n ? chalk.gray(` cannot read: ${view.maskedColumns.map(String).join(\", \")}`)\n : \"\";\n console.log(` ${slug.padEnd(width)} ${rows}${masked}`);\n }\n }, body);\n}\n\nconst RLS_ACTIONS: HelpAction[] = [\n {\n action: \"simulate\",\n description: \"Per table: the rows an identity reads against yours, scope shut-outs, unreadable columns\",\n flags: [\n [\"--role <role>\", \"Simulate a role (anon for a visitor)\"],\n [\"--user <uid>\", \"Simulate one user, with their live roles\"],\n [\"--key <api-key-id>\", \"Simulate a service key, with its scopes\"],\n [\"--table <slug>\", \"Only this table\"]\n ]\n },\n { action: \"options\", description: \"The roles and service keys there are to simulate\" }\n];\n\nfunction printRlsHelp(): void {\n printProjectHelp({\n command: \"rls\",\n title: \"What another identity would see, under the app's row-level security\",\n actions: RLS_ACTIONS,\n notes: [\n \"The simulator answers an administrator's own session, never a key: sign in first with `rebase auth login`.\",\n \"Example: rebase rls simulate --role anon\",\n \"`rebase verify --live` checks the policies themselves, with no identity in mind.\"\n ]\n });\n}\n"],"mappings":";;;;;;;AAsCA,IAAa,kBAAkB,CAAC,YAAY,SAAS;AAErD,IAAM,YAAY;AAElB,eAAsB,WAAW,YAAgC,SAAkC;CAC/F,oBAAoB,OAAO;CAC3B,IAAI,CAAC,cAAc,eAAe,YAAY,UAAU,OAAO,GAAG;EAC9D,aAAa;EACb;CACJ;CACA,QAAQ,YAAR;EACI,KAAK;GACD,MAAM,SAAS,OAAO;GACtB;EACJ,KAAK;GACD,MAAM,QAAQ,OAAO;GACrB;EACJ,SACI,eAAe,YAAY,iBAAiB,KAAK;CACzD;AACJ;AAEA,IAAa,oBAAoB,EAAE,GAAG,qBAAqB;AAE3D,eAAe,QAAQ,SAAkC;CACrD,MAAM,EAAE,UAAU,iBAAiB,iBAAiB;EAChD,MAAM;EACN;EACA,cAAc;EACd,SAAS;EACT,gBAAgB;CACpB,CAAC,CAAC;CAEF,MAAM,OAAO,MAAM,YAAY,MADV,cAAc,OAAO;EAAE,SAAS;EAAe,mBAAmB;CAAS,CAAC,GAC1D,GAAG,UAAU,WAAW,sCAAsC;CACrG,WAAW;EACP,MAAM,QAAQ,UAAU,SAAS,IAAI,IAAI,KAAK,QAAQ,KAAA,CAAS;EAC/D,MAAM,OAAO,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,KAAA,CAAS;EAChE,QAAQ,IAAI,MAAM,KAAK,SAAS,CAAC;EACjC,KAAK,MAAM,QAAQ,OAAO,QAAQ,IAAI,OAAO,SAAS,KAAK,EAAE,KAAK,KAAK;EACvE,QAAQ,IAAI,MAAM,KAAK,gBAAg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AAK,OAAO,KAAK,EAAE,IAAI,OAAO,QAAQ;EAC3D;CACJ,GAAG,IAAI;AACX;AAEA,IAAM,cAA4B,CAC9B;CACI,QAAQ;CACR,aAAa;CACb,OAAO;EACH,CAAC,iBAAiB,sCAAsC;EACxD,CAAC,gBAAgB,0CAA0C;EAC3D,CAAC,sBAAsB,yCAAyC;EAChE,CAAC,kBAAkB,iBAAiB;CACxC;AACJ,GACA;CAAE,QAAQ;CAAW,aAAa;AAAmD,CACzF;AAEA,SAAS,eAAqB;CAC1B,iBAAiB;EACb,SAAS;EACT,OAAO;EACP,SAAS;EACT,OAAO;GACH;GACA;GACA;EACJ;CACJ,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"rls-B4zGbTKY.js","names":[],"sources":["../src/commands/rls.ts"],"sourcesContent":["/**\n * CLI command: rebase rls <action>\n *\n * What another identity would see: the app's RLS simulator\n * (`/api/admin/rls-simulator`), the one Studio's \"view as\" uses. For a role,\n * a user or a service key it answers, table by table, how many rows that\n * identity reads against how many you read, which tables its scopes shut it\n * out of, and which columns it cannot read. Read-only: nothing is written.\n *\n * The simulator answers an administrator's own session, never a key — a\n * machine credential could otherwise borrow anyone's view. So this command\n * sends the session `rebase auth login` stored for the server, and says so\n * when there is none.\n *\n * `rebase verify --live` is the static half: policies checked against the\n * schema with no identity in mind.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { PROJECT_TARGET_FLAGS } from \"../utils/project-target\";\nimport {\n emit,\n isRecord,\n parsedLine,\n printProjectHelp,\n projectTarget,\n recordsOf,\n requestJson,\n startProjectCommand,\n stringOf,\n type HelpAction\n} from \"../utils/project-command\";\nimport { note } from \"./cloud/context\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const RLS_SUBCOMMANDS = [\"simulate\", \"options\"] as const;\n\nconst SIMULATOR = \"/api/admin/rls-simulator\";\n\nexport async function rlsCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printRlsHelp();\n return;\n }\n switch (subcommand) {\n case \"simulate\":\n await simulate(rawArgs);\n break;\n case \"options\":\n await options(rawArgs);\n break;\n default:\n unknownCommand(subcommand, RLS_SUBCOMMANDS, \"rls\");\n }\n}\n\nexport const RLS_OPTIONS_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nasync function options(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: RLS_OPTIONS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"rls options\",\n maxPositionals: 0\n }));\n const target = await projectTarget(flags, { command: \"rls options\", defaultCredential: \"person\" });\n const body = await requestJson(target, `${SIMULATOR}/options`, \"Failed to read what can be simulated\");\n emit(() => {\n const roles = recordsOf(isRecord(body) ? body.roles : undefined);\n const keys = recordsOf(isRecord(body) ? body.apiKeys : undefined);\n console.log(chalk.bold(\" Roles\"));\n for (const role of roles) console.log(` ${stringOf(role.id) ?? \"?\"}`);\n console.log(chalk.bold(\" Service keys\"));\n if (keys.length === 0) console.log(chalk.gray(\" none\"));\n for (const key of keys) console.log(` ${stringOf(key.id) ?? \"?\"} ${stringOf(key.name) ?? \"\"} ${chalk.gray(`[${stringOf(key.keyPrefix) ?? \"\"}•••]`)}`);\n }, body);\n}\n\nexport const RLS_SIMULATE_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--role\": String,\n \"--user\": String,\n \"--key\": String,\n \"--table\": String\n} satisfies arg.Spec;\n\nasync function simulate(rawArgs: string[]): Promise<void> {\n const { flags, simulation } = parsedLine(() => {\n const parsed = parseCommandArgs({\n spec: RLS_SIMULATE_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"rls simulate\",\n maxPositionals: 0\n });\n const given = [parsed.flags[\"--role\"], parsed.flags[\"--user\"], parsed.flags[\"--key\"]].filter(v => v !== undefined);\n if (given.length !== 1) throw new UsageError(\"Name one identity: --role <role>, --user <uid> or --key <api-key-id> (`rebase rls options` lists them).\");\n return {\n flags: parsed.flags,\n simulation: {\n ...(parsed.flags[\"--role\"] ? { role: parsed.flags[\"--role\"] } : {}),\n ...(parsed.flags[\"--user\"] ? { userId: parsed.flags[\"--user\"] } : {}),\n ...(parsed.flags[\"--key\"] ? { apiKeyId: parsed.flags[\"--key\"] } : {})\n }\n };\n });\n const target = await projectTarget(flags, { command: \"rls simulate\", defaultCredential: \"person\" });\n const body = await requestJson(target, `${SIMULATOR}/preview`, \"Failed to simulate\", { method: \"POST\", json: simulation });\n const tables = recordsOf(isRecord(body) ? body.collections : undefined)\n .filter(view => !flags[\"--table\"] || view.slug === flags[\"--table\"]);\n emit(() => {\n const identity = isRecord(body) && isRecord(body.identity) ? body.identity : undefined;\n const who = stringOf(simulation.role) ?? stringOf(simulation.userId) ?? stringOf(simulation.apiKeyId) ?? \"?\";\n const roles = identity && Array.isArray(identity.roles) ? identity.roles.map(String).join(\", \") : \"\";\n console.log(chalk.bold(` As ${who}`) + (roles ? chalk.gray(` roles: ${roles}`) : \"\"));\n if (tables.length === 0) return note(flags[\"--table\"] ? `No table named ${flags[\"--table\"]}.` : \"No tables.\");\n const width = Math.max(5, ...tables.map(view => (stringOf(view.slug) ?? \"\").length));\n for (const view of tables) {\n const slug = stringOf(view.slug) ?? \"?\";\n const hidden = stringOf(view.hiddenBy);\n const visible = typeof view.visibleRows === \"number\" ? view.visibleRows : undefined;\n const total = typeof view.totalRows === \"number\" ? view.totalRows : undefined;\n const rows = hidden === \"scope\"\n ? chalk.gray(\"shut out by the key's scopes\")\n : hidden === \"error\"\n ? chalk.red(`read fails: ${stringOf(view.error) ?? \"unknown error\"}`)\n : `${visible ?? \"?\"} of ${total ?? \"?\"} rows${hidden === \"rls\" ? chalk.yellow(\" (policies hide every row)\") : \"\"}`;\n const masked = Array.isArray(view.maskedColumns) && view.maskedColumns.length > 0\n ? chalk.gray(` cannot read: ${view.maskedColumns.map(String).join(\", \")}`)\n : \"\";\n console.log(` ${slug.padEnd(width)} ${rows}${masked}`);\n }\n }, body);\n}\n\nconst RLS_ACTIONS: HelpAction[] = [\n {\n action: \"simulate\",\n description: \"Per table: the rows an identity reads against yours, scope shut-outs, unreadable columns\",\n flags: [\n [\"--role <role>\", \"Simulate a role (anon for a visitor)\"],\n [\"--user <uid>\", \"Simulate one user, with their live roles\"],\n [\"--key <api-key-id>\", \"Simulate a service key, with its scopes\"],\n [\"--table <slug>\", \"Only this table\"]\n ]\n },\n { action: \"options\", description: \"The roles and service keys there are to simulate\" }\n];\n\nfunction printRlsHelp(): void {\n printProjectHelp({\n command: \"rls\",\n title: \"What another identity would see, under the app's row-level security\",\n actions: RLS_ACTIONS,\n notes: [\n \"The simulator answers an administrator's own session, never a key: sign in first with `rebase auth login`.\",\n \"Example: rebase rls simulate --role anon\",\n \"`rebase verify --live` checks the policies themselves, with no identity in mind.\"\n ]\n });\n}\n"],"mappings":";;;;;;;AAsCA,IAAa,kBAAkB,CAAC,YAAY,SAAS;AAErD,IAAM,YAAY;AAElB,eAAsB,WAAW,YAAgC,SAAkC;CAC/F,oBAAoB,OAAO;CAC3B,IAAI,CAAC,cAAc,eAAe,YAAY,UAAU,OAAO,GAAG;EAC9D,aAAa;EACb;CACJ;CACA,QAAQ,YAAR;EACI,KAAK;GACD,MAAM,SAAS,OAAO;GACtB;EACJ,KAAK;GACD,MAAM,QAAQ,OAAO;GACrB;EACJ,SACI,eAAe,YAAY,iBAAiB,KAAK;CACzD;AACJ;AAEA,IAAa,oBAAoB,EAAE,GAAG,qBAAqB;AAE3D,eAAe,QAAQ,SAAkC;CACrD,MAAM,EAAE,UAAU,iBAAiB,iBAAiB;EAChD,MAAM;EACN;EACA,cAAc;EACd,SAAS;EACT,gBAAgB;CACpB,CAAC,CAAC;CAEF,MAAM,OAAO,MAAM,YAAY,MADV,cAAc,OAAO;EAAE,SA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AO,WAAW,UAClB,MAAM,KAAK,8BAA8B,IACzC,WAAW,UACP,MAAM,IAAI,eAAe,SAAS,KAAK,KAAK,KAAK,iBAAiB,IAClE,GAAG,WAAW,IAAI,MAAM,SAAS,IAAI,OAAO,WAAW,QAAQ,MAAM,OAAO,6BAA6B,IAAI;GACvH,MAAM,SAAS,MAAM,QAAQ,KAAK,aAAa,KAAK,KAAK,cAAc,SAAS,IAC1E,MAAM,KAAK,kBAAkB,KAAK,cAAc,IAAI,MAAM,CAAC,CAAC,KAAK,IAAI,GAAG,IACxE;GACN,QAAQ,IAAI,KAAK,KAAK,OAAO,KAAK,EAAE,IAAI,OAAO,QAAQ;EAC3D;CACJ,GAAG,IAAI;AACX;AAEA,IAAM,cAA4B,CAC9B;CACI,QAAQ;CACR,aAAa;CACb,OAAO;EACH,CAAC,iBAAiB,sCAAsC;EACxD,CAAC,gBAAgB,0CAA0C;EAC3D,CAAC,sBAAsB,yCAAyC;EAChE,CAAC,kBAAkB,iBAAiB;CACxC;AACJ,GACA;CAAE,QAAQ;CAAW,aAAa;AAAmD,CACzF;AAEA,SAAS,eAAqB;CAC1B,iBAAiB;EACb,SAAS;EACT,OAAO;EACP,SAAS;EACT,OAAO;GACH;GACA;GACA;EACJ;CACJ,CAAC;AACL"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { i as recordEvent } from "./telemetry-
|
|
1
|
+
import { i as recordEvent } from "./telemetry-CJbrRuG3.js";
|
|
2
2
|
import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
|
|
3
3
|
import { a as wantsHelp, t as UsageError } from "./args-DHyrshtI.js";
|
|
4
|
-
import { f as requireBackendDir, h as resolvePluginCliScript, l as getActiveBackendPlugin, o as findEnvFile, p as requireProjectRoot, r as exitDependenciesNotInstalled } from "./project-
|
|
5
|
-
import { r as schemaDirArgs } from "./schema-dir-
|
|
6
|
-
import { a as refuseRemovedCollectionsFlag, i as refuseMissingSchemaDir, n as SCHEMA_DIR_FLAG_HELP } from "./path-flags-
|
|
7
|
-
import { a as projectTarget, d as PROJECT_TARGET_FLAGS } from "./project-command-
|
|
8
|
-
import { n as describeFailure } from "./api-keys-
|
|
9
|
-
import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-
|
|
10
|
-
import { absolutizeLocalPathArgs, ensureDockerDatabase, n as argsFromCommand, spawnDriverCli, t as reportSpawnFailure } from "./db-
|
|
4
|
+
import { f as requireBackendDir, h as resolvePluginCliScript, l as getActiveBackendPlugin, o as findEnvFile, p as requireProjectRoot, r as exitDependenciesNotInstalled } from "./project-CQ5nKddJ.js";
|
|
5
|
+
import { r as schemaDirArgs } from "./schema-dir-Dd1Pzqq5.js";
|
|
6
|
+
import { a as refuseRemovedCollectionsFlag, i as refuseMissingSchemaDir, n as SCHEMA_DIR_FLAG_HELP } from "./path-flags-B7Ydt5nv.js";
|
|
7
|
+
import { a as projectTarget, d as PROJECT_TARGET_FLAGS } from "./project-command-5wM_bJQt.js";
|
|
8
|
+
import { n as describeFailure } from "./api-keys-CG2IpknI.js";
|
|
9
|
+
import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-CFpYl1Nt.js";
|
|
10
|
+
import { absolutizeLocalPathArgs, ensureDockerDatabase, n as argsFromCommand, spawnDriverCli, t as reportSpawnFailure } from "./db-DAotpOxs.js";
|
|
11
11
|
import chalk from "chalk";
|
|
12
12
|
import arg from "arg";
|
|
13
13
|
import { RebaseApiError } from "@rebasepro/client";
|
|
@@ -184,14 +184,14 @@ async function schemaCommand(subcommand, rawArgs) {
|
|
|
184
184
|
if (!SCHEMA_ACTION_HELP[subcommand]) unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), "schema");
|
|
185
185
|
refuseRemovedCollectionsFlag(rawArgs.slice(2), `schema ${subcommand}`);
|
|
186
186
|
if (subcommand === "show") {
|
|
187
|
-
const { schemaShowCommand } = await import("./schema-show-
|
|
187
|
+
const { schemaShowCommand } = await import("./schema-show-DwYtOp4S.js");
|
|
188
188
|
await schemaShowCommand(rawArgs);
|
|
189
189
|
return;
|
|
190
190
|
}
|
|
191
191
|
const projectRoot = requireProjectRoot();
|
|
192
192
|
if (subcommand === "reconcile") {
|
|
193
193
|
recordEvent("cli.schema", { subcommand }, { projectRoot });
|
|
194
|
-
const { schemaReconcileCommand } = await import("./schema-reconcile-
|
|
194
|
+
const { schemaReconcileCommand } = await import("./schema-reconcile-DGEMmYJI.js");
|
|
195
195
|
await schemaReconcileCommand(rawArgs);
|
|
196
196
|
return;
|
|
197
197
|
}
|
|
@@ -336,4 +336,4 @@ ${chalk.green.bold("stale Options")}
|
|
|
336
336
|
//#endregion
|
|
337
337
|
export { SCHEMA_SUBCOMMANDS, schemaReconcileCommand as i, describeReconcilePlan as n, parseReconcileArgs as r, schemaCommand, RECONCILE_USAGE as t };
|
|
338
338
|
|
|
339
|
-
//# sourceMappingURL=schema-
|
|
339
|
+
//# sourceMappingURL=schema-CWzzn0cY.js.map
|