@rebasepro/cli 0.31.0-canary.g902a0ce → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-setup-DqAcoDcn.js → agent-setup-Cg_zBWoW.js} +3 -3
- package/dist/{agent-setup-DqAcoDcn.js.map → agent-setup-Cg_zBWoW.js.map} +1 -1
- package/dist/api-TbmW33D7.js +275 -0
- package/dist/api-TbmW33D7.js.map +1 -0
- package/dist/{api-keys-eIUjMqWn.js → api-keys-fPQ55DCm.js} +151 -158
- package/dist/api-keys-fPQ55DCm.js.map +1 -0
- package/dist/{apps-DExO4PEl.js → apps-DBTRoOeP.js} +18 -13
- package/dist/apps-DBTRoOeP.js.map +1 -0
- package/dist/{args-CaCcrYE1.js → args-DHyrshtI.js} +3 -132
- package/dist/args-DHyrshtI.js.map +1 -0
- package/dist/{atlas-dev-database-DOCKk6ht.js → atlas-dev-database-D6h65f2x.js} +3 -3
- package/dist/{atlas-dev-database-DOCKk6ht.js.map → atlas-dev-database-D6h65f2x.js.map} +1 -1
- package/dist/{auth-CyADghFQ.js → auth-BpyYLEFY.js} +93 -12
- package/dist/auth-BpyYLEFY.js.map +1 -0
- package/dist/auth-session-B6aT0Dyj.js +371 -0
- package/dist/auth-session-B6aT0Dyj.js.map +1 -0
- package/dist/{backend-guard-C0mVkXBw.js → backend-guard-Cf8eMK_f.js} +2 -2
- package/dist/{backend-guard-C0mVkXBw.js.map → backend-guard-Cf8eMK_f.js.map} +1 -1
- package/dist/{branch-pointer-DMPyvZoK.js → branch-pointer-BJOF2Ubv.js} +1 -1
- package/dist/{build-CA5R07tw.js → build-BfdT-AUR.js} +12 -10
- package/dist/{build-CA5R07tw.js.map → build-BfdT-AUR.js.map} +1 -1
- package/dist/{bundle-DgILeA5b.js → bundle-CIiKGrte.js} +78 -12
- package/dist/bundle-CIiKGrte.js.map +1 -0
- package/dist/bundle.d.ts +31 -1
- package/dist/{cloud-CYMk92iG.js → cloud-MqnyPnmX.js} +1540 -1531
- package/dist/cloud-MqnyPnmX.js.map +1 -0
- package/dist/{cms-directories-BK3vcswg.js → cms-directories-BaV-Is9a.js} +2 -2
- package/dist/{cms-directories-BK3vcswg.js.map → cms-directories-BaV-Is9a.js.map} +1 -1
- package/dist/codemod/collections-to-tables/backend.d.ts +0 -2
- package/dist/codemod/collections-to-tables/customization.d.ts +2 -1
- package/dist/codemod/collections-to-tables/modules.d.ts +32 -0
- package/dist/codemod/collections-to-tables/plan-context.d.ts +7 -1
- package/dist/{command-D5lhW_-B.js → command-D9g46gg9.js} +68 -42
- package/dist/command-D9g46gg9.js.map +1 -0
- package/dist/commands/api-keys.d.ts +89 -52
- package/dist/commands/api.d.ts +114 -0
- package/dist/commands/auth-session.d.ts +94 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/cloud/alerts.d.ts +29 -0
- package/dist/commands/cloud/context.d.ts +8 -0
- package/dist/commands/cloud/debug.d.ts +16 -1
- package/dist/commands/cloud/deploy-hooks.d.ts +19 -0
- package/dist/commands/cloud/deploy.d.ts +25 -0
- package/dist/commands/cloud/env.d.ts +1 -0
- package/dist/commands/cloud/index.d.ts +5 -0
- package/dist/commands/cloud/maintenance.d.ts +26 -1
- package/dist/commands/cloud/not-served.d.ts +27 -0
- package/dist/commands/cloud/orgs.d.ts +5 -0
- package/dist/commands/cloud/resources.d.ts +82 -2
- package/dist/commands/cloud/runtime-logs.d.ts +57 -0
- package/dist/commands/cloud/settings.d.ts +3 -0
- package/dist/commands/cron.d.ts +68 -0
- package/dist/commands/data.d.ts +197 -0
- package/dist/commands/functions.d.ts +38 -0
- package/dist/commands/logs.d.ts +22 -0
- package/dist/commands/rls.d.ts +31 -0
- package/dist/commands/schema-reconcile.d.ts +2 -1
- package/dist/commands/schema-show.d.ts +38 -0
- package/dist/commands/storage-objects.d.ts +88 -0
- package/dist/commands/storage.d.ts +18 -2
- package/dist/commands/users.d.ts +147 -0
- package/dist/{consent-BXLIrMl8.js → consent-UV6ObCME.js} +2 -2
- package/dist/{consent-BXLIrMl8.js.map → consent-UV6ObCME.js.map} +1 -1
- package/dist/{console-CMjhgMUE.js → console-BVoYOLAO.js} +6 -6
- package/dist/{console-CMjhgMUE.js.map → console-BVoYOLAO.js.map} +1 -1
- package/dist/{context--JwaHaZp.js → context-BOMEoKxn.js} +80 -9
- package/dist/{context--JwaHaZp.js.map → context-BOMEoKxn.js.map} +1 -1
- package/dist/cron-CpUsQ739.js +298 -0
- package/dist/cron-CpUsQ739.js.map +1 -0
- package/dist/cron-ZRXsla0v.js +259 -0
- package/dist/cron-ZRXsla0v.js.map +1 -0
- package/dist/{daemon-w30PsdwV.js → daemon-D5gdG7gx.js} +3 -3
- package/dist/{daemon-w30PsdwV.js.map → daemon-D5gdG7gx.js.map} +1 -1
- package/dist/{daemon-entry-zOC1revO.js → daemon-entry--ummUJnk.js} +2 -2
- package/dist/{daemon-entry-zOC1revO.js.map → daemon-entry--ummUJnk.js.map} +1 -1
- package/dist/data-BJ9AZFUC.js +947 -0
- package/dist/data-BJ9AZFUC.js.map +1 -0
- package/dist/{db-A7XDCIIO.js → db-D_iF4E-v.js} +60 -36
- package/dist/db-D_iF4E-v.js.map +1 -0
- package/dist/debug-nNbbxAeo.js +1114 -0
- package/dist/debug-nNbbxAeo.js.map +1 -0
- package/dist/{derive-C3ezmY-p.js → derive-Mky_u59_.js} +3 -3
- package/dist/{derive-C3ezmY-p.js.map → derive-Mky_u59_.js.map} +1 -1
- package/dist/{dev-tWwPyWkQ.js → dev-bj6dEeSQ.js} +13 -13
- package/dist/{dev-tWwPyWkQ.js.map → dev-bj6dEeSQ.js.map} +1 -1
- package/dist/dev-db/__fixtures__/unanswering-postgres.d.ts +11 -0
- package/dist/dev-db/attver.d.ts +38 -6
- package/dist/dev-db/local-timeouts.d.ts +25 -0
- package/dist/dev-db/pull.d.ts +49 -9
- package/dist/{dev-preflight-DjvcV6SK.js → dev-preflight-BMOf2N6r.js} +2 -2
- package/dist/{dev-preflight-DjvcV6SK.js.map → dev-preflight-BMOf2N6r.js.map} +1 -1
- package/dist/{dev-server-BLxCbQEP.js → dev-server-2XHSHM_q.js} +2 -2
- package/dist/{dev-server-BLxCbQEP.js.map → dev-server-2XHSHM_q.js.map} +1 -1
- package/dist/{doctor-BBM0dWvZ.js → doctor-2Jlau0Rm.js} +9 -8
- package/dist/{doctor-BBM0dWvZ.js.map → doctor-2Jlau0Rm.js.map} +1 -1
- package/dist/{eject-Bhzd6hgb.js → eject-DK_M9kor.js} +4 -4
- package/dist/{eject-Bhzd6hgb.js.map → eject-DK_M9kor.js.map} +1 -1
- package/dist/{fold-static-CKewnAPX.js → fold-static-2t3UUX4z.js} +10 -6
- package/dist/fold-static-2t3UUX4z.js.map +1 -0
- package/dist/fold-static.d.ts +7 -0
- package/dist/functions-B4JR6EZL.js +120 -0
- package/dist/functions-B4JR6EZL.js.map +1 -0
- package/dist/{generate-view-CTOluXvH.js → generate-view-BMaLQm8H.js} +5 -5
- package/dist/{generate-view-CTOluXvH.js.map → generate-view-BMaLQm8H.js.map} +1 -1
- package/dist/{generate_sdk-De-aLC1L.js → generate_sdk-ByD-gTsK.js} +7 -7
- package/dist/{generate_sdk-De-aLC1L.js.map → generate_sdk-ByD-gTsK.js.map} +1 -1
- package/dist/index.es.js +123 -47
- package/dist/index.es.js.map +1 -1
- package/dist/{init-Dtl-IcXf.js → init-DHCe5mJ5.js} +59 -11
- package/dist/init-DHCe5mJ5.js.map +1 -0
- package/dist/{invoked-command-CG_rIa_o.js → invoked-command-FBeIBS8o.js} +2 -2
- package/dist/{invoked-command-CG_rIa_o.js.map → invoked-command-FBeIBS8o.js.map} +1 -1
- package/dist/last-dev-database-CBVkEUEl.js +2 -0
- package/dist/local-timeouts-B1Kwligw.js +30 -0
- package/dist/local-timeouts-B1Kwligw.js.map +1 -0
- package/dist/logs-CIgfLBsu.js +192 -0
- package/dist/logs-CIgfLBsu.js.map +1 -0
- package/dist/{manifest-C3uLDrrJ.js → manifest-RjqxfCpb.js} +114 -5
- package/dist/manifest-RjqxfCpb.js.map +1 -0
- package/dist/{migrate-VrKoi3nB.js → migrate-Cx8-Y4TG.js} +5 -4
- package/dist/{migrate-VrKoi3nB.js.map → migrate-Cx8-Y4TG.js.map} +1 -1
- package/dist/{normalize-imports-DwxqEMYq.js → normalize-imports-P86NVfpo.js} +3 -3
- package/dist/{normalize-imports-DwxqEMYq.js.map → normalize-imports-P86NVfpo.js.map} +1 -1
- package/dist/{path-flags-7O5uPBcQ.js → path-flags-ekLdkbra.js} +3 -3
- package/dist/{path-flags-7O5uPBcQ.js.map → path-flags-ekLdkbra.js.map} +1 -1
- package/dist/{prepare-Ccxspoj-.js → prepare-BaJe0Zik.js} +4 -4
- package/dist/{prepare-Ccxspoj-.js.map → prepare-BaJe0Zik.js.map} +1 -1
- package/dist/{project-CLcF5i8c.js → project-DALmhb5R.js} +2 -2
- package/dist/{project-CLcF5i8c.js.map → project-DALmhb5R.js.map} +1 -1
- package/dist/project-command-Cl9EZzjr.js +662 -0
- package/dist/project-command-Cl9EZzjr.js.map +1 -0
- package/dist/{project-schema-CsSOG2gE.js → project-schema-Dm6Jk0Y_.js} +4 -2
- package/dist/{project-schema-CsSOG2gE.js.map → project-schema-Dm6Jk0Y_.js.map} +1 -1
- package/dist/{pull-D9WvpDYY.js → pull-CTIsST6T.js} +336 -55
- package/dist/pull-CTIsST6T.js.map +1 -0
- package/dist/resolve-C36px9tR.js +2 -0
- package/dist/{resources-Dpfs2y8P.js → resources-Db3USuPO.js} +5 -5
- package/dist/{resources-Dpfs2y8P.js.map → resources-Db3USuPO.js.map} +1 -1
- package/dist/rls-BxrQ0P50.js +133 -0
- package/dist/rls-BxrQ0P50.js.map +1 -0
- package/dist/{schema-DwFDI1iU.js → schema-_FzZEoB8.js} +54 -40
- package/dist/schema-_FzZEoB8.js.map +1 -0
- package/dist/{schema-dir-Cd1kvYbf.js → schema-dir-ChcYfWjP.js} +2 -2
- package/dist/{schema-dir-Cd1kvYbf.js.map → schema-dir-ChcYfWjP.js.map} +1 -1
- package/dist/schema-reconcile-DV14XY4o.js +2 -0
- package/dist/schema-show-h72UJ9zH.js +127 -0
- package/dist/schema-show-h72UJ9zH.js.map +1 -0
- package/dist/{skills-CXjA9TWw.js → skills-DQ2bZGkj.js} +6 -5
- package/dist/{skills-CXjA9TWw.js.map → skills-DQ2bZGkj.js.map} +1 -1
- package/dist/star-nudge.d.ts +28 -0
- package/dist/{start-Bwbtt2W5.js → start-Cjx4W0bJ.js} +7 -7
- package/dist/{start-Bwbtt2W5.js.map → start-Cjx4W0bJ.js.map} +1 -1
- package/dist/{status-DQ_PPz4C.js → status-CDBk25VO.js} +9 -9
- package/dist/{status-DQ_PPz4C.js.map → status-CDBk25VO.js.map} +1 -1
- package/dist/{storage-iTqj5-Av.js → storage-Clc8dLG8.js} +79 -36
- package/dist/storage-Clc8dLG8.js.map +1 -0
- package/dist/storage-objects-CfRKlTDe.js +279 -0
- package/dist/storage-objects-CfRKlTDe.js.map +1 -0
- package/dist/{telemetry-BP_1Cl9r.js → telemetry-DZU2-NCm.js} +5 -4
- package/dist/{telemetry-BP_1Cl9r.js.map → telemetry-DZU2-NCm.js.map} +1 -1
- package/dist/{telemetry-M3HjlyhZ.js → telemetry-EVtASbKb.js} +2 -2
- package/dist/{telemetry-M3HjlyhZ.js.map → telemetry-EVtASbKb.js.map} +1 -1
- package/dist/unknown-command-DnZ2uhGs.js +139 -0
- package/dist/unknown-command-DnZ2uhGs.js.map +1 -0
- package/dist/{upgrade-oZzJ13jM.js → upgrade-DhpUFb6p.js} +5 -5
- package/dist/{upgrade-oZzJ13jM.js.map → upgrade-DhpUFb6p.js.map} +1 -1
- package/dist/users-5PkqBY6R.js +561 -0
- package/dist/users-5PkqBY6R.js.map +1 -0
- package/dist/utils/project-command.d.ts +38 -0
- package/dist/utils/project-target.d.ts +193 -0
- package/dist/{verify-DkJqhYPI.js → verify-BdeqNb-V.js} +138 -12
- package/dist/verify-BdeqNb-V.js.map +1 -0
- package/dist/{version-Buyyo1ut.js → version-ONIeo7jl.js} +7 -2
- package/dist/{version-Buyyo1ut.js.map → version-ONIeo7jl.js.map} +1 -1
- package/package.json +10 -10
- package/dist/api-keys-eIUjMqWn.js.map +0 -1
- package/dist/apps-DExO4PEl.js.map +0 -1
- package/dist/args-CaCcrYE1.js.map +0 -1
- package/dist/auth-CyADghFQ.js.map +0 -1
- package/dist/bundle-DgILeA5b.js.map +0 -1
- package/dist/cloud-CYMk92iG.js.map +0 -1
- package/dist/command-D5lhW_-B.js.map +0 -1
- package/dist/db-A7XDCIIO.js.map +0 -1
- package/dist/fold-static-CKewnAPX.js.map +0 -1
- package/dist/init-Dtl-IcXf.js.map +0 -1
- package/dist/last-dev-database-Dc8cP01o.js +0 -2
- package/dist/manifest-C3uLDrrJ.js.map +0 -1
- package/dist/pull-D9WvpDYY.js.map +0 -1
- package/dist/resolve-BY7bSFRT.js +0 -2
- package/dist/schema-DwFDI1iU.js.map +0 -1
- package/dist/schema-reconcile-Tto54Qbv.js +0 -2
- package/dist/storage-iTqj5-Av.js.map +0 -1
- package/dist/verify-DkJqhYPI.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project-command-Cl9EZzjr.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,IAA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B;AACJ;;AAGA,SAAgB,SAAS,OAAkD;CACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E;AAEA,SAAgB,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,5 +1,7 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
1
2
|
import { t as createSchemaModuleImporter } from "./import-schema-module-Df67TIWj.js";
|
|
2
3
|
//#region src/utils/project-schema.ts
|
|
4
|
+
var project_schema_exports = /* @__PURE__ */ __exportAll({ loadProjectSchema: () => loadProjectSchema });
|
|
3
5
|
/**
|
|
4
6
|
* Import and compile a project's schema directory.
|
|
5
7
|
*
|
|
@@ -25,6 +27,6 @@ async function loadProjectSchema(projectRoot, schemaDir, aliases = {}) {
|
|
|
25
27
|
};
|
|
26
28
|
}
|
|
27
29
|
//#endregion
|
|
28
|
-
export { loadProjectSchema as t };
|
|
30
|
+
export { project_schema_exports as n, loadProjectSchema as t };
|
|
29
31
|
|
|
30
|
-
//# sourceMappingURL=project-schema-
|
|
32
|
+
//# sourceMappingURL=project-schema-Dm6Jk0Y_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-schema-
|
|
1
|
+
{"version":3,"file":"project-schema-Dm6Jk0Y_.js","names":[],"sources":["../src/utils/project-schema.ts"],"sourcesContent":["/**\n * The project's `backend/schema`, imported in this process — for the commands\n * that read the tables themselves rather than through the driver: `rebase\n * verify`, `rebase build`, `rebase resources`, `rebase generate-sdk`.\n *\n * Through `loadBackendSchema` from `@rebasepro/server`, the one definition of\n * \"the tables\" that boot, the runtime and the driver also read, so a command\n * here can never accept a schema the server refuses (or the reverse): a table\n * with no `rls`, an index that does not export a sibling's table, a project\n * still on the collections layout — each is the loader's error, word for word.\n * Modules are imported with the CLI's one importer\n * (`createSchemaModuleImporter`), so a file written earlier in the same\n * process is read as it is now.\n */\nimport type { CompiledSchema, LoadedSchema } from \"@rebasepro/server\";\nimport { createSchemaModuleImporter } from \"./import-schema-module\";\n\n/** The project's schema, as the loader read it and as it compiles. */\nexport interface ProjectSchema {\n loaded: LoadedSchema;\n compiled: CompiledSchema;\n}\n\n/**\n * Module specifiers mapped to files, for the importer. A user's project\n * resolves through its own `node_modules` and passes none; tests and in-repo\n * runs point `@rebasepro/*` at the workspace's source.\n */\nexport type ModuleAliases = Record<string, string>;\n\n/**\n * Import and compile a project's schema directory.\n *\n * Throws what the loader throws: `SchemaLoadError` (a module that does not\n * import, the legacy layout, a definition the index does not export) or\n * `SchemaDefinitionError` from `@rebasepro/common` (every problem with every\n * definition, one per line). A directory that does not exist, or has no\n * index, declares no tables: `descriptors` is empty.\n *\n * @param projectRoot the project root — where a leftover legacy collections\n * directory would be, and what the importer is rooted at.\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectSchema(\n projectRoot: string,\n schemaDir: string,\n aliases: ModuleAliases = {}\n): Promise<ProjectSchema> {\n const { loadBackendSchema, compileLoadedSchema } = await import(\"@rebasepro/server\");\n const importModule = await createSchemaModuleImporter(projectRoot, aliases);\n const loaded = await loadBackendSchema(schemaDir, { projectRoot, importModule });\n return { loaded, compiled: compileLoadedSchema(loaded) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2CA,eAAsB,kBAClB,aACA,WACA,UAAyB,CAAC,GACJ;CACtB,MAAM,EAAE,mBAAmB,wBAAwB,MAAM,OAAO;CAEhE,MAAM,SAAS,MAAM,kBAAkB,WAAW;EAAE;EAAa,cAAA,MADtC,2BAA2B,aAAa,OAAO;CACI,CAAC;CAC/E,OAAO;EAAE;EAAQ,UAAU,oBAAoB,MAAM;CAAE;AAC3D"}
|