@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,6 +1,6 @@
|
|
|
1
|
-
import { t as detectPackageManager } from "./package-manager-
|
|
1
|
+
import { t as detectPackageManager } from "./package-manager-DTNNGHyK.js";
|
|
2
2
|
import { n as cliVersion } from "./version-ONIeo7jl.js";
|
|
3
|
-
import { a as installSkills, i as detectInstalledAgents, n as AGENT_KEYS, s as loadBundledSkills, t as AGENTS } from "./skills-
|
|
3
|
+
import { a as installSkills, i as detectInstalledAgents, n as AGENT_KEYS, s as loadBundledSkills, t as AGENTS } from "./skills-CWmBTCRW.js";
|
|
4
4
|
import chalk from "chalk";
|
|
5
5
|
import fs from "fs";
|
|
6
6
|
import path from "path";
|
|
@@ -448,4 +448,4 @@ function installAgentHooks(projectDir, { force = false, templateDir = path.join(
|
|
|
448
448
|
//#endregion
|
|
449
449
|
export { AGENT_HOOK_SCRIPT, MCP_SERVER_NAME, cliPackageRoot, configureAgents, ensureMcpDependency, installAgentHooks, mcpDependencyNote, mcpServerRegistered, printAgentSetup, promptForAgents, retargetScaffoldMcpConfig, writeMcpConfig };
|
|
450
450
|
|
|
451
|
-
//# sourceMappingURL=agent-setup-
|
|
451
|
+
//# sourceMappingURL=agent-setup-kjdKozkF.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-setup-CGeAuP0Q.js","names":[],"sources":["../src/commands/agent-setup.ts"],"sourcesContent":["/**\n * Setting a project up for the AI coding assistants a developer uses: the\n * Rebase skills, and the Rebase MCP server in each assistant's own config.\n *\n * `rebase init` used to end by *printing* `rebase skills install`, and nothing\n * ran it — so a generated project had pointer files telling every assistant to\n * read skills that were not there, and an MCP server only Claude Code knew\n * about. This asks once, while the project is being made, pre-ticking the\n * assistants installed on the machine.\n */\nimport chalk from \"chalk\";\nimport { createHash } from \"crypto\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport inquirer from \"inquirer\";\nimport {\n AGENT_KEYS,\n AGENTS,\n type AgentKey,\n detectInstalledAgents,\n installSkills,\n type LoadedSkill,\n loadBundledSkills\n} from \"./skills\";\nimport { fileURLToPath } from \"url\";\nimport { detectPackageManager, type PackageManager } from \"../utils/package-manager\";\nimport { cliVersion } from \"../utils/version\";\n\n/** The name the server is registered under, in every config. */\nexport const MCP_SERVER_NAME = \"rebase\";\n\n/** The MCP server's package: a devDependency of the project, pinned with the rest. */\nexport const MCP_PACKAGE = \"@rebasepro/mcp\";\n\n/** The bin {@link MCP_PACKAGE} declares. */\nexport const MCP_BIN = \"rebase-mcp\";\n\n/** The command an assistant spawns, and its arguments. */\nexport interface McpLaunch {\n command: string;\n args: string[];\n}\n\n/**\n * How an assistant starts the Rebase MCP server: the project's own copy, through\n * the project's package manager.\n *\n * Not `npx -y @rebasepro/mcp`, which fetched the newest release on every first\n * start. The server drives the project's own CLI (`pnpm exec rebase …`) and calls\n * the project's own backend (`/api/admin/schema/plan`, …), whose versions the\n * lockfile pins — so a server from the registry ran ahead of both, at every\n * start, and downloaded before it could answer. `@rebasepro/mcp` is a\n * devDependency of the scaffold, pinned to the CLI's version like every other\n * `@rebasepro` package, and this runs that copy.\n *\n * `npx --no`, not `npx`: an assistant spawns the server with no TTY, and npx\n * then assumes \"yes\" and installs a missing package from the registry under the\n * name it was given. `--no` makes a missing install an error instead.\n */\nexport function mcpLaunch(pm: PackageManager): McpLaunch {\n return pm === \"npm\"\n ? { command: \"npx\", args: [\"--no\", MCP_BIN] }\n : { command: \"pnpm\", args: [\"exec\", MCP_BIN] };\n}\n\n/** What writing one MCP config did. */\nexport type McpWriteStatus =\n /** The file was created, or the server was added beside the ones in it. */\n | \"added\"\n /** A `rebase` server was already there. It is left exactly as it was. */\n | \"present\"\n /** The file exists but is not something this can edit without losing data. */\n | \"unreadable\";\n\nexport interface McpWriteResult {\n /** Project-relative path of the config file. */\n file: string;\n status: McpWriteStatus;\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 * Add the server to a JSON config under `key`, keeping everything else in it.\n *\n * A file that does not parse as plain JSON is left alone: VS Code and Gemini\n * both accept comments in these files, and rewriting one through\n * `JSON.stringify` would delete them. Refusing costs one line of hand-editing;\n * the alternative silently costs the developer theirs.\n */\nfunction addJsonServer(filePath: string, key: string, entry: Record<string, unknown>): McpWriteStatus {\n let doc: Record<string, unknown> = {};\n if (fs.existsSync(filePath)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n } catch {\n return \"unreadable\";\n }\n if (!isRecord(parsed)) return \"unreadable\";\n doc = parsed;\n }\n\n const servers = doc[key] ?? {};\n if (!isRecord(servers)) return \"unreadable\";\n if (MCP_SERVER_NAME in servers) return \"present\";\n\n doc[key] = { ...servers, [MCP_SERVER_NAME]: entry };\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, `${JSON.stringify(doc, null, 2)}\\n`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * The Codex block, as TOML. Appended rather than merged: there is no TOML\n * parser here, and an append keeps every byte already in the file.\n */\nexport function renderCodexServer(projectDir: string, launch: McpLaunch): string {\n // A JSON string literal is a valid TOML basic string for these values.\n const str = (v: string) => JSON.stringify(v);\n return [\n `[mcp_servers.${MCP_SERVER_NAME}]`,\n `command = ${str(launch.command)}`,\n `args = [${launch.args.map(str).join(\", \")}]`,\n \"\",\n `[mcp_servers.${MCP_SERVER_NAME}.env]`,\n `REBASE_PROJECT_DIR = ${str(projectDir)}`,\n \"\"\n ].join(\"\\n\");\n}\n\nfunction addCodexServer(filePath: string, projectDir: string, launch: McpLaunch): McpWriteStatus {\n const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, \"utf-8\") : \"\";\n const table = new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.(?:${MCP_SERVER_NAME}|\"${MCP_SERVER_NAME}\")\\\\]`, \"m\");\n if (table.test(existing)) return \"present\";\n\n const separator = existing === \"\" ? \"\" : existing.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, `${existing}${separator}${renderCodexServer(projectDir, launch)}`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * Register the Rebase MCP server in the agent's project-level config, started\n * through the project's package manager (see {@link mcpLaunch}).\n *\n * Returns null for an agent with no project-level config to write.\n */\nexport function writeMcpConfig(\n agentKey: AgentKey,\n projectDir: string,\n pm: PackageManager = detectPackageManager(projectDir)\n): McpWriteResult | null {\n const mcp = AGENTS[agentKey].mcp;\n if (!mcp) return null;\n\n const filePath = path.join(projectDir, mcp.file);\n const env = { REBASE_PROJECT_DIR: mcp.projectDir };\n const { command, args } = mcpLaunch(pm);\n const write = (): McpWriteStatus => {\n switch (mcp.format) {\n case \"mcpServers\":\n return addJsonServer(filePath, \"mcpServers\", { command, args, env });\n case \"vscode\":\n // VS Code's own shape: `servers`, and an explicit transport.\n return addJsonServer(filePath, \"servers\", { type: \"stdio\", command, args, env });\n case \"codexToml\":\n return addCodexServer(filePath, mcp.projectDir, { command, args });\n }\n };\n return { file: mcp.file, status: write() };\n}\n\n/** What making sure the project depends on the MCP server did. */\nexport type McpDependencyStatus =\n /** Added to `devDependencies`, at this CLI's version: an install is due. */\n | \"added\"\n /** Already a dependency. Left at the version the project chose. */\n | \"present\"\n /** No `package.json`, or one that is not plain JSON: left alone. */\n | \"unreadable\";\n\n/**\n * Make the project depend on {@link MCP_PACKAGE}, which the config written by\n * {@link writeMcpConfig} runs from the project's own install.\n *\n * Pinned to this CLI's version, as `rebase init` pins every `@rebasepro`\n * package; a project that already lists it keeps its own choice.\n */\nexport function ensureMcpDependency(projectDir: string): McpDependencyStatus {\n const manifestPath = path.join(projectDir, \"package.json\");\n if (!fs.existsSync(manifestPath)) return \"unreadable\";\n const text = fs.readFileSync(manifestPath, \"utf-8\");\n let manifest: unknown;\n try {\n manifest = JSON.parse(text);\n } catch {\n return \"unreadable\";\n }\n if (!isRecord(manifest)) return \"unreadable\";\n for (const field of [\"dependencies\", \"devDependencies\"] as const) {\n const deps = manifest[field];\n if (isRecord(deps) && MCP_PACKAGE in deps) return \"present\";\n }\n const devDependencies = isRecord(manifest.devDependencies) ? manifest.devDependencies : {};\n const version = cliVersion();\n manifest.devDependencies = { ...devDependencies, [MCP_PACKAGE]: version === \"unknown\" ? \"latest\" : version };\n // The file's own indentation, so the change is one line in a diff.\n const indent = /\\n([ \\t]+)\"/.exec(text)?.[1] ?? \" \";\n fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, indent)}\\n`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * Point the scaffold's `.mcp.json` at the project's package manager.\n *\n * The template ships the pnpm spelling (`pnpm exec rebase-mcp`); an npm project\n * has no pnpm to run it with. Only the entry the template wrote is rewritten.\n */\nexport function retargetScaffoldMcpConfig(projectDir: string, pm: PackageManager): void {\n const filePath = path.join(projectDir, \".mcp.json\");\n if (!fs.existsSync(filePath)) return;\n let doc: unknown;\n try {\n doc = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n } catch {\n return;\n }\n const servers = isRecord(doc) ? doc.mcpServers : undefined;\n const entry = isRecord(servers) ? servers[MCP_SERVER_NAME] : undefined;\n const shipped = mcpLaunch(\"pnpm\");\n if (!isRecord(doc) || !isRecord(servers) || !isRecord(entry)) return;\n if (entry.command !== shipped.command || JSON.stringify(entry.args) !== JSON.stringify(shipped.args)) return;\n const wanted = mcpLaunch(pm);\n if (wanted.command === shipped.command && JSON.stringify(wanted.args) === JSON.stringify(shipped.args)) return;\n servers[MCP_SERVER_NAME] = { ...entry, command: wanted.command, args: wanted.args };\n fs.writeFileSync(filePath, `${JSON.stringify(doc, null, 4)}\\n`, \"utf-8\");\n}\n\n/**\n * Whether the agent's project-level config already registers the Rebase\n * server: `null` for an agent that has no such config, `false` when the file\n * is missing or does not name it. Reads only — for the hint `rebase skills\n * install` prints when it was not asked to write one.\n */\nexport function mcpServerRegistered(agentKey: AgentKey, projectDir: string): boolean | null {\n const mcp = AGENTS[agentKey].mcp;\n if (!mcp) return null;\n const filePath = path.join(projectDir, mcp.file);\n if (!fs.existsSync(filePath)) return false;\n const text = fs.readFileSync(filePath, \"utf-8\");\n if (mcp.format === \"codexToml\") {\n return new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.(?:${MCP_SERVER_NAME}|\"${MCP_SERVER_NAME}\")\\\\]`, \"m\").test(text);\n }\n try {\n const doc: unknown = JSON.parse(text);\n const servers = isRecord(doc) ? doc[mcp.format === \"vscode\" ? \"servers\" : \"mcpServers\"] : undefined;\n return isRecord(servers) && MCP_SERVER_NAME in servers;\n } catch {\n // Not plain JSON (comments): cannot tell, so do not nag.\n return null;\n }\n}\n\n/** What `configureAgents` did for one agent. */\nexport interface AgentSetupResult {\n agent: AgentKey;\n /** Skills written, or null when the bundle could not be loaded. */\n skills: number | null;\n /** An earlier agent in the same run that already wrote the skills directory. */\n sharedWith?: AgentKey;\n mcp: McpWriteResult | null;\n}\n\n/**\n * Install the skills and register the MCP server for each agent.\n *\n * Never throws for a missing skills bundle — the scaffold it runs inside must\n * not fail over its assistants — and reports it as `skills: null` instead.\n */\nexport function configureAgents(\n agents: readonly AgentKey[],\n projectDir: string,\n load: () => LoadedSkill[] = loadBundledSkills,\n pm: PackageManager = detectPackageManager(projectDir)\n): { results: AgentSetupResult[]; skillsError?: string; mcpDependency?: McpDependencyStatus } {\n let skillsError: string | undefined;\n let installed: ReturnType<typeof installSkills> = [];\n try {\n installed = installSkills(agents, load(), projectDir);\n } catch (err) {\n skillsError = err instanceof Error ? err.message : String(err);\n }\n\n const results = agents.map((agent): AgentSetupResult => {\n const skills = installed.find(r => r.agent === agent);\n return {\n agent,\n skills: skills ? skills.skills : null,\n sharedWith: skills?.sharedWith,\n mcp: writeMcpConfig(agent, projectDir, pm)\n };\n });\n // A config that runs the project's copy of the server needs the project to\n // have one.\n const registered = results.some(r => r.mcp?.status === \"added\" || r.mcp?.status === \"present\");\n return { results, skillsError, ...(registered && { mcpDependency: ensureMcpDependency(projectDir) }) };\n}\n\n/** The line to print when {@link ensureMcpDependency} changed or could not change the manifest. */\nexport function mcpDependencyNote(status: McpDependencyStatus | undefined, pm: PackageManager): string | undefined {\n if (status === \"added\") {\n return `Added ${MCP_PACKAGE} to devDependencies — run \\`${pm} install\\` before your assistant starts it.`;\n }\n if (status === \"unreadable\") {\n return `Could not add ${MCP_PACKAGE} to package.json — add it to devDependencies by hand; the MCP config runs the project's own copy.`;\n }\n return undefined;\n}\n\n/** One line per agent, for the scaffold's output. */\nexport function printAgentSetup(\n { results, skillsError, mcpDependency }: ReturnType<typeof configureAgents>,\n pm: PackageManager = \"pnpm\"\n): void {\n for (const result of results) {\n const agent = AGENTS[result.agent];\n const parts: string[] = [];\n\n if (result.sharedWith) {\n parts.push(`skills in ${chalk.gray(agent.targetDir)} ${chalk.gray(`(shared with ${AGENTS[result.sharedWith].label})`)}`);\n } else if (result.skills !== null) {\n parts.push(`${result.skills} skills in ${chalk.gray(agent.targetDir)}`);\n }\n\n if (result.mcp?.status === \"added\") {\n parts.push(`MCP server in ${chalk.gray(result.mcp.file)}`);\n } else if (result.mcp?.status === \"present\") {\n parts.push(`MCP server already in ${chalk.gray(result.mcp.file)}`);\n }\n\n // A tick is a claim that something was written; with nothing, it isn't.\n const mark = parts.length ? chalk.green(\"✓\") : chalk.yellow(\"!\");\n console.log(` ${mark} ${chalk.bold(agent.label)}${parts.length ? ` — ${parts.join(\", \")}` : \"\"}`);\n\n if (result.mcp?.status === \"unreadable\") {\n console.log(chalk.yellow(` ${result.mcp.file} is not plain JSON, so it was left alone — add the \"${MCP_SERVER_NAME}\" server by hand.`));\n } else if (!result.mcp) {\n console.log(chalk.gray(` ${agent.label} has no project-level MCP config — add @rebasepro/mcp in its MCP settings.`));\n }\n }\n\n const dependencyNote = mcpDependencyNote(mcpDependency, pm);\n if (dependencyNote) console.log(chalk.gray(` ${dependencyNote}`));\n\n if (skillsError) {\n console.log(chalk.yellow(` Could not install the Rebase skills: ${skillsError}`));\n console.log(chalk.yellow(\" Run `rebase skills install` in the project once dependencies are installed.\"));\n }\n}\n\n/**\n * Ask whether to set up AI agents, then which, pre-ticking what is installed.\n *\n * Interactive only; the caller has already refused a non-TTY. Returns [] when\n * the developer says no or unticks everything.\n */\nexport async function promptForAgents(home?: string): Promise<AgentKey[]> {\n const { configure } = await inquirer.prompt([{\n type: \"confirm\",\n name: \"configure\",\n message: \"Set up Rebase skills and the Rebase MCP server for your AI coding agent(s)?\",\n default: true\n }]);\n if (!configure) return [];\n\n // Installed first, so the pre-ticked boxes are the ones under the cursor.\n const detected = detectInstalledAgents(home);\n const installed = [...detected.filter(a => a.found), ...detected.filter(a => !a.found)];\n console.log(\"\");\n console.log(\"Detecting installed AI coding agents...\");\n for (const { label, marker, found } of installed) {\n if (found) console.log(` ${chalk.green(\"✓\")} ${label} — ${marker}`);\n else if (marker) console.log(chalk.gray(` ✗ ${label} — ${marker} (not found)`));\n else console.log(chalk.gray(` · ${label} — can't be detected; tick it below if you use it`));\n }\n console.log(\"\");\n\n const { selectedAgents } = await inquirer.prompt([{\n type: \"checkbox\",\n name: \"selectedAgents\",\n message: \"Select agents to configure:\",\n choices: installed.map(({ key, label, found }) => {\n const { targetDir, mcp } = AGENTS[key];\n const writes = mcp ? `${targetDir} + ${mcp.file}` : targetDir;\n return { name: `${label} ${chalk.gray(`— ${writes}`)}`, short: label, value: key, checked: found };\n })\n }]);\n\n return AGENT_KEYS.filter(key => selectedAgents.includes(key));\n}\n\n// ─── Claude Code guardrail hooks ──────────────────────────────────────────────\n\n/**\n * The guardrail every scaffold ships for Claude Code: a PostToolUse hook that\n * runs `rebase verify --quiet` after each edit under `backend/schema/` (or the\n * `tables` directory rebase.json names) or `frontend/src/cms/`, and hands any\n * problem back to the agent (exit 2, the message on stderr).\n *\n * The script keeps the file name it first shipped with: it is how\n * {@link installAgentHooks} and the settings entry find a copy already installed.\n *\n * The files live in the template, under `.claude/`, so `rebase init` copies\n * them like everything else and `rebase skills --hooks` installs the very same\n * bytes into a project that predates them. Paths are project-relative.\n */\nexport const AGENT_HOOK_SCRIPT = \".claude/hooks/post-edit-collection.sh\";\nexport const AGENT_HOOK_SETTINGS = \".claude/settings.json\";\n\n/** What installing one hook file did. */\nexport type HookWriteStatus =\n /** Written, or merged into the settings beside the hooks already there. */\n | \"added\"\n /** Already there, unchanged — or, for the settings, already registered. */\n | \"present\"\n /** There, and edited: left as it was. `--force` replaces it. */\n | \"kept\"\n /** There, edited, and replaced because `--force` asked. */\n | \"replaced\"\n /** The settings file is not plain JSON with a `hooks` object: left alone. */\n | \"unreadable\";\n\nexport interface HookWriteResult {\n file: string;\n status: HookWriteStatus;\n}\n\n/** The CLI package's own directory, from wherever this module was bundled to. */\nexport function cliPackageRoot(): string {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n while (dir !== path.dirname(dir)) {\n const manifest = path.join(dir, \"package.json\");\n if (fs.existsSync(manifest)) {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(manifest, \"utf-8\"));\n if (isRecord(parsed) && parsed.name === \"@rebasepro/cli\") return dir;\n } catch {\n // Not ours; keep walking.\n }\n }\n dir = path.dirname(dir);\n }\n throw new Error(\"Could not find the @rebasepro/cli package directory to read the hook templates from.\");\n}\n\n/**\n * Register the shipped PostToolUse hook in an existing settings file, keeping\n * every other setting and hook in it. A file that is not plain JSON is left\n * alone, for the reason {@link addJsonServer} gives.\n */\nfunction mergeHookSettings(filePath: string, shippedText: string): HookWriteStatus {\n if (!fs.existsSync(filePath)) {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, shippedText, \"utf-8\");\n return \"added\";\n }\n const text = fs.readFileSync(filePath, \"utf-8\");\n let doc: unknown;\n try {\n doc = JSON.parse(text);\n } catch {\n return \"unreadable\";\n }\n const shipped: unknown = JSON.parse(shippedText);\n const shippedEntries = isRecord(shipped) && isRecord(shipped.hooks) && Array.isArray(shipped.hooks.PostToolUse)\n ? shipped.hooks.PostToolUse\n : [];\n if (!isRecord(doc)) return \"unreadable\";\n const hooks = doc.hooks ?? {};\n if (!isRecord(hooks)) return \"unreadable\";\n const post = hooks.PostToolUse ?? [];\n if (!Array.isArray(post)) return \"unreadable\";\n if (JSON.stringify(post).includes(path.basename(AGENT_HOOK_SCRIPT))) return \"present\";\n\n doc.hooks = { ...hooks, PostToolUse: [...post, ...shippedEntries] };\n const indent = /\\n([ \\t]+)\"/.exec(text)?.[1] ?? \" \";\n fs.writeFileSync(filePath, `${JSON.stringify(doc, null, indent)}\\n`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * The SHA-256 of every version of `post-edit-collection.sh` this CLI has ever\n * written, oldest first, the current one last — hashed with CRLF read as LF,\n * so a Windows checkout of an untouched copy still matches.\n *\n * A copy that differs from today's script was read as \"edited\" and kept, so a\n * fix to the hook never reached a project scaffolded before it: `rebase skills\n * install --hooks` answered \"was edited, so it was kept — pass --force\" about a\n * file nobody had touched. A copy whose hash is one of ours is our old\n * version, and is replaced like any stale file; only a copy we never shipped is\n * the developer's.\n *\n * Append, never replace: `agent-hooks.test.ts` fails when the shipped script's\n * hash is not here, so changing the hook means adding its new hash — and the\n * old one stays, which is the whole point.\n */\nexport const SHIPPED_HOOK_SCRIPT_SHA256S: readonly string[] = [\n \"335c56f268876293c93696cb557c0ff3d8e16b60f81f67ebccbab75b0df457ac\", // 4451138e43 — first version\n \"d624f805e1eb635d87cf769ad5e6f877d07d6aa8d547052d2d7ce9d6d6b3a27b\", // ac7c5059d2 — Windows paths\n \"25c307e0c9a8838703c6e59ab5ea62ff249966823f071d26dd0dd8c2508f83a4\", // c694488bfe — CLI predating verify\n \"7a0eeaa301f3cb6b90d5675199ccfcb8fe1c2a80a327e3f7b53bc82c3f4541c2\", // af6eac33cb — rebase.json config dir\n \"dbdbfcec9c4c4e1d2643900a615585594869f6ba9fc19b5652013526367363f6\", // 08a7cd9ec8 — skip when not installed\n \"beda0ca36c3700933aab02162bca47b582a6c231bf94e494bbe84131d5e72fa8\" // backend/schema and frontend/src/cms, not config/collections\n];\n\n/** The hash {@link SHIPPED_HOOK_SCRIPT_SHA256S} records for a script's text. */\nexport function hookScriptSha256(text: string): string {\n return createHash(\"sha256\").update(text.replace(/\\r\\n/g, \"\\n\")).digest(\"hex\");\n}\n\n/**\n * Install the Claude Code guardrail into a project: the hook script, and its\n * registration in `.claude/settings.json`.\n *\n * A script the developer edited is kept unless `force`; a version this CLI\n * shipped earlier is replaced. The settings are always merged, never\n * overwritten.\n */\nexport function installAgentHooks(\n projectDir: string,\n { force = false, templateDir = path.join(cliPackageRoot(), \"templates\", \"template\") }: { force?: boolean; templateDir?: string } = {}\n): HookWriteResult[] {\n const shippedScript = fs.readFileSync(path.join(templateDir, AGENT_HOOK_SCRIPT), \"utf-8\");\n const scriptPath = path.join(projectDir, AGENT_HOOK_SCRIPT);\n let scriptStatus: HookWriteStatus;\n if (!fs.existsSync(scriptPath)) {\n scriptStatus = \"added\";\n } else {\n const current = fs.readFileSync(scriptPath, \"utf-8\");\n if (current === shippedScript) {\n scriptStatus = \"present\";\n } else {\n const ours = SHIPPED_HOOK_SCRIPT_SHA256S.includes(hookScriptSha256(current));\n scriptStatus = force || ours ? \"replaced\" : \"kept\";\n }\n }\n if (scriptStatus === \"added\" || scriptStatus === \"replaced\") {\n fs.mkdirSync(path.dirname(scriptPath), { recursive: true });\n fs.writeFileSync(scriptPath, shippedScript, \"utf-8\");\n }\n if (scriptStatus !== \"kept\") fs.chmodSync(scriptPath, 0o755);\n\n const settingsStatus = mergeHookSettings(\n path.join(projectDir, AGENT_HOOK_SETTINGS),\n fs.readFileSync(path.join(templateDir, AGENT_HOOK_SETTINGS), \"utf-8\")\n );\n return [\n { file: AGENT_HOOK_SCRIPT, status: scriptStatus },\n { file: AGENT_HOOK_SETTINGS, status: settingsStatus }\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,kBAAkB;;AAG/B,IAAa,cAAc;;AAG3B,IAAa,UAAU;;;;;;;;;;;;;;;;;AAwBvB,SAAgB,UAAU,IAA+B;CACrD,OAAO,OAAO,QACR;EAAE,SAAS;EAAO,MAAM,CAAC,QAAQ,OAAO;CAAE,IAC1C;EAAE,SAAS;EAAQ,MAAM,CAAC,QAAQ,OAAO;CAAE;AACrD;AAiBA,SAAS,SAAS,OAAkD;CAChE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E;;;;;;;;;AAUA,SAAS,cAAc,UAAkB,KAAa,OAAgD;CAClG,IAAI,MAA+B,CAAC;CACpC,IAAI,GAAG,WAAW,QAAQ,GAAG;EACzB,IAAI;EACJ,IAAI;GACA,SAAS,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC;EAC1D,QAAQ;GACJ,OAAO;EACX;EACA,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;EAC9B,MAAM;CACV;CAEA,MAAM,UAAU,IAAI,QAAQ,CAAC;CAC7B,IAAI,CAAC,SAAS,OAAO,GAAG,OAAO;CAC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OAAO,cAAc,KAAK,KAAK,eAAe,GAAG,aAAa,UAAU,MAAiD,CAAC,GACnH;CACjB,MAAM,gBAAgB,GAAG,aAAa,KAAK,KAAK,aAAa,iBAAiB,GAAG,OAAO;CACxF,MAAM,aAAa,KAAK,KAAK,YAAY,iBAAiB;CAC1D,IAAI;CACJ,IAAI,CAAC,GAAG,WAAW,UAAU,GACzB,eAAe;MACZ;EACH,MAAM,UAAU,GAAG,aAAa,YAAY,OAAO;EACnD,IAAI,YAAY,eACZ,eAAe;OACZ;GACH,MAAM,OAAO,4BAA4B,SAAS,iBAAiB,OAAO,CAAC;GAC3E,eAAe,SAAS,OAAO,aAAa;EAChD;CACJ;CACA,IAAI,iBAAiB,WAAW,iBAAiB,YAAY;EACzD,GAAG,UAAU,KAAK,QAAQ,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;EAC1D,GAAG,cAAc,YAAY,eAAe,OAAO;CACvD;CACA,IAAI,iBAAiB,QAAQ,GAAG,UAAU,YAAY,GAAK;CAE3D,MAAM,iBAAiB,kBACnB,KAAK,KAAK,YAAY,mBAAmB,GACzC,GAAG,aAAa,KAAK,KAAK,aAAa,mBAAmB,GAAG,OAAO,CACxE;CACA,OAAO,CACH;EAAE,MAAM;EAAmB,QAAQ;CAAa,GAChD;EAAE,MAAM;EAAqB,QAAQ;CAAe,CACxD;AACJ"}
|
|
1
|
+
{"version":3,"file":"agent-setup-kjdKozkF.js","names":[],"sources":["../src/commands/agent-setup.ts"],"sourcesContent":["/**\n * Setting a project up for the AI coding assistants a developer uses: the\n * Rebase skills, and the Rebase MCP server in each assistant's own config.\n *\n * `rebase init` used to end by *printing* `rebase skills install`, and nothing\n * ran it — so a generated project had pointer files telling every assistant to\n * read skills that were not there, and an MCP server only Claude Code knew\n * about. This asks once, while the project is being made, pre-ticking the\n * assistants installed on the machine.\n */\nimport chalk from \"chalk\";\nimport { createHash } from \"crypto\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport inquirer from \"inquirer\";\nimport {\n AGENT_KEYS,\n AGENTS,\n type AgentKey,\n detectInstalledAgents,\n installSkills,\n type LoadedSkill,\n loadBundledSkills\n} from \"./skills\";\nimport { fileURLToPath } from \"url\";\nimport { detectPackageManager, type PackageManager } from \"../utils/package-manager\";\nimport { cliVersion } from \"../utils/version\";\n\n/** The name the server is registered under, in every config. */\nexport const MCP_SERVER_NAME = \"rebase\";\n\n/** The MCP server's package: a devDependency of the project, pinned with the rest. */\nexport const MCP_PACKAGE = \"@rebasepro/mcp\";\n\n/** The bin {@link MCP_PACKAGE} declares. */\nexport const MCP_BIN = \"rebase-mcp\";\n\n/** The command an assistant spawns, and its arguments. */\nexport interface McpLaunch {\n command: string;\n args: string[];\n}\n\n/**\n * How an assistant starts the Rebase MCP server: the project's own copy, through\n * the project's package manager.\n *\n * Not `npx -y @rebasepro/mcp`, which fetched the newest release on every first\n * start. The server drives the project's own CLI (`pnpm exec rebase …`) and calls\n * the project's own backend (`/api/admin/schema/plan`, …), whose versions the\n * lockfile pins — so a server from the registry ran ahead of both, at every\n * start, and downloaded before it could answer. `@rebasepro/mcp` is a\n * devDependency of the scaffold, pinned to the CLI's version like every other\n * `@rebasepro` package, and this runs that copy.\n *\n * `npx --no`, not `npx`: an assistant spawns the server with no TTY, and npx\n * then assumes \"yes\" and installs a missing package from the registry under the\n * name it was given. `--no` makes a missing install an error instead.\n */\nexport function mcpLaunch(pm: PackageManager): McpLaunch {\n return pm === \"npm\"\n ? { command: \"npx\", args: [\"--no\", MCP_BIN] }\n : { command: \"pnpm\", args: [\"exec\", MCP_BIN] };\n}\n\n/** What writing one MCP config did. */\nexport type McpWriteStatus =\n /** The file was created, or the server was added beside the ones in it. */\n | \"added\"\n /** A `rebase` server was already there. It is left exactly as it was. */\n | \"present\"\n /** The file exists but is not something this can edit without losing data. */\n | \"unreadable\";\n\nexport interface McpWriteResult {\n /** Project-relative path of the config file. */\n file: string;\n status: McpWriteStatus;\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 * Add the server to a JSON config under `key`, keeping everything else in it.\n *\n * A file that does not parse as plain JSON is left alone: VS Code and Gemini\n * both accept comments in these files, and rewriting one through\n * `JSON.stringify` would delete them. Refusing costs one line of hand-editing;\n * the alternative silently costs the developer theirs.\n */\nfunction addJsonServer(filePath: string, key: string, entry: Record<string, unknown>): McpWriteStatus {\n let doc: Record<string, unknown> = {};\n if (fs.existsSync(filePath)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n } catch {\n return \"unreadable\";\n }\n if (!isRecord(parsed)) return \"unreadable\";\n doc = parsed;\n }\n\n const servers = doc[key] ?? {};\n if (!isRecord(servers)) return \"unreadable\";\n if (MCP_SERVER_NAME in servers) return \"present\";\n\n doc[key] = { ...servers, [MCP_SERVER_NAME]: entry };\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, `${JSON.stringify(doc, null, 2)}\\n`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * The Codex block, as TOML. Appended rather than merged: there is no TOML\n * parser here, and an append keeps every byte already in the file.\n */\nexport function renderCodexServer(projectDir: string, launch: McpLaunch): string {\n // A JSON string literal is a valid TOML basic string for these values.\n const str = (v: string) => JSON.stringify(v);\n return [\n `[mcp_servers.${MCP_SERVER_NAME}]`,\n `command = ${str(launch.command)}`,\n `args = [${launch.args.map(str).join(\", \")}]`,\n \"\",\n `[mcp_servers.${MCP_SERVER_NAME}.env]`,\n `REBASE_PROJECT_DIR = ${str(projectDir)}`,\n \"\"\n ].join(\"\\n\");\n}\n\nfunction addCodexServer(filePath: string, projectDir: string, launch: McpLaunch): McpWriteStatus {\n const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, \"utf-8\") : \"\";\n const table = new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.(?:${MCP_SERVER_NAME}|\"${MCP_SERVER_NAME}\")\\\\]`, \"m\");\n if (table.test(existing)) return \"present\";\n\n const separator = existing === \"\" ? \"\" : existing.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, `${existing}${separator}${renderCodexServer(projectDir, launch)}`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * Register the Rebase MCP server in the agent's project-level config, started\n * through the project's package manager (see {@link mcpLaunch}).\n *\n * Returns null for an agent with no project-level config to write.\n */\nexport function writeMcpConfig(\n agentKey: AgentKey,\n projectDir: string,\n pm: PackageManager = detectPackageManager(projectDir)\n): McpWriteResult | null {\n const mcp = AGENTS[agentKey].mcp;\n if (!mcp) return null;\n\n const filePath = path.join(projectDir, mcp.file);\n const env = { REBASE_PROJECT_DIR: mcp.projectDir };\n const { command, args } = mcpLaunch(pm);\n const write = (): McpWriteStatus => {\n switch (mcp.format) {\n case \"mcpServers\":\n return addJsonServer(filePath, \"mcpServers\", { command, args, env });\n case \"vscode\":\n // VS Code's own shape: `servers`, and an explicit transport.\n return addJsonServer(filePath, \"servers\", { type: \"stdio\", command, args, env });\n case \"codexToml\":\n return addCodexServer(filePath, mcp.projectDir, { command, args });\n }\n };\n return { file: mcp.file, status: write() };\n}\n\n/** What making sure the project depends on the MCP server did. */\nexport type McpDependencyStatus =\n /** Added to `devDependencies`, at this CLI's version: an install is due. */\n | \"added\"\n /** Already a dependency. Left at the version the project chose. */\n | \"present\"\n /** No `package.json`, or one that is not plain JSON: left alone. */\n | \"unreadable\";\n\n/**\n * Make the project depend on {@link MCP_PACKAGE}, which the config written by\n * {@link writeMcpConfig} runs from the project's own install.\n *\n * Pinned to this CLI's version, as `rebase init` pins every `@rebasepro`\n * package; a project that already lists it keeps its own choice.\n */\nexport function ensureMcpDependency(projectDir: string): McpDependencyStatus {\n const manifestPath = path.join(projectDir, \"package.json\");\n if (!fs.existsSync(manifestPath)) return \"unreadable\";\n const text = fs.readFileSync(manifestPath, \"utf-8\");\n let manifest: unknown;\n try {\n manifest = JSON.parse(text);\n } catch {\n return \"unreadable\";\n }\n if (!isRecord(manifest)) return \"unreadable\";\n for (const field of [\"dependencies\", \"devDependencies\"] as const) {\n const deps = manifest[field];\n if (isRecord(deps) && MCP_PACKAGE in deps) return \"present\";\n }\n const devDependencies = isRecord(manifest.devDependencies) ? manifest.devDependencies : {};\n const version = cliVersion();\n manifest.devDependencies = { ...devDependencies, [MCP_PACKAGE]: version === \"unknown\" ? \"latest\" : version };\n // The file's own indentation, so the change is one line in a diff.\n const indent = /\\n([ \\t]+)\"/.exec(text)?.[1] ?? \" \";\n fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, indent)}\\n`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * Point the scaffold's `.mcp.json` at the project's package manager.\n *\n * The template ships the pnpm spelling (`pnpm exec rebase-mcp`); an npm project\n * has no pnpm to run it with. Only the entry the template wrote is rewritten.\n */\nexport function retargetScaffoldMcpConfig(projectDir: string, pm: PackageManager): void {\n const filePath = path.join(projectDir, \".mcp.json\");\n if (!fs.existsSync(filePath)) return;\n let doc: unknown;\n try {\n doc = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n } catch {\n return;\n }\n const servers = isRecord(doc) ? doc.mcpServers : undefined;\n const entry = isRecord(servers) ? servers[MCP_SERVER_NAME] : undefined;\n const shipped = mcpLaunch(\"pnpm\");\n if (!isRecord(doc) || !isRecord(servers) || !isRecord(entry)) return;\n if (entry.command !== shipped.command || JSON.stringify(entry.args) !== JSON.stringify(shipped.args)) return;\n const wanted = mcpLaunch(pm);\n if (wanted.command === shipped.command && JSON.stringify(wanted.args) === JSON.stringify(shipped.args)) return;\n servers[MCP_SERVER_NAME] = { ...entry, command: wanted.command, args: wanted.args };\n fs.writeFileSync(filePath, `${JSON.stringify(doc, null, 4)}\\n`, \"utf-8\");\n}\n\n/**\n * Whether the agent's project-level config already registers the Rebase\n * server: `null` for an agent that has no such config, `false` when the file\n * is missing or does not name it. Reads only — for the hint `rebase skills\n * install` prints when it was not asked to write one.\n */\nexport function mcpServerRegistered(agentKey: AgentKey, projectDir: string): boolean | null {\n const mcp = AGENTS[agentKey].mcp;\n if (!mcp) return null;\n const filePath = path.join(projectDir, mcp.file);\n if (!fs.existsSync(filePath)) return false;\n const text = fs.readFileSync(filePath, \"utf-8\");\n if (mcp.format === \"codexToml\") {\n return new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.(?:${MCP_SERVER_NAME}|\"${MCP_SERVER_NAME}\")\\\\]`, \"m\").test(text);\n }\n try {\n const doc: unknown = JSON.parse(text);\n const servers = isRecord(doc) ? doc[mcp.format === \"vscode\" ? \"servers\" : \"mcpServers\"] : undefined;\n return isRecord(servers) && MCP_SERVER_NAME in servers;\n } catch {\n // Not plain JSON (comments): cannot tell, so do not nag.\n return null;\n }\n}\n\n/** What `configureAgents` did for one agent. */\nexport interface AgentSetupResult {\n agent: AgentKey;\n /** Skills written, or null when the bundle could not be loaded. */\n skills: number | null;\n /** An earlier agent in the same run that already wrote the skills directory. */\n sharedWith?: AgentKey;\n mcp: McpWriteResult | null;\n}\n\n/**\n * Install the skills and register the MCP server for each agent.\n *\n * Never throws for a missing skills bundle — the scaffold it runs inside must\n * not fail over its assistants — and reports it as `skills: null` instead.\n */\nexport function configureAgents(\n agents: readonly AgentKey[],\n projectDir: string,\n load: () => LoadedSkill[] = loadBundledSkills,\n pm: PackageManager = detectPackageManager(projectDir)\n): { results: AgentSetupResult[]; skillsError?: string; mcpDependency?: McpDependencyStatus } {\n let skillsError: string | undefined;\n let installed: ReturnType<typeof installSkills> = [];\n try {\n installed = installSkills(agents, load(), projectDir);\n } catch (err) {\n skillsError = err instanceof Error ? err.message : String(err);\n }\n\n const results = agents.map((agent): AgentSetupResult => {\n const skills = installed.find(r => r.agent === agent);\n return {\n agent,\n skills: skills ? skills.skills : null,\n sharedWith: skills?.sharedWith,\n mcp: writeMcpConfig(agent, projectDir, pm)\n };\n });\n // A config that runs the project's copy of the server needs the project to\n // have one.\n const registered = results.some(r => r.mcp?.status === \"added\" || r.mcp?.status === \"present\");\n return { results, skillsError, ...(registered && { mcpDependency: ensureMcpDependency(projectDir) }) };\n}\n\n/** The line to print when {@link ensureMcpDependency} changed or could not change the manifest. */\nexport function mcpDependencyNote(status: McpDependencyStatus | undefined, pm: PackageManager): string | undefined {\n if (status === \"added\") {\n return `Added ${MCP_PACKAGE} to devDependencies — run \\`${pm} install\\` before your assistant starts it.`;\n }\n if (status === \"unreadable\") {\n return `Could not add ${MCP_PACKAGE} to package.json — add it to devDependencies by hand; the MCP config runs the project's own copy.`;\n }\n return undefined;\n}\n\n/** One line per agent, for the scaffold's output. */\nexport function printAgentSetup(\n { results, skillsError, mcpDependency }: ReturnType<typeof configureAgents>,\n pm: PackageManager = \"pnpm\"\n): void {\n for (const result of results) {\n const agent = AGENTS[result.agent];\n const parts: string[] = [];\n\n if (result.sharedWith) {\n parts.push(`skills in ${chalk.gray(agent.targetDir)} ${chalk.gray(`(shared with ${AGENTS[result.sharedWith].label})`)}`);\n } else if (result.skills !== null) {\n parts.push(`${result.skills} skills in ${chalk.gray(agent.targetDir)}`);\n }\n\n if (result.mcp?.status === \"added\") {\n parts.push(`MCP server in ${chalk.gray(result.mcp.file)}`);\n } else if (result.mcp?.status === \"present\") {\n parts.push(`MCP server already in ${chalk.gray(result.mcp.file)}`);\n }\n\n // A tick is a claim that something was written; with nothing, it isn't.\n const mark = parts.length ? chalk.green(\"✓\") : chalk.yellow(\"!\");\n console.log(` ${mark} ${chalk.bold(agent.label)}${parts.length ? ` — ${parts.join(\", \")}` : \"\"}`);\n\n if (result.mcp?.status === \"unreadable\") {\n console.log(chalk.yellow(` ${result.mcp.file} is not plain JSON, so it was left alone — add the \"${MCP_SERVER_NAME}\" server by hand.`));\n } else if (!result.mcp) {\n console.log(chalk.gray(` ${agent.label} has no project-level MCP config — add @rebasepro/mcp in its MCP settings.`));\n }\n }\n\n const dependencyNote = mcpDependencyNote(mcpDependency, pm);\n if (dependencyNote) console.log(chalk.gray(` ${dependencyNote}`));\n\n if (skillsError) {\n console.log(chalk.yellow(` Could not install the Rebase skills: ${skillsError}`));\n console.log(chalk.yellow(\" Run `rebase skills install` in the project once dependencies are installed.\"));\n }\n}\n\n/**\n * Ask whether to set up AI agents, then which, pre-ticking what is installed.\n *\n * Interactive only; the caller has already refused a non-TTY. Returns [] when\n * the developer says no or unticks everything.\n */\nexport async function promptForAgents(home?: string): Promise<AgentKey[]> {\n const { configure } = await inquirer.prompt([{\n type: \"confirm\",\n name: \"configure\",\n message: \"Set up Rebase skills and the Rebase MCP server for your AI coding agent(s)?\",\n default: true\n }]);\n if (!configure) return [];\n\n // Installed first, so the pre-ticked boxes are the ones under the cursor.\n const detected = detectInstalledAgents(home);\n const installed = [...detected.filter(a => a.found), ...detected.filter(a => !a.found)];\n console.log(\"\");\n console.log(\"Detecting installed AI coding agents...\");\n for (const { label, marker, found } of installed) {\n if (found) console.log(` ${chalk.green(\"✓\")} ${label} — ${marker}`);\n else if (marker) console.log(chalk.gray(` ✗ ${label} — ${marker} (not found)`));\n else console.log(chalk.gray(` · ${label} — can't be detected; tick it below if you use it`));\n }\n console.log(\"\");\n\n const { selectedAgents } = await inquirer.prompt([{\n type: \"checkbox\",\n name: \"selectedAgents\",\n message: \"Select agents to configure:\",\n choices: installed.map(({ key, label, found }) => {\n const { targetDir, mcp } = AGENTS[key];\n const writes = mcp ? `${targetDir} + ${mcp.file}` : targetDir;\n return { name: `${label} ${chalk.gray(`— ${writes}`)}`, short: label, value: key, checked: found };\n })\n }]);\n\n return AGENT_KEYS.filter(key => selectedAgents.includes(key));\n}\n\n// ─── Claude Code guardrail hooks ──────────────────────────────────────────────\n\n/**\n * The guardrail every scaffold ships for Claude Code: a PostToolUse hook that\n * runs `rebase verify --quiet` after each edit under `backend/schema/` (or the\n * `tables` directory rebase.json names) or `frontend/src/cms/`, and hands any\n * problem back to the agent (exit 2, the message on stderr).\n *\n * The script keeps the file name it first shipped with: it is how\n * {@link installAgentHooks} and the settings entry find a copy already installed.\n *\n * The files live in the template, under `.claude/`, so `rebase init` copies\n * them like everything else and `rebase skills --hooks` installs the very same\n * bytes into a project that predates them. Paths are project-relative.\n */\nexport const AGENT_HOOK_SCRIPT = \".claude/hooks/post-edit-collection.sh\";\nexport const AGENT_HOOK_SETTINGS = \".claude/settings.json\";\n\n/** What installing one hook file did. */\nexport type HookWriteStatus =\n /** Written, or merged into the settings beside the hooks already there. */\n | \"added\"\n /** Already there, unchanged — or, for the settings, already registered. */\n | \"present\"\n /** There, and edited: left as it was. `--force` replaces it. */\n | \"kept\"\n /** There, edited, and replaced because `--force` asked. */\n | \"replaced\"\n /** The settings file is not plain JSON with a `hooks` object: left alone. */\n | \"unreadable\";\n\nexport interface HookWriteResult {\n file: string;\n status: HookWriteStatus;\n}\n\n/** The CLI package's own directory, from wherever this module was bundled to. */\nexport function cliPackageRoot(): string {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n while (dir !== path.dirname(dir)) {\n const manifest = path.join(dir, \"package.json\");\n if (fs.existsSync(manifest)) {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(manifest, \"utf-8\"));\n if (isRecord(parsed) && parsed.name === \"@rebasepro/cli\") return dir;\n } catch {\n // Not ours; keep walking.\n }\n }\n dir = path.dirname(dir);\n }\n throw new Error(\"Could not find the @rebasepro/cli package directory to read the hook templates from.\");\n}\n\n/**\n * Register the shipped PostToolUse hook in an existing settings file, keeping\n * every other setting and hook in it. A file that is not plain JSON is left\n * alone, for the reason {@link addJsonServer} gives.\n */\nfunction mergeHookSettings(filePath: string, shippedText: string): HookWriteStatus {\n if (!fs.existsSync(filePath)) {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, shippedText, \"utf-8\");\n return \"added\";\n }\n const text = fs.readFileSync(filePath, \"utf-8\");\n let doc: unknown;\n try {\n doc = JSON.parse(text);\n } catch {\n return \"unreadable\";\n }\n const shipped: unknown = JSON.parse(shippedText);\n const shippedEntries = isRecord(shipped) && isRecord(shipped.hooks) && Array.isArray(shipped.hooks.PostToolUse)\n ? shipped.hooks.PostToolUse\n : [];\n if (!isRecord(doc)) return \"unreadable\";\n const hooks = doc.hooks ?? {};\n if (!isRecord(hooks)) return \"unreadable\";\n const post = hooks.PostToolUse ?? [];\n if (!Array.isArray(post)) return \"unreadable\";\n if (JSON.stringify(post).includes(path.basename(AGENT_HOOK_SCRIPT))) return \"present\";\n\n doc.hooks = { ...hooks, PostToolUse: [...post, ...shippedEntries] };\n const indent = /\\n([ \\t]+)\"/.exec(text)?.[1] ?? \" \";\n fs.writeFileSync(filePath, `${JSON.stringify(doc, null, indent)}\\n`, \"utf-8\");\n return \"added\";\n}\n\n/**\n * The SHA-256 of every version of `post-edit-collection.sh` this CLI has ever\n * written, oldest first, the current one last — hashed with CRLF read as LF,\n * so a Windows checkout of an untouched copy still matches.\n *\n * A copy that differs from today's script was read as \"edited\" and kept, so a\n * fix to the hook never reached a project scaffolded before it: `rebase skills\n * install --hooks` answered \"was edited, so it was kept — pass --force\" about a\n * file nobody had touched. A copy whose hash is one of ours is our old\n * version, and is replaced like any stale file; only a copy we never shipped is\n * the developer's.\n *\n * Append, never replace: `agent-hooks.test.ts` fails when the shipped script's\n * hash is not here, so changing the hook means adding its new hash — and the\n * old one stays, which is the whole point.\n */\nexport const SHIPPED_HOOK_SCRIPT_SHA256S: readonly string[] = [\n \"335c56f268876293c93696cb557c0ff3d8e16b60f81f67ebccbab75b0df457ac\", // 4451138e43 — first version\n \"d624f805e1eb635d87cf769ad5e6f877d07d6aa8d547052d2d7ce9d6d6b3a27b\", // ac7c5059d2 — Windows paths\n \"25c307e0c9a8838703c6e59ab5ea62ff249966823f071d26dd0dd8c2508f83a4\", // c694488bfe — CLI predating verify\n \"7a0eeaa301f3cb6b90d5675199ccfcb8fe1c2a80a327e3f7b53bc82c3f4541c2\", // af6eac33cb — rebase.json config dir\n \"dbdbfcec9c4c4e1d2643900a615585594869f6ba9fc19b5652013526367363f6\", // 08a7cd9ec8 — skip when not installed\n \"beda0ca36c3700933aab02162bca47b582a6c231bf94e494bbe84131d5e72fa8\" // backend/schema and frontend/src/cms, not config/collections\n];\n\n/** The hash {@link SHIPPED_HOOK_SCRIPT_SHA256S} records for a script's text. */\nexport function hookScriptSha256(text: string): string {\n return createHash(\"sha256\").update(text.replace(/\\r\\n/g, \"\\n\")).digest(\"hex\");\n}\n\n/**\n * Install the Claude Code guardrail into a project: the hook script, and its\n * registration in `.claude/settings.json`.\n *\n * A script the developer edited is kept unless `force`; a version this CLI\n * shipped earlier is replaced. The settings are always merged, never\n * overwritten.\n */\nexport function installAgentHooks(\n projectDir: string,\n { force = false, templateDir = path.join(cliPackageRoot(), \"templates\", \"template\") }: { force?: boolean; templateDir?: string } = {}\n): HookWriteResult[] {\n const shippedScript = fs.readFileSync(path.join(templateDir, AGENT_HOOK_SCRIPT), \"utf-8\");\n const scriptPath = path.join(projectDir, AGENT_HOOK_SCRIPT);\n let scriptStatus: HookWriteStatus;\n if (!fs.existsSync(scriptPath)) {\n scriptStatus = \"added\";\n } else {\n const current = fs.readFileSync(scriptPath, \"utf-8\");\n if (current === shippedScript) {\n scriptStatus = \"present\";\n } else {\n const ours = SHIPPED_HOOK_SCRIPT_SHA256S.includes(hookScriptSha256(current));\n scriptStatus = force || ours ? \"replaced\" : \"kept\";\n }\n }\n if (scriptStatus === \"added\" || scriptStatus === \"replaced\") {\n fs.mkdirSync(path.dirname(scriptPath), { recursive: true });\n fs.writeFileSync(scriptPath, shippedScript, \"utf-8\");\n }\n if (scriptStatus !== \"kept\") fs.chmodSync(scriptPath, 0o755);\n\n const settingsStatus = mergeHookSettings(\n path.join(projectDir, AGENT_HOOK_SETTINGS),\n fs.readFileSync(path.join(templateDir, AGENT_HOOK_SETTINGS), \"utf-8\")\n );\n return [\n { file: AGENT_HOOK_SCRIPT, status: scriptStatus },\n { file: AGENT_HOOK_SETTINGS, status: settingsStatus }\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;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K,CAAC;EAC1D,GAAG,cAAc,YAAY,eAAe,OAAO;CACvD;CACA,IAAI,iBAAiB,QAAQ,GAAG,UAAU,YAAY,GAAK;CAE3D,MAAM,iBAAiB,kBACnB,KAAK,KAAK,YAAY,mBAAmB,GACzC,GAAG,aAAa,KAAK,KAAK,aAAa,mBAAmB,GAAG,OAAO,CACxE;CACA,OAAO,CACH;EAAE,MAAM;EAAmB,QAAQ;CAAa,GAChD;EAAE,MAAM;EAAqB,QAAQ;CAAe,CACxD;AACJ"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
|
|
2
|
-
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, i as printProjectHelp, l as startProjectCommand, r as parsedLine, s as reportTargetError } from "./project-command-
|
|
2
|
+
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, i as printProjectHelp, l as startProjectCommand, r as parsedLine, s as reportTargetError } from "./project-command-5wM_bJQt.js";
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
//#region src/commands/api.ts
|
|
@@ -272,4 +272,4 @@ function printApiHelp() {
|
|
|
272
272
|
//#endregion
|
|
273
273
|
export { apiCommand, buildApiPlan, sendApiPlan };
|
|
274
274
|
|
|
275
|
-
//# sourceMappingURL=api-
|
|
275
|
+
//# sourceMappingURL=api-CQh_qTyQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-zx1wSK5a.js","names":[],"sources":["../src/commands/api.ts"],"sourcesContent":["/**\n * CLI command: rebase api [METHOD] <path>\n *\n * Any route a Rebase app serves, with the target and credential every project\n * command resolves (`utils/project-target.ts`): the local `rebase dev`, a\n * server named by `--url` or `REBASE_BASE_URL`, or a Rebase Cloud project\n * through the console's Studio proxy. Shaped after `gh api`.\n *\n * The answer is printed as it came: JSON pretty-printed, anything else as\n * text. A non-2xx answer is still printed — the app's error envelope is the\n * useful part — and the command exits 1.\n *\n * It exists so the long tail needs no command of its own: a row's history, a\n * materialized view's refresh, the RLS audit, the schema editor's status, a\n * custom function, `/api/meta/contract`. The everyday operations have their\n * own commands (`data`, `users`, `cron`, `storage`, …), which validate their\n * input and confirm what they delete.\n */\nimport fs from \"fs\";\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { PROJECT_TARGET_FLAGS, type ProjectTarget } from \"../utils/project-target\";\nimport {\n parsedLine,\n printProjectHelp,\n projectTarget,\n reportTargetError,\n startProjectCommand\n} from \"../utils/project-command\";\n\n/** The flags `rebase api` takes, on top of the target flags. */\nexport const API_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--method\": String,\n \"-X\": \"--method\",\n \"--field\": [String],\n \"-f\": \"--field\",\n \"--raw-field\": [String],\n \"-F\": \"--raw-field\",\n \"--input\": String,\n \"--header\": [String],\n \"-H\": \"--header\",\n \"--include\": Boolean,\n \"-i\": \"--include\",\n \"--silent\": Boolean\n} satisfies arg.Spec;\n\nconst METHODS = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"]);\n\n/** What one `rebase api` line asks for. Exported for its tests. */\nexport interface ApiRequestPlan {\n method: string;\n path: string;\n query: Record<string, string[]>;\n body?: string;\n contentType?: string;\n headers: Record<string, string>;\n}\n\n/**\n * The path a request goes to: `/…` as written, anything else under `/api/`\n * — `data/posts` is `/api/data/posts`, as `gh api repos/x` is relative to its\n * API root. A full URL is refused: the target flags say where requests go, so\n * a URL in the path would send the credential somewhere they did not choose.\n */\nexport function resolveApiPath(raw: string): string {\n const trimmed = raw.trim();\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed)) {\n throw new UsageError(\n `\\`rebase api\\` takes a path, not a URL (${trimmed}). Name the server with --url and the path after it: `\n + \"rebase api --url https://example.com /api/health.\"\n );\n }\n return trimmed.startsWith(\"/\") ? trimmed : `/api/${trimmed}`;\n}\n\n/** `key=value` split at its first `=`. */\nfunction splitField(raw: string, flag: string): [string, string] {\n const at = raw.indexOf(\"=\");\n if (at <= 0) throw new UsageError(`${flag} takes key=value (got \"${raw}\").`);\n return [raw.slice(0, at), raw.slice(at + 1)];\n}\n\n/**\n * A typed field's value, as `gh api -F` reads one: `true`, `false` and `null`\n * as themselves, a number as a number, `@file` as that file's text, a JSON\n * array or object as JSON, anything else as the string.\n */\nexport function typedFieldValue(raw: string): unknown {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n if (raw === \"null\") return null;\n if (/^-?\\d+(\\.\\d+)?$/.test(raw)) return Number(raw);\n if (raw.startsWith(\"@\")) {\n const file = raw.slice(1);\n try {\n return fs.readFileSync(file === \"-\" ? 0 : file, \"utf8\");\n } catch (e) {\n throw new UsageError(`Cannot read ${file}: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n if ((raw.startsWith(\"{\") && raw.endsWith(\"}\")) || (raw.startsWith(\"[\") && raw.endsWith(\"]\"))) {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n }\n return raw;\n}\n\n/**\n * Resolve a line into the request it describes. Exported for its tests.\n *\n * The method is the first argument when it is one (`rebase api DELETE\n * data/posts/1`), `--method`, or GET — POST when the line carries a body.\n * Fields go into the query string of a GET, HEAD or DELETE and into a JSON\n * body otherwise, as with `gh api`.\n */\nexport function resolveApiRequest(rawArgs: string[]): { plan: ApiRequestPlan; flags: ReturnType<typeof parseApiLine>[\"flags\"] } {\n const { flags, positionals } = parseApiLine(rawArgs);\n let words = positionals;\n let method = flags[\"--method\"]?.toUpperCase();\n if (words.length === 2) {\n const first = words[0].toUpperCase();\n if (!METHODS.has(first)) {\n throw new UsageError(`\\`rebase api\\` takes [METHOD] <path>; \"${words[0]}\" is not an HTTP method.`);\n }\n if (method && method !== first) throw new UsageError(`The method is given twice: ${first} and --method ${method}.`);\n method = first;\n words = words.slice(1);\n }\n if (words.length !== 1) throw new UsageError(\"`rebase api` needs a path: rebase api data/posts (see `rebase api --help`).\");\n const plan = buildApiPlan({\n method,\n path: resolveApiPath(words[0]),\n fields: flags[\"--field\"],\n rawFields: flags[\"--raw-field\"],\n input: flags[\"--input\"],\n headers: flags[\"--header\"]\n });\n return { plan, flags };\n}\n\n/** What a line says about a request, before it is resolved into one. */\nexport interface ApiRequestParts {\n method?: string;\n /** The path, `/api/…` already resolved, optionally with a query string. */\n path: string;\n fields?: readonly string[];\n rawFields?: readonly string[];\n input?: string;\n headers?: readonly string[];\n}\n\n/**\n * Resolve the parts of a line into the request they describe. Shared by\n * `rebase api` and `rebase functions invoke`. Exported for tests.\n *\n * The method is the one given, or GET — POST with `--input`. Fields go into\n * the query string of a GET, HEAD or DELETE and into a JSON body otherwise.\n * Unlike `gh api`, a field alone never makes the request a POST.\n */\nexport function buildApiPlan(parts: ApiRequestParts): ApiRequestPlan {\n const method = parts.method?.toUpperCase();\n if (method && !METHODS.has(method)) throw new UsageError(`--method ${method} is not an HTTP method.`);\n\n const fields: Array<[string, unknown]> = [\n ...(parts.fields ?? []).map((raw): [string, unknown] => splitField(raw, \"--field\")),\n ...(parts.rawFields ?? []).map((raw): [string, unknown] => {\n const [key, value] = splitField(raw, \"--raw-field\");\n return [key, typedFieldValue(value)];\n })\n ];\n\n let input: string | undefined;\n if (parts.input !== undefined) {\n const file = parts.input;\n try {\n input = fs.readFileSync(file === \"-\" ? 0 : file, \"utf8\");\n } catch (e) {\n throw new UsageError(`Cannot read --input ${file}: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n // GET unless the line says otherwise. `gh api` switches to POST as soon as\n // a field is added; here that would turn `rebase api data/posts -f limit=5`\n // into creating a row. A write is named (`POST`, `-X PATCH`) or carries a\n // whole body (`--input`).\n const resolvedMethod = method ?? (input !== undefined ? \"POST\" : \"GET\");\n const inQuery = resolvedMethod === \"GET\" || resolvedMethod === \"HEAD\" || resolvedMethod === \"DELETE\";\n if (input !== undefined && fields.length > 0 && !inQuery) {\n throw new UsageError(\"--input is the whole body; fields cannot be added to it. Give one or the other.\");\n }\n\n const headers: Record<string, string> = {};\n for (const raw of parts.headers ?? []) {\n const at = raw.indexOf(\":\");\n if (at <= 0) throw new UsageError(`--header takes \"Name: value\" (got \"${raw}\").`);\n const name = raw.slice(0, at).trim();\n if (/^authorization$/i.test(name)) {\n throw new UsageError(\"Pass a bearer with --token, not an Authorization header: the target decides where credentials go.\");\n }\n headers[name] = raw.slice(at + 1).trim();\n }\n\n const query: Record<string, string[]> = {};\n const [bare, search] = parts.path.split(/\\?(.*)/s, 2);\n if (search) {\n for (const [key, value] of new URLSearchParams(search)) (query[key] ??= []).push(value);\n }\n\n const plan: ApiRequestPlan = { method: resolvedMethod, path: bare, query, headers };\n if (inQuery) {\n for (const [key, value] of fields) (query[key] ??= []).push(typeof value === \"string\" ? value : JSON.stringify(value));\n }\n if (input !== undefined) {\n plan.body = input;\n plan.contentType = looksLikeJson(input) ? \"application/json\" : \"application/octet-stream\";\n } else if (fields.length > 0 && !inQuery) {\n plan.body = JSON.stringify(Object.fromEntries(fields));\n plan.contentType = \"application/json\";\n }\n return plan;\n}\n\nfunction looksLikeJson(text: string): boolean {\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction parseApiLine(rawArgs: string[]) {\n return parseCommandArgs({\n spec: API_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"api\",\n maxPositionals: 2\n });\n}\n\nexport async function apiCommand(rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (wantsHelp(rawArgs)) {\n printApiHelp();\n return;\n }\n const { plan, flags } = parsedLine(() => resolveApiRequest(rawArgs));\n const target = await projectTarget(flags, { command: \"api\" });\n await sendApiPlan(target, plan, { include: flags[\"--include\"] === true, silent: flags[\"--silent\"] === true });\n}\n\n/**\n * Send a resolved request and print the answer as it came: JSON\n * pretty-printed, anything else as text, the status line and headers first\n * with `include`. A non-2xx answer is printed too, and exits 1.\n */\nexport async function sendApiPlan(\n target: ProjectTarget,\n plan: ApiRequestPlan,\n options: { include?: boolean; silent?: boolean } = {}\n): Promise<void> {\n let res: Response;\n try {\n res = await target.request(plan.path, {\n method: plan.method,\n query: plan.query,\n body: plan.body,\n headers: { ...plan.headers, ...(plan.contentType ? { \"Content-Type\": plan.contentType } : {}) }\n });\n } catch (e) {\n reportTargetError(e, target);\n }\n\n if (options.include) {\n process.stdout.write(`HTTP ${res.status} ${res.statusText}\\n`);\n res.headers.forEach((value, name) => process.stdout.write(`${name}: ${value}\\n`));\n process.stdout.write(\"\\n\");\n }\n\n const text = plan.method === \"HEAD\" ? \"\" : await res.text();\n if (!options.silent && text) {\n let printed = text;\n try {\n printed = JSON.stringify(JSON.parse(text), null, 2);\n } catch {\n // Not JSON: printed as it came.\n }\n process.stdout.write(printed.endsWith(\"\\n\") ? printed : `${printed}\\n`);\n }\n\n if (res.status >= 300) {\n // The body above says why; this is the exit code a script branches on,\n // and one line for whoever reads the terminal.\n process.stderr.write(chalk.red(`✗ HTTP ${res.status} from ${target.label}\\n`));\n process.exit(1);\n }\n}\n\nfunction printApiHelp(): void {\n printProjectHelp({\n command: \"api\",\n usage: \"[METHOD] <path>\",\n title: \"Send any request to the app's API, with the project's credential\",\n actions: [\n {\n action: \"[METHOD] <path>\",\n description: \"data/posts is /api/data/posts; a path starting with / is sent as written\",\n flags: [\n [\"--method, -X <method>\", \"The HTTP method (else GET; POST with --input — a field alone never writes)\"],\n [\"--field, -f <key=value>\", \"A string field: query string on GET/HEAD/DELETE, JSON body otherwise\"],\n [\"--raw-field, -F <key=value>\", \"A typed field: true/false/null, numbers, JSON, @file\"],\n [\"--input <file|->\", \"The whole request body, from a file or stdin\"],\n [\"--header, -H <\\\"Name: value\\\">\", \"An extra request header (never Authorization: use --token)\"],\n [\"--include, -i\", \"Print the status line and response headers first\"],\n [\"--silent\", \"Print nothing; only the exit code says how it went\"]\n ]\n }\n ],\n notes: [\n \"Examples:\",\n \" rebase api data/posts -f status=eq.published -f limit=5\",\n \" rebase api POST data/posts -F title=Hello -F published=true\",\n \" rebase api /api/admin/rls-audit --project acme\",\n \" rebase api functions/hello --anon\",\n \"A non-2xx answer is printed and exits 1. The everyday operations have their own commands: rebase data, users, cron, storage, functions, logs.\"\n ]\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,YAAY;CACrB,GAAG;CACH,YAAY;CACZ,MAAM;CACN,WAAW,CAAC,MAAM;CAClB,MAAM;CACN,eAAe,CAAC,MAAM;CACtB,MAAM;CACN,WAAW;CACX,YAAY,CAAC,MAAM;CACnB,MAAM;CACN,aAAa;CACb,MAAM;CACN,YAAY;AAChB;AAEA,IAAM,0BAAU,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAO;CAAS;CAAU;CAAQ;AAAS,CAAC;;;;;;;AAkBpF,SAAgB,eAAe,KAAqB;CAChD,MAAM,UAAU,IAAI,KAAK;CACzB,IAAI,2BAA2B,KAAK,OAAO,GACvC,MAAM,IAAI,WACN,2CAA2C,QAAQ,uGAEvD;CAEJ,OAAO,QAAQ,WAAW,GAAG,IAAI,UAAU,QAAQ;AACvD;;AAGA,SAAS,WAAW,KAAa,MAAgC;CAC7D,MAAM,KAAK,IAAI,QAAQ,GAAG;CAC1B,IAAI,MAAM,GAAG,MAAM,IAAI,WAAW,GAAG,KAAK,yBAAyB,IAAI,IAAI;CAC3E,OAAO,CAAC,IAAI,MAAM,GAAG,EAAE,GAAG,IAAI,MAAM,KAAK,CAAC,CAAC;AAC/C;;;;;;AAOA,SAAgB,gBAAgB,KAAsB;CAClD,IAAI,QAAQ,QAAQ,OAAO;CAC3B,IAAI,QAAQ,SAAS,OAAO;CAC5B,IAAI,QAAQ,QAAQ,OAAO;CAC3B,IAAI,kBAAkB,KAAK,GAAG,GAAG,OAAO,OAAO,GAAG;CAClD,IAAI,IAAI,WAAW,GAAG,GAAG;EACrB,MAAM,OAAO,IAAI,MAAM,CAAC;EACxB,IAAI;GACA,OAAO,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CLI command: rebase api [METHOD] <path>\n *\n * Any route a Rebase app serves, with the target and credential every project\n * command resolves (`utils/project-target.ts`): the local `rebase dev`, a\n * server named by `--url` or `REBASE_BASE_URL`, or a Rebase Cloud project\n * through the console's Studio proxy. Shaped after `gh api`.\n *\n * The answer is printed as it came: JSON pretty-printed, anything else as\n * text. A non-2xx answer is still printed — the app's error envelope is the\n * useful part — and the command exits 1.\n *\n * It exists so the long tail needs no command of its own: a row's history, a\n * materialized view's refresh, the RLS audit, the schema editor's status, a\n * custom function, `/api/meta/contract`. The everyday operations have their\n * own commands (`data`, `users`, `cron`, `storage`, …), which validate their\n * input and confirm what they delete.\n */\nimport fs from \"fs\";\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { PROJECT_TARGET_FLAGS, type ProjectTarget } from \"../utils/project-target\";\nimport {\n parsedLine,\n printProjectHelp,\n projectTarget,\n reportTargetError,\n startProjectCommand\n} from \"../utils/project-command\";\n\n/** The flags `rebase api` takes, on top of the target flags. */\nexport const API_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--method\": String,\n \"-X\": \"--method\",\n \"--field\": [String],\n \"-f\": \"--field\",\n \"--raw-field\": [String],\n \"-F\": \"--raw-field\",\n \"--input\": String,\n \"--header\": [String],\n \"-H\": \"--header\",\n \"--include\": Boolean,\n \"-i\": \"--include\",\n \"--silent\": Boolean\n} satisfies arg.Spec;\n\nconst METHODS = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"]);\n\n/** What one `rebase api` line asks for. Exported for its tests. */\nexport interface ApiRequestPlan {\n method: string;\n path: string;\n query: Record<string, string[]>;\n body?: string;\n contentType?: string;\n headers: Record<string, string>;\n}\n\n/**\n * The path a request goes to: `/…` as written, anything else under `/api/`\n * — `data/posts` is `/api/data/posts`, as `gh api repos/x` is relative to its\n * API root. A full URL is refused: the target flags say where requests go, so\n * a URL in the path would send the credential somewhere they did not choose.\n */\nexport function resolveApiPath(raw: string): string {\n const trimmed = raw.trim();\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed)) {\n throw new UsageError(\n `\\`rebase api\\` takes a path, not a URL (${trimmed}). Name the server with --url and the path after it: `\n + \"rebase api --url https://example.com /api/health.\"\n );\n }\n return trimmed.startsWith(\"/\") ? trimmed : `/api/${trimmed}`;\n}\n\n/** `key=value` split at its first `=`. */\nfunction splitField(raw: string, flag: string): [string, string] {\n const at = raw.indexOf(\"=\");\n if (at <= 0) throw new UsageError(`${flag} takes key=value (got \"${raw}\").`);\n return [raw.slice(0, at), raw.slice(at + 1)];\n}\n\n/**\n * A typed field's value, as `gh api -F` reads one: `true`, `false` and `null`\n * as themselves, a number as a number, `@file` as that file's text, a JSON\n * array or object as JSON, anything else as the string.\n */\nexport function typedFieldValue(raw: string): unknown {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n if (raw === \"null\") return null;\n if (/^-?\\d+(\\.\\d+)?$/.test(raw)) return Number(raw);\n if (raw.startsWith(\"@\")) {\n const file = raw.slice(1);\n try {\n return fs.readFileSync(file === \"-\" ? 0 : file, \"utf8\");\n } catch (e) {\n throw new UsageError(`Cannot read ${file}: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n if ((raw.startsWith(\"{\") && raw.endsWith(\"}\")) || (raw.startsWith(\"[\") && raw.endsWith(\"]\"))) {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n }\n return raw;\n}\n\n/**\n * Resolve a line into the request it describes. Exported for its tests.\n *\n * The method is the first argument when it is one (`rebase api DELETE\n * data/posts/1`), `--method`, or GET — POST when the line carries a body.\n * Fields go into the query string of a GET, HEAD or DELETE and into a JSON\n * body otherwise, as with `gh api`.\n */\nexport function resolveApiRequest(rawArgs: string[]): { plan: ApiRequestPlan; flags: ReturnType<typeof parseApiLine>[\"flags\"] } {\n const { flags, positionals } = parseApiLine(rawArgs);\n let words = positionals;\n let method = flags[\"--method\"]?.toUpperCase();\n if (words.length === 2) {\n const first = words[0].toUpperCase();\n if (!METHODS.has(first)) {\n throw new UsageError(`\\`rebase api\\` takes [METHOD] <path>; \"${words[0]}\" is not an HTTP method.`);\n }\n if (method && method !== first) throw new UsageError(`The method is given twice: ${first} and --method ${method}.`);\n method = first;\n words = words.slice(1);\n }\n if (words.length !== 1) throw new UsageError(\"`rebase api` needs a path: rebase api data/posts (see `rebase api --help`).\");\n const plan = buildApiPlan({\n method,\n path: resolveApiPath(words[0]),\n fields: flags[\"--field\"],\n rawFields: flags[\"--raw-field\"],\n input: flags[\"--input\"],\n headers: flags[\"--header\"]\n });\n return { plan, flags };\n}\n\n/** What a line says about a request, before it is resolved into one. */\nexport interface ApiRequestParts {\n method?: string;\n /** The path, `/api/…` already resolved, optionally with a query string. */\n path: string;\n fields?: readonly string[];\n rawFields?: readonly string[];\n input?: string;\n headers?: readonly string[];\n}\n\n/**\n * Resolve the parts of a line into the request they describe. Shared by\n * `rebase api` and `rebase functions invoke`. Exported for tests.\n *\n * The method is the one given, or GET — POST with `--input`. Fields go into\n * the query string of a GET, HEAD or DELETE and into a JSON body otherwise.\n * Unlike `gh api`, a field alone never makes the request a POST.\n */\nexport function buildApiPlan(parts: ApiRequestParts): ApiRequestPlan {\n const method = parts.method?.toUpperCase();\n if (method && !METHODS.has(method)) throw new UsageError(`--method ${method} is not an HTTP method.`);\n\n const fields: Array<[string, unknown]> = [\n ...(parts.fields ?? []).map((raw): [string, unknown] => splitField(raw, \"--field\")),\n ...(parts.rawFields ?? []).map((raw): [string, unknown] => {\n const [key, value] = splitField(raw, \"--raw-field\");\n return [key, typedFieldValue(value)];\n })\n ];\n\n let input: string | undefined;\n if (parts.input !== undefined) {\n const file = parts.input;\n try {\n input = fs.readFileSync(file === \"-\" ? 0 : file, \"utf8\");\n } catch (e) {\n throw new UsageError(`Cannot read --input ${file}: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n // GET unless the line says otherwise. `gh api` switches to POST as soon as\n // a field is added; here that would turn `rebase api data/posts -f limit=5`\n // into creating a row. A write is named (`POST`, `-X PATCH`) or carries a\n // whole body (`--input`).\n const resolvedMethod = method ?? (input !== undefined ? \"POST\" : \"GET\");\n const inQuery = resolvedMethod === \"GET\" || resolvedMethod === \"HEAD\" || resolvedMethod === \"DELETE\";\n if (input !== undefined && fields.length > 0 && !inQuery) {\n throw new UsageError(\"--input is the whole body; fields cannot be added to it. Give one or the other.\");\n }\n\n const headers: Record<string, string> = {};\n for (const raw of parts.headers ?? []) {\n const at = raw.indexOf(\":\");\n if (at <= 0) throw new UsageError(`--header takes \"Name: value\" (got \"${raw}\").`);\n const name = raw.slice(0, at).trim();\n if (/^authorization$/i.test(name)) {\n throw new UsageError(\"Pass a bearer with --token, not an Authorization header: the target decides where credentials go.\");\n }\n headers[name] = raw.slice(at + 1).trim();\n }\n\n const query: Record<string, string[]> = {};\n const [bare, search] = parts.path.split(/\\?(.*)/s, 2);\n if (search) {\n for (const [key, value] of new URLSearchParams(search)) (query[key] ??= []).push(value);\n }\n\n const plan: ApiRequestPlan = { method: resolvedMethod, path: bare, query, headers };\n if (inQuery) {\n for (const [key, value] of fields) (query[key] ??= []).push(typeof value === \"string\" ? value : JSON.stringify(value));\n }\n if (input !== undefined) {\n plan.body = input;\n plan.contentType = looksLikeJson(input) ? \"application/json\" : \"application/octet-stream\";\n } else if (fields.length > 0 && !inQuery) {\n plan.body = JSON.stringify(Object.fromEntries(fields));\n plan.contentType = \"application/json\";\n }\n return plan;\n}\n\nfunction looksLikeJson(text: string): boolean {\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction parseApiLine(rawArgs: string[]) {\n return parseCommandArgs({\n spec: API_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"api\",\n maxPositionals: 2\n });\n}\n\nexport async function apiCommand(rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (wantsHelp(rawArgs)) {\n printApiHelp();\n return;\n }\n const { plan, flags } = parsedLine(() => resolveApiRequest(rawArgs));\n const target = await projectTarget(flags, { command: \"api\" });\n await sendApiPlan(target, plan, { include: flags[\"--include\"] === true, silent: flags[\"--silent\"] === true });\n}\n\n/**\n * Send a resolved request and print the answer as it came: JSON\n * pretty-printed, anything else as text, the status line and headers first\n * with `include`. A non-2xx answer is printed too, and exits 1.\n */\nexport async function sendApiPlan(\n target: ProjectTarget,\n plan: ApiRequestPlan,\n options: { include?: boolean; silent?: boolean } = {}\n): Promise<void> {\n let res: Response;\n try {\n res = await target.request(plan.path, {\n method: plan.method,\n query: plan.query,\n body: plan.body,\n headers: { ...plan.headers, ...(plan.contentType ? { \"Content-Type\": plan.contentType } : {}) }\n });\n } catch (e) {\n reportTargetError(e, target);\n }\n\n if (options.include) {\n process.stdout.write(`HTTP ${res.status} ${res.statusText}\\n`);\n res.headers.forEach((value, name) => process.stdout.write(`${name}: ${value}\\n`));\n process.stdout.write(\"\\n\");\n }\n\n const text = plan.method === \"HEAD\" ? \"\" : await res.text();\n if (!options.silent && text) {\n let printed = text;\n try {\n printed = JSON.stringify(JSON.parse(text), null, 2);\n } catch {\n // Not JSON: printed as it came.\n }\n process.stdout.write(printed.endsWith(\"\\n\") ? printed : `${printed}\\n`);\n }\n\n if (res.status >= 300) {\n // The body above says why; this is the exit code a script branches on,\n // and one line for whoever reads the terminal.\n process.stderr.write(chalk.red(`✗ HTTP ${res.status} from ${target.label}\\n`));\n process.exit(1);\n }\n}\n\nfunction printApiHelp(): void {\n printProjectHelp({\n command: \"api\",\n usage: \"[METHOD] <path>\",\n title: \"Send any request to the app's API, with the project's credential\",\n actions: [\n {\n action: \"[METHOD] <path>\",\n description: \"data/posts is /api/data/posts; a path starting with / is sent as written\",\n flags: [\n [\"--method, -X <method>\", \"The HTTP method (else GET; POST with --input — a field alone never writes)\"],\n [\"--field, -f <key=value>\", \"A string field: query string on GET/HEAD/DELETE, JSON body otherwise\"],\n [\"--raw-field, -F <key=value>\", \"A typed field: true/false/null, numbers, JSON, @file\"],\n [\"--input <file|->\", \"The whole request body, from a file or stdin\"],\n [\"--header, -H <\\\"Name: value\\\">\", \"An extra request header (never Authorization: use --token)\"],\n [\"--include, -i\", \"Print the status line and response headers first\"],\n [\"--silent\", \"Print nothing; only the exit code says how it went\"]\n ]\n }\n ],\n notes: [\n \"Examples:\",\n \" rebase api data/posts -f status=eq.published -f limit=5\",\n \" rebase api POST data/posts -F title=Hello -F published=true\",\n \" rebase api /api/admin/rls-audit --project acme\",\n \" rebase api functions/hello --anon\",\n \"A non-2xx answer is printed and exits 1. The everyday operations have their own commands: rebase data, users, cron, storage, functions, logs.\"\n ]\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,YAAY;CACrB,GAAG;CACH,YAAY;CACZ,MAAM;CACN,WAAW,CAAC,MAAM;CAClB,MAAM;CACN,eAAe,CAAC,MAAM;CACtB,MAAM;CACN,WAAW;CACX,YAAY,CAAC,MAAM;CACnB,MAAM;CACN,aAAa;CACb,MAAM;CACN,YAAY;AAChB;AAEA,IAAM,0BAAU,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAO;CAAS;CAAU;CAAQ;AAAS,CAAC;;;;;;;AAkBpF,SAAgB,eAAe,KAAqB;CAChD,MAAM,UAAU,IAAI,KAAK;CACzB,IAAI,2BAA2B,KAAK,OAAO,GACvC,MAAM,IAAI,WACN,2CAA2C,QAAQ,uGAEvD;CAEJ,OAAO,QAAQ,WAAW,GAAG,IAAI,UAAU,QAAQ;AACvD;;AAGA,SAAS,WAAW,KAAa,MAAgC;CAC7D,MAAM,KAAK,IAAI,QAAQ,GAAG;CAC1B,IAAI,MAAM,GAAG,MAAM,IAAI,WAAW,GAAG,KAAK,yBAAyB,IAAI,IAAI;CAC3E,OAAO,CAAC,IAAI,MAAM,GAAG,EAAE,GAAG,IAAI,MAAM,KAAK,CAAC,CAAC;AAC/C;;;;;;AAOA,SAAgB,gBAAgB,KAAsB;CAClD,IAAI,Q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CAAkC,4DAA4D;IAC/F,CAAC,iBAAiB,kDAAkD;IACpE,CAAC,YAAY,oDAAoD;GACrE;EACJ,CACJ;EACA,OAAO;GACH;GACA;GACA;GACA;GACA;GACA;EACJ;CACJ,CAAC;AACL"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
|
|
3
3
|
import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
|
|
4
|
-
import { c as findProjectRoot } from "./project-
|
|
4
|
+
import { c as findProjectRoot } from "./project-CQ5nKddJ.js";
|
|
5
5
|
import { t as cliUserAgent } from "./version-ONIeo7jl.js";
|
|
6
|
-
import { a as serverUnreachableHint } from "./dev-server-
|
|
7
|
-
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, h as projectServiceKey } from "./project-command-
|
|
8
|
-
import { l as confirmDestructive } from "./context-
|
|
6
|
+
import { a as serverUnreachableHint } from "./dev-server-dsabI0UT.js";
|
|
7
|
+
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, h as projectServiceKey } from "./project-command-5wM_bJQt.js";
|
|
8
|
+
import { l as confirmDestructive } from "./context-C9lz1vTS.js";
|
|
9
9
|
import chalk from "chalk";
|
|
10
10
|
import arg from "arg";
|
|
11
11
|
import { ADMIN_SCOPES, DATA_PLANE_SCOPES, KEY_MANAGEMENT_SCOPES, parseScope } from "@rebasepro/types";
|
|
@@ -631,4 +631,4 @@ ${chalk.green.bold("Examples")}
|
|
|
631
631
|
//#endregion
|
|
632
632
|
export { describeFailure as n, api_keys_exports as t };
|
|
633
633
|
|
|
634
|
-
//# sourceMappingURL=api-keys-
|
|
634
|
+
//# sourceMappingURL=api-keys-CG2IpknI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-keys-DaWN8dyI.js","names":[],"sources":["../src/commands/api-keys.ts"],"sourcesContent":["/**\n * CLI command: rebase api-keys <action>\n *\n * The project's service keys, through `/api/admin/api-keys`, authenticated with\n * the service key from `.env`.\n *\n * Subcommands:\n * list — List the service keys (masked): kind, scopes, roles\n * get — Show one key\n * create — Create a service key holding the scopes named on the line\n * revoke — Revoke a key\n * scopes — List the scopes this backend knows, and which the caller holds\n */\nimport chalk from \"chalk\";\nimport arg from \"arg\";\nimport { createRebaseClient, RebaseApiError } from \"@rebasepro/client\";\nimport {\n ADMIN_SCOPES,\n DATA_PLANE_SCOPES,\n KEY_MANAGEMENT_SCOPES,\n parseScope,\n type ApiKeyMasked,\n type ApiKeyWithSecret,\n type CreateApiKeyRequest,\n type UpdateApiKeyRequest,\n type ScopeSummary\n} from \"@rebasepro/types\";\nimport { findProjectRoot } from \"../utils/project\";\nimport { PROJECT_TARGET_FLAGS, cloudTargetNote, projectServiceKey, resolveBackendAddress } from \"../utils/project-target\";\nimport { projectTarget } from \"../utils/project-command\";\nimport { confirmDestructive } from \"./cloud/context\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { serverUnreachableHint } from \"../utils/dev-server\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const API_KEYS_SUBCOMMANDS = [\"list\", \"get\", \"create\", \"update\", \"revoke\", \"scopes\"] as const;\n\n/* ═══════════════════════════════════════════════════════════════\n Where the backend is — shared with every project command\n ═══════════════════════════════════════════════════════════════ */\n\n// The address rules (REBASE_BASE_URL, then a live `rebase dev`, nothing\n// guessed) moved to `utils/project-target.ts` with the other project\n// commands; re-exported here for the callers and tests that import them\n// from this module.\nexport { cloudTargetNote, resolveBackendAddress, type BackendAddress } from \"../utils/project-target\";\n\n/**\n * The address to send the service key to, or the end of the command.\n *\n * Exits before any request is made: the refusal is the point.\n */\nexport function requireBackendUrl(env: Record<string, string>, projectRoot: string): string {\n const address = resolveBackendAddress(env, projectRoot);\n const note = cloudTargetNote(address);\n if (note) console.error(chalk.yellow(` ⚠ ${note}`));\n if (address.url !== null) return address.url;\n\n console.error(chalk.red(\"✗ No server to send the request to.\"));\n console.error(chalk.gray(` ${address.reason}`));\n process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n The backend, through the SDK\n ═══════════════════════════════════════════════════════════════ */\n\ntype ProjectClient = ReturnType<typeof createRebaseClient>;\n\ninterface Connection {\n client: ProjectClient;\n baseUrl: string;\n /** The variable the service key was read from, for a hint that names it. */\n keyVariable: ServiceKeyVariable;\n}\n\n/** Where a service key is read from: the name a scaffold writes, or the older one. */\ntype ServiceKeyVariable = \"REBASE_SERVICE_KEY\" | \"SERVICE_KEY\";\n\n/**\n * An SDK client for this project's backend, holding the service key — or the\n * credential the target flags name, resolved as every project command\n * resolves it (`--project`, `--cloud`, `--url`, `--token`, `--session`).\n *\n * The service key is the project's own machine identity — the `admin` role,\n * every scope — so it is what may list, mint and revoke service keys. It is a\n * static bearer token: no session to restore or refresh, and no socket. An\n * `rk_` key is refused on these routes whatever it holds.\n *\n * The line was already parsed strictly by the action's own spec, which\n * declares the target flags; they are read again here only for their values.\n */\nasync function connect(rawArgs: string[]): Promise<Connection> {\n const targetFlags = arg(PROJECT_TARGET_FLAGS, { argv: rawArgs.slice(2), permissive: true });\n const target = await projectTarget(targetFlags, { command: \"api-keys\" });\n const token = await target.bearer();\n const client = createRebaseClient({\n baseUrl: target.baseUrl,\n ...(token ? { token } : {}),\n realtime: false,\n headers: { \"User-Agent\": cliUserAgent() },\n auth: { persistSession: false, autoRefresh: false }\n });\n const keyVariable = target.credential === \"service-key\" ? projectServiceKey(findProjectRoot())?.variable : undefined;\n return {\n client,\n baseUrl: target.label,\n keyVariable: keyVariable === \"SERVICE_KEY\" ? \"SERVICE_KEY\" : \"REBASE_SERVICE_KEY\"\n };\n}\n\n/**\n * What to print when a request fails: the server's error code and message,\n * which is what says why — `SCOPE_EXCEEDS_CREATOR`, `INVALID_SCOPES`,\n * `ROLE_EXCEEDS_CREATOR`, `KEY_MANAGEMENT_SCOPE` — and a hint where one helps.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeFailure(\n action: string,\n error: unknown,\n baseUrl: string,\n keyVariable: ServiceKeyVariable = \"REBASE_SERVICE_KEY\"\n): string[] {\n if (!(error instanceof RebaseApiError)) {\n return [`✗ ${action}: ${error instanceof Error ? error.message : String(error)}`];\n }\n if (error.status === 0 || error.code === \"NETWORK_ERROR\") {\n return [`✗ ${action}: ${error.message}`, ...serverUnreachableHint(baseUrl)];\n }\n\n const label = [error.code, error.status ? `(${error.status})` : undefined].filter(Boolean).join(\" \");\n const lines = [`✗ ${action}${label ? ` — ${label}` : \"\"}: ${error.message}`];\n\n if (error.status === 401) {\n lines.push(` The server at ${baseUrl} did not accept ${keyVariable} from .env — is it this project's server?`);\n }\n // The message names the target that is not there; what *is* there rides\n // in `details`, and is the thing to pick from.\n if (error.code === \"UNKNOWN_SCOPE_TARGET\" && isRecord(error.details)) {\n for (const [kind, title] of [[\"collections\", \"Tables\"], [\"buckets\", \"Buckets\"], [\"functions\", \"Functions\"]] as const) {\n const names = error.details[kind];\n if (Array.isArray(names) && names.length > 0) {\n lines.push(` ${title}: ${names.map(String).join(\", \")}`);\n }\n }\n }\n return lines;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction fail(action: string, error: unknown, connection: Connection): never {\n for (const line of describeFailure(action, error, connection.baseUrl, connection.keyVariable)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Entry\n ═══════════════════════════════════════════════════════════════ */\n\nexport async function apiKeysCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered before dispatch, never by a handler. `cli.ts` only\n // rewrites the subcommand to `\"--help\"` when none was named, so\n // `rebase api-keys list --help` used to *list the keys* and\n // `rebase api-keys revoke --help` sent `DELETE /api/admin/api-keys/--help`.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printApiKeysHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listKeys(rawArgs);\n break;\n case \"get\":\n await getKey(rawArgs);\n break;\n case \"create\":\n await createKey(rawArgs);\n break;\n case \"update\":\n await updateKey(rawArgs);\n break;\n case \"revoke\":\n await revokeKey(rawArgs);\n break;\n case \"scopes\":\n await listScopes(rawArgs);\n break;\n default:\n // The shape every other family uses. This one printed a bare line\n // to stderr *and* the whole help page to stdout, so a typo wrote\n // twenty lines to a stream a `--json` caller reads, with no `✗`, no\n // pointer at `--help`, and no did-you-mean — `craete` is one\n // transposition from `create`.\n unknownCommand(subcommand, API_KEYS_SUBCOMMANDS, \"api-keys\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Showing a key\n ═══════════════════════════════════════════════════════════════ */\n\nfunction keyStatus(key: ApiKeyMasked, now: Date): string {\n if (key.revoked_at) return chalk.red(\"revoked\");\n if (key.expires_at && new Date(key.expires_at) < now) return chalk.yellow(\"expired\");\n return chalk.green(\"active\");\n}\n\n/**\n * The lines that describe one key: what it is, what it may do and whom it\n * runs as.\n *\n * A service key runs as the RLS role `service` plus its own `roles`; a\n * personal key runs as its owner's roles as they are when it is used, so it\n * has none of its own to show.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeKey(key: ApiKeyMasked, now: Date = new Date()): string[] {\n const field = (label: string, value: string) => ` ${chalk.gray(`${label}:`.padEnd(12))}${value}`;\n const roles = key.kind === \"personal\"\n ? `its owner's (${key.owner_uid ?? \"unknown\"})`\n : [\"service\", ...key.roles].join(\", \");\n\n const lines = [\n ` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${keyStatus(key, now)}`,\n field(\"ID\", key.id),\n field(\"Kind\", key.kind),\n field(\"Scopes\", key.scopes.length > 0 ? key.scopes.join(\", \") : chalk.gray(\"none\")),\n field(\"Roles\", roles)\n ];\n if (key.rate_limit !== null) lines.push(field(\"Rate limit\", `${key.rate_limit} requests / 15 min`));\n if (key.expires_at) lines.push(field(\"Expires\", new Date(key.expires_at).toLocaleDateString()));\n lines.push(field(\"Created\", new Date(key.created_at).toLocaleDateString()));\n if (key.last_used_at) lines.push(field(\"Last used\", new Date(key.last_used_at).toLocaleDateString()));\n return lines;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys list` takes: none of its own. */\nexport const LIST_KEYS_FLAGS = { ...PROJECT_TARGET_FLAGS } as const;\n\nasync function listKeys(rawArgs: string[]): Promise<void> {\n parseCommandArgs({\n spec: LIST_KEYS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys list\",\n maxPositionals: 0\n });\n\n const connection = await connect(rawArgs);\n const { client } = connection;\n let keys: ApiKeyMasked[];\n try {\n ({ keys } = await client.apiKeys.listKeys());\n } catch (e: unknown) {\n fail(\"Failed to list API keys\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 API Keys\"));\n console.log(\"\");\n\n if (keys.length === 0) {\n console.log(chalk.gray(\" No API keys found.\"));\n console.log(\"\");\n return;\n }\n\n const now = new Date();\n for (const key of keys) {\n for (const line of describeKey(key, now)) console.log(line);\n console.log(\"\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n get\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys get` takes. */\nexport const GET_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--id\": String\n} as const;\n\n/**\n * Which key this invocation names, as a positional or as `--id`.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveGetKeyArgs(rawArgs: string[]): { id?: string } {\n const { flags, positionals } = parseCommandArgs({\n spec: GET_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys get\",\n maxPositionals: 1\n });\n\n return { id: flags[\"--id\"] || positionals[0] };\n}\n\nasync function getKey(rawArgs: string[]): Promise<void> {\n const { id } = resolveGetKeyArgs(rawArgs);\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys get <key-id> (`rebase api-keys list` shows them).\");\n }\n\n const connection = await connect(rawArgs);\n const { client } = connection;\n let key: ApiKeyMasked;\n try {\n ({ key } = await client.apiKeys.getKey(id));\n } catch (e: unknown) {\n fail(\"Failed to read API key\", e, connection);\n }\n\n console.log(\"\");\n for (const line of describeKey(key)) console.log(line);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n create\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys create` takes. */\nexport const CREATE_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--name\": String,\n \"--scopes\": [String],\n \"--full-access\": Boolean,\n \"--roles\": [String],\n \"--rate-limit\": Number,\n \"--expires-in\": String,\n \"--expires-at\": String,\n \"-n\": \"--name\"\n} satisfies arg.Spec;\n\n/**\n * Options `create` refuses by name, each with the flag that does that job.\n *\n * Checked before the line is parsed: the strict parser would answer them\n * \"unknown option\", which does not say what to type instead.\n */\nexport const RETIRED_CREATE_OPTIONS: Readonly<Record<string, string>> = {\n \"--permissions\":\n \"--permissions is gone: name what the key may do with --scopes, e.g. \" +\n \"--scopes data:read:posts,data:write:posts (`rebase api-keys scopes` lists them).\",\n \"--admin\":\n \"--admin is gone: give the key the RLS role with --roles admin, and the admin-plane scopes it needs \" +\n \"with --scopes, e.g. --scopes users:read,schema:read.\",\n \"--expires\":\n \"--expires is gone: use --expires-in <days> (e.g. --expires-in 90) or --expires-at <ISO date>.\"\n};\n\n/** Refuse a retired option, wherever on the line and however it is spelled. */\nfunction refuseRetiredOptions(rawArgs: string[]): void {\n for (const token of rawArgs.slice(2)) {\n // Past `--` everything is a value, never an option.\n if (token === \"--\") return;\n const name = token.split(\"=\", 1)[0];\n const replacement = Object.prototype.hasOwnProperty.call(RETIRED_CREATE_OPTIONS, name)\n ? RETIRED_CREATE_OPTIONS[name]\n : undefined;\n if (replacement) throw new UsageError(replacement);\n }\n}\n\n/**\n * A list flag's values, whether repeated (`--scopes a --scopes b`) or\n * comma-separated (`--scopes a,b`) — or both — trimmed and deduplicated.\n * Whitespace separates too: no scope or role name contains any.\n */\nfunction splitList(values: readonly string[] | undefined): string[] {\n const out = new Set<string>();\n for (const value of values ?? []) {\n for (const entry of value.split(/[\\s,]+/)) {\n if (entry) out.add(entry);\n }\n }\n return [...out];\n}\n\nconst DAY_MS = 86_400_000;\n\nfunction resolveExpiry(expiresIn: string | undefined, expiresAt: string | undefined, now: Date): string | null {\n if (expiresIn !== undefined && expiresAt !== undefined) {\n throw new UsageError(\"Pass --expires-in or --expires-at, not both.\");\n }\n if (expiresIn !== undefined) {\n const days = /^\\d+$/.test(expiresIn.trim()) ? Number(expiresIn.trim()) : NaN;\n if (!Number.isSafeInteger(days) || days < 1) {\n throw new UsageError(`--expires-in takes a whole number of days, e.g. --expires-in 90 (got \"${expiresIn}\").`);\n }\n return new Date(now.getTime() + days * DAY_MS).toISOString();\n }\n if (expiresAt !== undefined) {\n const parsed = new Date(expiresAt);\n if (isNaN(parsed.getTime())) {\n throw new UsageError(`--expires-at takes an ISO date, e.g. --expires-at 2027-01-31 (got \"${expiresAt}\").`);\n }\n if (parsed.getTime() <= now.getTime()) {\n throw new UsageError(`--expires-at must be in the future (got ${parsed.toISOString()}).`);\n }\n return parsed.toISOString();\n }\n return null;\n}\n\n/** What `rebase api-keys create` was asked to mint. */\nexport interface CreateKeyPlan {\n name: string;\n /** The scopes named with `--scopes`, or `\"held\"` for `--full-access`. */\n scopes: string[] | \"held\";\n /** RLS roles beside `service`. */\n roles: string[];\n rate_limit: number | null;\n expires_at: string | null;\n}\n\n/**\n * What this invocation asks to be created.\n *\n * The name may be given either way — `--name \"My Key\"` or as the single\n * positional — and under the old permissive parse an undeclared flag became\n * that positional: `rebase api-keys create --debug --full-access` created a\n * key called `--debug` with access to everything, and `--debug` is what the\n * CLI prints after every failure as the thing to re-run with. Strict parsing\n * makes the flag an error instead of a name.\n *\n * What the key may do has to be asked for by name — `--scopes` or\n * `--full-access` — never defaulted: a forgotten flag must not mint a key that\n * reaches everything.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveCreateKeyArgs(rawArgs: string[], now: Date = new Date()): CreateKeyPlan {\n refuseRetiredOptions(rawArgs);\n\n const { flags, positionals } = parseCommandArgs({\n spec: CREATE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys create\",\n maxPositionals: 1\n });\n\n const name = (flags[\"--name\"] || positionals[0] || \"\").trim();\n if (!name) {\n throw new UsageError('A key needs a name: rebase api-keys create \"CI\" --scopes data:read');\n }\n\n const named = splitList(flags[\"--scopes\"]);\n const fullAccess = flags[\"--full-access\"] === true;\n if (fullAccess && named.length > 0) {\n throw new UsageError(\"Pass --scopes or --full-access, not both: --full-access already means every scope you hold.\");\n }\n if (!fullAccess && named.length === 0) {\n throw new UsageError(\n \"Name what the key may do: --scopes data:read:posts,data:write:posts, or --full-access for every \" +\n \"scope you hold. `rebase api-keys scopes` lists them.\"\n );\n }\n\n const rateLimit = flags[\"--rate-limit\"];\n if (rateLimit !== undefined && (!Number.isSafeInteger(rateLimit) || rateLimit < 1)) {\n throw new UsageError(\"--rate-limit takes a whole number of requests per 15-minute window, e.g. --rate-limit 500.\");\n }\n\n return {\n name,\n scopes: fullAccess ? \"held\" : named,\n roles: splitList(flags[\"--roles\"]),\n rate_limit: rateLimit ?? null,\n expires_at: resolveExpiry(flags[\"--expires-in\"], flags[\"--expires-at\"], now)\n };\n}\n\n/**\n * The scopes `--full-access` puts on a key: every one the caller holds, less\n * key management, which no key may hold.\n *\n * Exported so its tests can check the subtraction without a server.\n */\nexport function grantableScopes(held: readonly string[]): string[] {\n const management: readonly string[] = KEY_MANAGEMENT_SCOPES;\n return held.filter(entry => !management.includes(parseScope(entry)?.scope ?? entry));\n}\n\nasync function createKey(rawArgs: string[]): Promise<void> {\n const plan = resolveCreateKeyArgs(rawArgs);\n const connection = await connect(rawArgs);\n const { client } = connection;\n\n let scopes: string[];\n if (plan.scopes === \"held\") {\n let held: string[];\n try {\n ({ held } = await client.personalKeys.listScopes());\n } catch (e: unknown) {\n fail(\"Failed to read the scopes you hold\", e, connection);\n }\n scopes = grantableScopes(held);\n if (scopes.length === 0) {\n console.error(chalk.red(\"✗ You hold no scope a key may carry, so --full-access has nothing to grant.\"));\n process.exit(1);\n }\n } else {\n scopes = plan.scopes;\n }\n\n const request: CreateApiKeyRequest = {\n name: plan.name,\n scopes,\n ...(plan.roles.length > 0 ? { roles: plan.roles } : {}),\n ...(plan.rate_limit !== null ? { rate_limit: plan.rate_limit } : {}),\n ...(plan.expires_at !== null ? { expires_at: plan.expires_at } : {})\n };\n\n let created: ApiKeyWithSecret;\n try {\n ({ key: created } = await client.apiKeys.createKey(request));\n } catch (e: unknown) {\n fail(\"Failed to create API key\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key created\"));\n console.log(\"\");\n for (const line of describeKey(created)) console.log(line);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy your key now — it won't be shown again:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(created.key)}`);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n update\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys update` takes. */\nexport const UPDATE_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--id\": String,\n \"--name\": String,\n \"--scopes\": [String],\n \"--roles\": [String],\n \"--rate-limit\": Number,\n \"--no-rate-limit\": Boolean,\n \"--expires-in\": String,\n \"--expires-at\": String,\n \"--no-expiry\": Boolean,\n \"-n\": \"--name\"\n} satisfies arg.Spec;\n\n/**\n * Which key, and what to change on it: only what the line names is sent, so\n * an update never resets a field it did not mention. Exported for its tests.\n */\nexport function resolveUpdateKeyArgs(rawArgs: string[], now: Date = new Date()): { id?: string; change: UpdateApiKeyRequest } {\n const { flags, positionals } = parseCommandArgs({\n spec: UPDATE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys update\",\n maxPositionals: 1\n });\n if (flags[\"--rate-limit\"] !== undefined && flags[\"--no-rate-limit\"]) {\n throw new UsageError(\"--rate-limit sets a limit and --no-rate-limit removes it; give one.\");\n }\n if ((flags[\"--expires-in\"] !== undefined || flags[\"--expires-at\"] !== undefined) && flags[\"--no-expiry\"]) {\n throw new UsageError(\"--expires-in/--expires-at set an expiry and --no-expiry removes it; give one.\");\n }\n const change: UpdateApiKeyRequest = {};\n if (flags[\"--name\"] !== undefined) change.name = flags[\"--name\"];\n if (flags[\"--scopes\"] !== undefined) change.scopes = splitList(flags[\"--scopes\"]);\n if (flags[\"--roles\"] !== undefined) change.roles = splitList(flags[\"--roles\"]);\n if (flags[\"--rate-limit\"] !== undefined) change.rate_limit = flags[\"--rate-limit\"];\n if (flags[\"--no-rate-limit\"]) change.rate_limit = null;\n const expiry = resolveExpiry(flags[\"--expires-in\"], flags[\"--expires-at\"], now);\n if (expiry !== null) change.expires_at = expiry;\n if (flags[\"--no-expiry\"]) change.expires_at = null;\n if (Object.keys(change).length === 0) {\n throw new UsageError(\"Nothing to change: pass --name, --scopes, --roles, --rate-limit, --no-rate-limit, --expires-in, --expires-at or --no-expiry.\");\n }\n return { id: flags[\"--id\"] || positionals[0], change };\n}\n\nasync function updateKey(rawArgs: string[]): Promise<void> {\n const { id, change } = resolveUpdateKeyArgs(rawArgs);\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys update <key-id> --scopes … (`rebase api-keys list` shows them).\");\n }\n const connection = await connect(rawArgs);\n let key: ApiKeyMasked;\n try {\n ({ key } = await connection.client.apiKeys.updateKey(id, change));\n } catch (e: unknown) {\n fail(\"Failed to update API key\", e, connection);\n }\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key updated\"));\n console.log(\"\");\n for (const line of describeKey(key)) console.log(line);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n revoke\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys revoke` takes. */\nexport const REVOKE_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--id\": String\n} as const;\n\n/**\n * Which key this invocation names.\n *\n * The id is a positional, so the permissive parse handed one straight to the\n * DELETE: `rebase api-keys revoke --foo` sent\n * `DELETE /api/admin/api-keys/--foo`, and `rebase --debug api-keys revoke <id>`\n * shifted the words along and revoked the key named `revoke`.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveRevokeKeyArgs(rawArgs: string[]): { id?: string; yes: boolean } {\n const { flags, positionals } = parseCommandArgs({\n spec: REVOKE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys revoke\",\n maxPositionals: 1\n });\n\n return { id: flags[\"--id\"] || positionals[0], yes: flags[\"--yes\"] === true };\n}\n\nasync function revokeKey(rawArgs: string[]): Promise<void> {\n const { id, yes } = resolveRevokeKeyArgs(rawArgs);\n\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys revoke <key-id> (`rebase api-keys list` shows them).\");\n }\n\n const connection = await connect(rawArgs);\n // Everything holding the key stops working at once, and a revoked key\n // cannot be restored — only replaced.\n await confirmDestructive({ yes, prompt: `Revoke API key ${id} on ${connection.baseUrl}? Anything using it stops working.` });\n const { client } = connection;\n try {\n await client.apiKeys.revokeKey(id);\n } catch (e: unknown) {\n fail(\"Failed to revoke API key\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key revoked\"));\n console.log(` ${chalk.gray(\"ID:\")} ${id}`);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n scopes\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys scopes` takes: none of its own. */\nexport const SCOPES_LIST_FLAGS = { ...PROJECT_TARGET_FLAGS } as const;\n\nconst PLANES: ReadonlyArray<{ plane: ScopeSummary[\"plane\"]; title: string; note: string }> = [\n { plane: \"data\", title: \"Data\", note: \"narrow what a key reaches; row-level security still decides the rows\" },\n { plane: \"admin\", title: \"Admin\", note: \"nobody holds these unless a role grants them; the admin role holds all\" },\n { plane: \"app\", title: \"App\", note: \"declared by this app under auth.scopes on the users table\" }\n];\n\n/**\n * The scope catalogue as printed lines: one section per plane, each scope with\n * its label and what its target names, marked when the caller holds it.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeScopes(scopes: readonly ScopeSummary[], held: readonly string[]): string[] {\n const management: readonly string[] = KEY_MANAGEMENT_SCOPES;\n const width = Math.max(0, ...scopes.map(s => s.scope.length)) + 2;\n const labelWidth = Math.max(0, ...scopes.map(s => s.label.length)) + 2;\n const lines: string[] = [];\n for (const { plane, title, note } of PLANES) {\n const inPlane = scopes.filter(s => s.plane === plane);\n if (inPlane.length === 0) continue;\n lines.push(` ${chalk.bold(title)} ${chalk.gray(`— ${note}`)}`);\n for (const s of inPlane) {\n const mark = held.includes(s.scope) ? chalk.green(\"✓\") : \" \";\n const extra = management.includes(s.scope)\n ? chalk.gray(\"never on a key\")\n : s.target ? chalk.gray(`:<${s.target}>`) : \"\";\n lines.push(` ${mark} ${s.scope.padEnd(width)}${extra ? s.label.padEnd(labelWidth) : s.label}${extra}`);\n }\n lines.push(\"\");\n }\n return lines;\n}\n\nasync function listScopes(rawArgs: string[]): Promise<void> {\n parseCommandArgs({\n spec: SCOPES_LIST_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys scopes\",\n maxPositionals: 0\n });\n\n const connection = await connect(rawArgs);\n const { client } = connection;\n let catalogue: { scopes: ScopeSummary[]; held: string[] };\n try {\n catalogue = await client.personalKeys.listScopes();\n } catch (e: unknown) {\n fail(\"Failed to read the scopes\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold(\" Scopes\") + chalk.gray(\" (✓ = you hold it; :<target> narrows it to one)\"));\n console.log(\"\");\n for (const line of describeScopes(catalogue.scopes, catalogue.held)) console.log(line);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nfunction printApiKeysHelp() {\n const keyable = ADMIN_SCOPES.filter(scope => !(KEY_MANAGEMENT_SCOPES as readonly string[]).includes(scope));\n console.log(`\n${chalk.bold(\"rebase api-keys\")} — Manage service API keys\n\n${chalk.green.bold(\"Usage\")}\n rebase api-keys ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List the service keys: kind, scopes, roles\n ${chalk.blue.bold(\"get\")} ${chalk.gray(\"<id>\")} Show one key\n ${chalk.blue.bold(\"create\")} Create a service key\n ${chalk.blue.bold(\"update\")} ${chalk.gray(\"<id>\")} Change a key's name, scopes, roles, limit or expiry\n ${chalk.blue.bold(\"revoke\")} ${chalk.gray(\"<id>\")} Revoke a key ${chalk.gray(\"(asks first; --yes skips)\")}\n ${chalk.blue.bold(\"scopes\")} List the scopes this backend knows, and which you hold\n\n${chalk.green.bold(\"create Options\")}\n ${chalk.blue(\"--name, -n\")} Key name ${chalk.gray(\"(required; or the first argument)\")}\n ${chalk.blue(\"--scopes\")} What the key may do, comma-separated or repeated\n ${chalk.gray(\"(required unless --full-access)\")}\n ${chalk.blue(\"--full-access\")} Every scope you hold, less keys:read and keys:write\n ${chalk.blue(\"--roles\")} RLS roles the key runs as beside ${chalk.gray(\"service\")}, e.g. admin\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window ${chalk.gray(\"(default: the server's API-key limit)\")}\n ${chalk.blue(\"--expires-in\")} Days until the key expires\n ${chalk.blue(\"--expires-at\")} Expiry as an ISO date, e.g. 2027-01-31\n\n${chalk.green.bold(\"update Options\")} ${chalk.gray(\"only what you name changes\")}\n ${chalk.blue(\"--name, -n\")} New name\n ${chalk.blue(\"--scopes\")} Replace the scopes ${chalk.gray(\"(never more than you hold)\")}\n ${chalk.blue(\"--roles\")} Replace the roles\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window; ${chalk.blue(\"--no-rate-limit\")} back to the server's\n ${chalk.blue(\"--expires-in\")} Days from now; ${chalk.blue(\"--expires-at\")} an ISO date; ${chalk.blue(\"--no-expiry\")} never\n\n${chalk.green.bold(\"get / update / revoke Options\")}\n ${chalk.blue(\"--id\")} API key ID ${chalk.gray(\"(or the first argument)\")}\n\n${chalk.green.bold(\"Target options\")} ${chalk.gray(\"(every command)\")}\n ${chalk.blue(\"--project <slug>\")} A Rebase Cloud project, through the console's Studio proxy\n ${chalk.blue(\"--cloud\")} The Rebase Cloud project this directory is linked to\n ${chalk.blue(\"--url <server>\")} A server at this address ${chalk.gray(\"(else REBASE_BASE_URL, then \\`rebase dev\\`)\")}\n ${chalk.blue(\"--token <bearer>\")} Send this bearer instead of the service key ${chalk.gray(\"(an rk_ key is always refused here)\")}\n ${chalk.blue(\"--session\")} Send the session \\`rebase auth login\\` stored ${chalk.gray(\"(an admin's)\")}\n ${chalk.blue(\"--anon\")} Send no credential\n ${chalk.blue(\"--json\")} Accepted; these commands print text\n ${chalk.blue(\"--yes\")} Skip the revoke prompt\n\n${chalk.green.bold(\"Scopes\")}\n A scope is ${chalk.blue(\"resource:action\")}, optionally narrowed to one target:\n ${chalk.blue(\"data:read:posts\")} reads the posts table and nothing else.\n Data ${DATA_PLANE_SCOPES.join(\", \")}\n ${chalk.gray(\"target: a table slug, a storage source id (default), a function name\")}\n Admin ${keyable.join(\", \")}\n App whatever the app declares under auth.scopes ${chalk.gray(\"(rebase api-keys scopes)\")}\n\n${chalk.green.bold(\"Examples\")}\n rebase api-keys list\n rebase api-keys create \"Analytics\" --scopes data:read:events\n rebase api-keys create -n \"Blog CI\" --scopes data:read:posts,data:write:posts --expires-in 90\n rebase api-keys create -n \"Mailer\" --scopes \"functions:invoke:send-email,storage:read:(default)\"\n rebase api-keys create -n \"Ops\" --full-access --roles admin --expires-at 2027-01-31\n rebase api-keys get abc123-def456\n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AAE;WAC7B,MAAM,KAAK,sEAAsE,EAAE;WACnF,QAAQ,KAAK,IAAI,EAAE;uDACyB,MAAM,KAAK,0BAA0B,EAAE;;EAE5F,MAAM,MAAM,KAAK,UAAU,EAAE;;;;;;;;;CAS9B;AACD"}
|
|
1
|
+
{"version":3,"file":"api-keys-CG2IpknI.js","names":[],"sources":["../src/commands/api-keys.ts"],"sourcesContent":["/**\n * CLI command: rebase api-keys <action>\n *\n * The project's service keys, through `/api/admin/api-keys`, authenticated with\n * the service key from `.env`.\n *\n * Subcommands:\n * list — List the service keys (masked): kind, scopes, roles\n * get — Show one key\n * create — Create a service key holding the scopes named on the line\n * revoke — Revoke a key\n * scopes — List the scopes this backend knows, and which the caller holds\n */\nimport chalk from \"chalk\";\nimport arg from \"arg\";\nimport { createRebaseClient, RebaseApiError } from \"@rebasepro/client\";\nimport {\n ADMIN_SCOPES,\n DATA_PLANE_SCOPES,\n KEY_MANAGEMENT_SCOPES,\n parseScope,\n type ApiKeyMasked,\n type ApiKeyWithSecret,\n type CreateApiKeyRequest,\n type UpdateApiKeyRequest,\n type ScopeSummary\n} from \"@rebasepro/types\";\nimport { findProjectRoot } from \"../utils/project\";\nimport { PROJECT_TARGET_FLAGS, cloudTargetNote, projectServiceKey, resolveBackendAddress } from \"../utils/project-target\";\nimport { projectTarget } from \"../utils/project-command\";\nimport { confirmDestructive } from \"./cloud/context\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { serverUnreachableHint } from \"../utils/dev-server\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const API_KEYS_SUBCOMMANDS = [\"list\", \"get\", \"create\", \"update\", \"revoke\", \"scopes\"] as const;\n\n/* ═══════════════════════════════════════════════════════════════\n Where the backend is — shared with every project command\n ═══════════════════════════════════════════════════════════════ */\n\n// The address rules (REBASE_BASE_URL, then a live `rebase dev`, nothing\n// guessed) moved to `utils/project-target.ts` with the other project\n// commands; re-exported here for the callers and tests that import them\n// from this module.\nexport { cloudTargetNote, resolveBackendAddress, type BackendAddress } from \"../utils/project-target\";\n\n/**\n * The address to send the service key to, or the end of the command.\n *\n * Exits before any request is made: the refusal is the point.\n */\nexport function requireBackendUrl(env: Record<string, string>, projectRoot: string): string {\n const address = resolveBackendAddress(env, projectRoot);\n const note = cloudTargetNote(address);\n if (note) console.error(chalk.yellow(` ⚠ ${note}`));\n if (address.url !== null) return address.url;\n\n console.error(chalk.red(\"✗ No server to send the request to.\"));\n console.error(chalk.gray(` ${address.reason}`));\n process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n The backend, through the SDK\n ═══════════════════════════════════════════════════════════════ */\n\ntype ProjectClient = ReturnType<typeof createRebaseClient>;\n\ninterface Connection {\n client: ProjectClient;\n baseUrl: string;\n /** The variable the service key was read from, for a hint that names it. */\n keyVariable: ServiceKeyVariable;\n}\n\n/** Where a service key is read from: the name a scaffold writes, or the older one. */\ntype ServiceKeyVariable = \"REBASE_SERVICE_KEY\" | \"SERVICE_KEY\";\n\n/**\n * An SDK client for this project's backend, holding the service key — or the\n * credential the target flags name, resolved as every project command\n * resolves it (`--project`, `--cloud`, `--url`, `--token`, `--session`).\n *\n * The service key is the project's own machine identity — the `admin` role,\n * every scope — so it is what may list, mint and revoke service keys. It is a\n * static bearer token: no session to restore or refresh, and no socket. An\n * `rk_` key is refused on these routes whatever it holds.\n *\n * The line was already parsed strictly by the action's own spec, which\n * declares the target flags; they are read again here only for their values.\n */\nasync function connect(rawArgs: string[]): Promise<Connection> {\n const targetFlags = arg(PROJECT_TARGET_FLAGS, { argv: rawArgs.slice(2), permissive: true });\n const target = await projectTarget(targetFlags, { command: \"api-keys\" });\n const token = await target.bearer();\n const client = createRebaseClient({\n baseUrl: target.baseUrl,\n ...(token ? { token } : {}),\n realtime: false,\n headers: { \"User-Agent\": cliUserAgent() },\n auth: { persistSession: false, autoRefresh: false }\n });\n const keyVariable = target.credential === \"service-key\" ? projectServiceKey(findProjectRoot())?.variable : undefined;\n return {\n client,\n baseUrl: target.label,\n keyVariable: keyVariable === \"SERVICE_KEY\" ? \"SERVICE_KEY\" : \"REBASE_SERVICE_KEY\"\n };\n}\n\n/**\n * What to print when a request fails: the server's error code and message,\n * which is what says why — `SCOPE_EXCEEDS_CREATOR`, `INVALID_SCOPES`,\n * `ROLE_EXCEEDS_CREATOR`, `KEY_MANAGEMENT_SCOPE` — and a hint where one helps.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeFailure(\n action: string,\n error: unknown,\n baseUrl: string,\n keyVariable: ServiceKeyVariable = \"REBASE_SERVICE_KEY\"\n): string[] {\n if (!(error instanceof RebaseApiError)) {\n return [`✗ ${action}: ${error instanceof Error ? error.message : String(error)}`];\n }\n if (error.status === 0 || error.code === \"NETWORK_ERROR\") {\n return [`✗ ${action}: ${error.message}`, ...serverUnreachableHint(baseUrl)];\n }\n\n const label = [error.code, error.status ? `(${error.status})` : undefined].filter(Boolean).join(\" \");\n const lines = [`✗ ${action}${label ? ` — ${label}` : \"\"}: ${error.message}`];\n\n if (error.status === 401) {\n lines.push(` The server at ${baseUrl} did not accept ${keyVariable} from .env — is it this project's server?`);\n }\n // The message names the target that is not there; what *is* there rides\n // in `details`, and is the thing to pick from.\n if (error.code === \"UNKNOWN_SCOPE_TARGET\" && isRecord(error.details)) {\n for (const [kind, title] of [[\"collections\", \"Tables\"], [\"buckets\", \"Buckets\"], [\"functions\", \"Functions\"]] as const) {\n const names = error.details[kind];\n if (Array.isArray(names) && names.length > 0) {\n lines.push(` ${title}: ${names.map(String).join(\", \")}`);\n }\n }\n }\n return lines;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction fail(action: string, error: unknown, connection: Connection): never {\n for (const line of describeFailure(action, error, connection.baseUrl, connection.keyVariable)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Entry\n ═══════════════════════════════════════════════════════════════ */\n\nexport async function apiKeysCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered before dispatch, never by a handler. `cli.ts` only\n // rewrites the subcommand to `\"--help\"` when none was named, so\n // `rebase api-keys list --help` used to *list the keys* and\n // `rebase api-keys revoke --help` sent `DELETE /api/admin/api-keys/--help`.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printApiKeysHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listKeys(rawArgs);\n break;\n case \"get\":\n await getKey(rawArgs);\n break;\n case \"create\":\n await createKey(rawArgs);\n break;\n case \"update\":\n await updateKey(rawArgs);\n break;\n case \"revoke\":\n await revokeKey(rawArgs);\n break;\n case \"scopes\":\n await listScopes(rawArgs);\n break;\n default:\n // The shape every other family uses. This one printed a bare line\n // to stderr *and* the whole help page to stdout, so a typo wrote\n // twenty lines to a stream a `--json` caller reads, with no `✗`, no\n // pointer at `--help`, and no did-you-mean — `craete` is one\n // transposition from `create`.\n unknownCommand(subcommand, API_KEYS_SUBCOMMANDS, \"api-keys\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Showing a key\n ═══════════════════════════════════════════════════════════════ */\n\nfunction keyStatus(key: ApiKeyMasked, now: Date): string {\n if (key.revoked_at) return chalk.red(\"revoked\");\n if (key.expires_at && new Date(key.expires_at) < now) return chalk.yellow(\"expired\");\n return chalk.green(\"active\");\n}\n\n/**\n * The lines that describe one key: what it is, what it may do and whom it\n * runs as.\n *\n * A service key runs as the RLS role `service` plus its own `roles`; a\n * personal key runs as its owner's roles as they are when it is used, so it\n * has none of its own to show.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeKey(key: ApiKeyMasked, now: Date = new Date()): string[] {\n const field = (label: string, value: string) => ` ${chalk.gray(`${label}:`.padEnd(12))}${value}`;\n const roles = key.kind === \"personal\"\n ? `its owner's (${key.owner_uid ?? \"unknown\"})`\n : [\"service\", ...key.roles].join(\", \");\n\n const lines = [\n ` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${keyStatus(key, now)}`,\n field(\"ID\", key.id),\n field(\"Kind\", key.kind),\n field(\"Scopes\", key.scopes.length > 0 ? key.scopes.join(\", \") : chalk.gray(\"none\")),\n field(\"Roles\", roles)\n ];\n if (key.rate_limit !== null) lines.push(field(\"Rate limit\", `${key.rate_limit} requests / 15 min`));\n if (key.expires_at) lines.push(field(\"Expires\", new Date(key.expires_at).toLocaleDateString()));\n lines.push(field(\"Created\", new Date(key.created_at).toLocaleDateString()));\n if (key.last_used_at) lines.push(field(\"Last used\", new Date(key.last_used_at).toLocaleDateString()));\n return lines;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys list` takes: none of its own. */\nexport const LIST_KEYS_FLAGS = { ...PROJECT_TARGET_FLAGS } as const;\n\nasync function listKeys(rawArgs: string[]): Promise<void> {\n parseCommandArgs({\n spec: LIST_KEYS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys list\",\n maxPositionals: 0\n });\n\n const connection = await connect(rawArgs);\n const { client } = connection;\n let keys: ApiKeyMasked[];\n try {\n ({ keys } = await client.apiKeys.listKeys());\n } catch (e: unknown) {\n fail(\"Failed to list API keys\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 API Keys\"));\n console.log(\"\");\n\n if (keys.length === 0) {\n console.log(chalk.gray(\" No API keys found.\"));\n console.log(\"\");\n return;\n }\n\n const now = new Date();\n for (const key of keys) {\n for (const line of describeKey(key, now)) console.log(line);\n console.log(\"\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n get\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys get` takes. */\nexport const GET_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--id\": String\n} as const;\n\n/**\n * Which key this invocation names, as a positional or as `--id`.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveGetKeyArgs(rawArgs: string[]): { id?: string } {\n const { flags, positionals } = parseCommandArgs({\n spec: GET_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys get\",\n maxPositionals: 1\n });\n\n return { id: flags[\"--id\"] || positionals[0] };\n}\n\nasync function getKey(rawArgs: string[]): Promise<void> {\n const { id } = resolveGetKeyArgs(rawArgs);\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys get <key-id> (`rebase api-keys list` shows them).\");\n }\n\n const connection = await connect(rawArgs);\n const { client } = connection;\n let key: ApiKeyMasked;\n try {\n ({ key } = await client.apiKeys.getKey(id));\n } catch (e: unknown) {\n fail(\"Failed to read API key\", e, connection);\n }\n\n console.log(\"\");\n for (const line of describeKey(key)) console.log(line);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n create\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys create` takes. */\nexport const CREATE_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--name\": String,\n \"--scopes\": [String],\n \"--full-access\": Boolean,\n \"--roles\": [String],\n \"--rate-limit\": Number,\n \"--expires-in\": String,\n \"--expires-at\": String,\n \"-n\": \"--name\"\n} satisfies arg.Spec;\n\n/**\n * Options `create` refuses by name, each with the flag that does that job.\n *\n * Checked before the line is parsed: the strict parser would answer them\n * \"unknown option\", which does not say what to type instead.\n */\nexport const RETIRED_CREATE_OPTIONS: Readonly<Record<string, string>> = {\n \"--permissions\":\n \"--permissions is gone: name what the key may do with --scopes, e.g. \" +\n \"--scopes data:read:posts,data:write:posts (`rebase api-keys scopes` lists them).\",\n \"--admin\":\n \"--admin is gone: give the key the RLS role with --roles admin, and the admin-plane scopes it needs \" +\n \"with --scopes, e.g. --scopes users:read,schema:read.\",\n \"--expires\":\n \"--expires is gone: use --expires-in <days> (e.g. --expires-in 90) or --expires-at <ISO date>.\"\n};\n\n/** Refuse a retired option, wherever on the line and however it is spelled. */\nfunction refuseRetiredOptions(rawArgs: string[]): void {\n for (const token of rawArgs.slice(2)) {\n // Past `--` everything is a value, never an option.\n if (token === \"--\") return;\n const name = token.split(\"=\", 1)[0];\n const replacement = Object.prototype.hasOwnProperty.call(RETIRED_CREATE_OPTIONS, name)\n ? RETIRED_CREATE_OPTIONS[name]\n : undefined;\n if (replacement) throw new UsageError(replacement);\n }\n}\n\n/**\n * A list flag's values, whether repeated (`--scopes a --scopes b`) or\n * comma-separated (`--scopes a,b`) — or both — trimmed and deduplicated.\n * Whitespace separates too: no scope or role name contains any.\n */\nfunction splitList(values: readonly string[] | undefined): string[] {\n const out = new Set<string>();\n for (const value of values ?? []) {\n for (const entry of value.split(/[\\s,]+/)) {\n if (entry) out.add(entry);\n }\n }\n return [...out];\n}\n\nconst DAY_MS = 86_400_000;\n\nfunction resolveExpiry(expiresIn: string | undefined, expiresAt: string | undefined, now: Date): string | null {\n if (expiresIn !== undefined && expiresAt !== undefined) {\n throw new UsageError(\"Pass --expires-in or --expires-at, not both.\");\n }\n if (expiresIn !== undefined) {\n const days = /^\\d+$/.test(expiresIn.trim()) ? Number(expiresIn.trim()) : NaN;\n if (!Number.isSafeInteger(days) || days < 1) {\n throw new UsageError(`--expires-in takes a whole number of days, e.g. --expires-in 90 (got \"${expiresIn}\").`);\n }\n return new Date(now.getTime() + days * DAY_MS).toISOString();\n }\n if (expiresAt !== undefined) {\n const parsed = new Date(expiresAt);\n if (isNaN(parsed.getTime())) {\n throw new UsageError(`--expires-at takes an ISO date, e.g. --expires-at 2027-01-31 (got \"${expiresAt}\").`);\n }\n if (parsed.getTime() <= now.getTime()) {\n throw new UsageError(`--expires-at must be in the future (got ${parsed.toISOString()}).`);\n }\n return parsed.toISOString();\n }\n return null;\n}\n\n/** What `rebase api-keys create` was asked to mint. */\nexport interface CreateKeyPlan {\n name: string;\n /** The scopes named with `--scopes`, or `\"held\"` for `--full-access`. */\n scopes: string[] | \"held\";\n /** RLS roles beside `service`. */\n roles: string[];\n rate_limit: number | null;\n expires_at: string | null;\n}\n\n/**\n * What this invocation asks to be created.\n *\n * The name may be given either way — `--name \"My Key\"` or as the single\n * positional — and under the old permissive parse an undeclared flag became\n * that positional: `rebase api-keys create --debug --full-access` created a\n * key called `--debug` with access to everything, and `--debug` is what the\n * CLI prints after every failure as the thing to re-run with. Strict parsing\n * makes the flag an error instead of a name.\n *\n * What the key may do has to be asked for by name — `--scopes` or\n * `--full-access` — never defaulted: a forgotten flag must not mint a key that\n * reaches everything.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveCreateKeyArgs(rawArgs: string[], now: Date = new Date()): CreateKeyPlan {\n refuseRetiredOptions(rawArgs);\n\n const { flags, positionals } = parseCommandArgs({\n spec: CREATE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys create\",\n maxPositionals: 1\n });\n\n const name = (flags[\"--name\"] || positionals[0] || \"\").trim();\n if (!name) {\n throw new UsageError('A key needs a name: rebase api-keys create \"CI\" --scopes data:read');\n }\n\n const named = splitList(flags[\"--scopes\"]);\n const fullAccess = flags[\"--full-access\"] === true;\n if (fullAccess && named.length > 0) {\n throw new UsageError(\"Pass --scopes or --full-access, not both: --full-access already means every scope you hold.\");\n }\n if (!fullAccess && named.length === 0) {\n throw new UsageError(\n \"Name what the key may do: --scopes data:read:posts,data:write:posts, or --full-access for every \" +\n \"scope you hold. `rebase api-keys scopes` lists them.\"\n );\n }\n\n const rateLimit = flags[\"--rate-limit\"];\n if (rateLimit !== undefined && (!Number.isSafeInteger(rateLimit) || rateLimit < 1)) {\n throw new UsageError(\"--rate-limit takes a whole number of requests per 15-minute window, e.g. --rate-limit 500.\");\n }\n\n return {\n name,\n scopes: fullAccess ? \"held\" : named,\n roles: splitList(flags[\"--roles\"]),\n rate_limit: rateLimit ?? null,\n expires_at: resolveExpiry(flags[\"--expires-in\"], flags[\"--expires-at\"], now)\n };\n}\n\n/**\n * The scopes `--full-access` puts on a key: every one the caller holds, less\n * key management, which no key may hold.\n *\n * Exported so its tests can check the subtraction without a server.\n */\nexport function grantableScopes(held: readonly string[]): string[] {\n const management: readonly string[] = KEY_MANAGEMENT_SCOPES;\n return held.filter(entry => !management.includes(parseScope(entry)?.scope ?? entry));\n}\n\nasync function createKey(rawArgs: string[]): Promise<void> {\n const plan = resolveCreateKeyArgs(rawArgs);\n const connection = await connect(rawArgs);\n const { client } = connection;\n\n let scopes: string[];\n if (plan.scopes === \"held\") {\n let held: string[];\n try {\n ({ held } = await client.personalKeys.listScopes());\n } catch (e: unknown) {\n fail(\"Failed to read the scopes you hold\", e, connection);\n }\n scopes = grantableScopes(held);\n if (scopes.length === 0) {\n console.error(chalk.red(\"✗ You hold no scope a key may carry, so --full-access has nothing to grant.\"));\n process.exit(1);\n }\n } else {\n scopes = plan.scopes;\n }\n\n const request: CreateApiKeyRequest = {\n name: plan.name,\n scopes,\n ...(plan.roles.length > 0 ? { roles: plan.roles } : {}),\n ...(plan.rate_limit !== null ? { rate_limit: plan.rate_limit } : {}),\n ...(plan.expires_at !== null ? { expires_at: plan.expires_at } : {})\n };\n\n let created: ApiKeyWithSecret;\n try {\n ({ key: created } = await client.apiKeys.createKey(request));\n } catch (e: unknown) {\n fail(\"Failed to create API key\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key created\"));\n console.log(\"\");\n for (const line of describeKey(created)) console.log(line);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy your key now — it won't be shown again:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(created.key)}`);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n update\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys update` takes. */\nexport const UPDATE_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--id\": String,\n \"--name\": String,\n \"--scopes\": [String],\n \"--roles\": [String],\n \"--rate-limit\": Number,\n \"--no-rate-limit\": Boolean,\n \"--expires-in\": String,\n \"--expires-at\": String,\n \"--no-expiry\": Boolean,\n \"-n\": \"--name\"\n} satisfies arg.Spec;\n\n/**\n * Which key, and what to change on it: only what the line names is sent, so\n * an update never resets a field it did not mention. Exported for its tests.\n */\nexport function resolveUpdateKeyArgs(rawArgs: string[], now: Date = new Date()): { id?: string; change: UpdateApiKeyRequest } {\n const { flags, positionals } = parseCommandArgs({\n spec: UPDATE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys update\",\n maxPositionals: 1\n });\n if (flags[\"--rate-limit\"] !== undefined && flags[\"--no-rate-limit\"]) {\n throw new UsageError(\"--rate-limit sets a limit and --no-rate-limit removes it; give one.\");\n }\n if ((flags[\"--expires-in\"] !== undefined || flags[\"--expires-at\"] !== undefined) && flags[\"--no-expiry\"]) {\n throw new UsageError(\"--expires-in/--expires-at set an expiry and --no-expiry removes it; give one.\");\n }\n const change: UpdateApiKeyRequest = {};\n if (flags[\"--name\"] !== undefined) change.name = flags[\"--name\"];\n if (flags[\"--scopes\"] !== undefined) change.scopes = splitList(flags[\"--scopes\"]);\n if (flags[\"--roles\"] !== undefined) change.roles = splitList(flags[\"--roles\"]);\n if (flags[\"--rate-limit\"] !== undefined) change.rate_limit = flags[\"--rate-limit\"];\n if (flags[\"--no-rate-limit\"]) change.rate_limit = null;\n const expiry = resolveExpiry(flags[\"--expires-in\"], flags[\"--expires-at\"], now);\n if (expiry !== null) change.expires_at = expiry;\n if (flags[\"--no-expiry\"]) change.expires_at = null;\n if (Object.keys(change).length === 0) {\n throw new UsageError(\"Nothing to change: pass --name, --scopes, --roles, --rate-limit, --no-rate-limit, --expires-in, --expires-at or --no-expiry.\");\n }\n return { id: flags[\"--id\"] || positionals[0], change };\n}\n\nasync function updateKey(rawArgs: string[]): Promise<void> {\n const { id, change } = resolveUpdateKeyArgs(rawArgs);\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys update <key-id> --scopes … (`rebase api-keys list` shows them).\");\n }\n const connection = await connect(rawArgs);\n let key: ApiKeyMasked;\n try {\n ({ key } = await connection.client.apiKeys.updateKey(id, change));\n } catch (e: unknown) {\n fail(\"Failed to update API key\", e, connection);\n }\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key updated\"));\n console.log(\"\");\n for (const line of describeKey(key)) console.log(line);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n revoke\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys revoke` takes. */\nexport const REVOKE_KEY_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--id\": String\n} as const;\n\n/**\n * Which key this invocation names.\n *\n * The id is a positional, so the permissive parse handed one straight to the\n * DELETE: `rebase api-keys revoke --foo` sent\n * `DELETE /api/admin/api-keys/--foo`, and `rebase --debug api-keys revoke <id>`\n * shifted the words along and revoked the key named `revoke`.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveRevokeKeyArgs(rawArgs: string[]): { id?: string; yes: boolean } {\n const { flags, positionals } = parseCommandArgs({\n spec: REVOKE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys revoke\",\n maxPositionals: 1\n });\n\n return { id: flags[\"--id\"] || positionals[0], yes: flags[\"--yes\"] === true };\n}\n\nasync function revokeKey(rawArgs: string[]): Promise<void> {\n const { id, yes } = resolveRevokeKeyArgs(rawArgs);\n\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys revoke <key-id> (`rebase api-keys list` shows them).\");\n }\n\n const connection = await connect(rawArgs);\n // Everything holding the key stops working at once, and a revoked key\n // cannot be restored — only replaced.\n await confirmDestructive({ yes, prompt: `Revoke API key ${id} on ${connection.baseUrl}? Anything using it stops working.` });\n const { client } = connection;\n try {\n await client.apiKeys.revokeKey(id);\n } catch (e: unknown) {\n fail(\"Failed to revoke API key\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key revoked\"));\n console.log(` ${chalk.gray(\"ID:\")} ${id}`);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n scopes\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys scopes` takes: none of its own. */\nexport const SCOPES_LIST_FLAGS = { ...PROJECT_TARGET_FLAGS } as const;\n\nconst PLANES: ReadonlyArray<{ plane: ScopeSummary[\"plane\"]; title: string; note: string }> = [\n { plane: \"data\", title: \"Data\", note: \"narrow what a key reaches; row-level security still decides the rows\" },\n { plane: \"admin\", title: \"Admin\", note: \"nobody holds these unless a role grants them; the admin role holds all\" },\n { plane: \"app\", title: \"App\", note: \"declared by this app under auth.scopes on the users table\" }\n];\n\n/**\n * The scope catalogue as printed lines: one section per plane, each scope with\n * its label and what its target names, marked when the caller holds it.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeScopes(scopes: readonly ScopeSummary[], held: readonly string[]): string[] {\n const management: readonly string[] = KEY_MANAGEMENT_SCOPES;\n const width = Math.max(0, ...scopes.map(s => s.scope.length)) + 2;\n const labelWidth = Math.max(0, ...scopes.map(s => s.label.length)) + 2;\n const lines: string[] = [];\n for (const { plane, title, note } of PLANES) {\n const inPlane = scopes.filter(s => s.plane === plane);\n if (inPlane.length === 0) continue;\n lines.push(` ${chalk.bold(title)} ${chalk.gray(`— ${note}`)}`);\n for (const s of inPlane) {\n const mark = held.includes(s.scope) ? chalk.green(\"✓\") : \" \";\n const extra = management.includes(s.scope)\n ? chalk.gray(\"never on a key\")\n : s.target ? chalk.gray(`:<${s.target}>`) : \"\";\n lines.push(` ${mark} ${s.scope.padEnd(width)}${extra ? s.label.padEnd(labelWidth) : s.label}${extra}`);\n }\n lines.push(\"\");\n }\n return lines;\n}\n\nasync function listScopes(rawArgs: string[]): Promise<void> {\n parseCommandArgs({\n spec: SCOPES_LIST_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys scopes\",\n maxPositionals: 0\n });\n\n const connection = await connect(rawArgs);\n const { client } = connection;\n let catalogue: { scopes: ScopeSummary[]; held: string[] };\n try {\n catalogue = await client.personalKeys.listScopes();\n } catch (e: unknown) {\n fail(\"Failed to read the scopes\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold(\" Scopes\") + chalk.gray(\" (✓ = you hold it; :<target> narrows it to one)\"));\n console.log(\"\");\n for (const line of describeScopes(catalogue.scopes, catalogue.held)) console.log(line);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nfunction printApiKeysHelp() {\n const keyable = ADMIN_SCOPES.filter(scope => !(KEY_MANAGEMENT_SCOPES as readonly string[]).includes(scope));\n console.log(`\n${chalk.bold(\"rebase api-keys\")} — Manage service API keys\n\n${chalk.green.bold(\"Usage\")}\n rebase api-keys ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List the service keys: kind, scopes, roles\n ${chalk.blue.bold(\"get\")} ${chalk.gray(\"<id>\")} Show one key\n ${chalk.blue.bold(\"create\")} Create a service key\n ${chalk.blue.bold(\"update\")} ${chalk.gray(\"<id>\")} Change a key's name, scopes, roles, limit or expiry\n ${chalk.blue.bold(\"revoke\")} ${chalk.gray(\"<id>\")} Revoke a key ${chalk.gray(\"(asks first; --yes skips)\")}\n ${chalk.blue.bold(\"scopes\")} List the scopes this backend knows, and which you hold\n\n${chalk.green.bold(\"create Options\")}\n ${chalk.blue(\"--name, -n\")} Key name ${chalk.gray(\"(required; or the first argument)\")}\n ${chalk.blue(\"--scopes\")} What the key may do, comma-separated or repeated\n ${chalk.gray(\"(required unless --full-access)\")}\n ${chalk.blue(\"--full-access\")} Every scope you hold, less keys:read and keys:write\n ${chalk.blue(\"--roles\")} RLS roles the key runs as beside ${chalk.gray(\"service\")}, e.g. admin\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window ${chalk.gray(\"(default: the server's API-key limit)\")}\n ${chalk.blue(\"--expires-in\")} Days until the key expires\n ${chalk.blue(\"--expires-at\")} Expiry as an ISO date, e.g. 2027-01-31\n\n${chalk.green.bold(\"update Options\")} ${chalk.gray(\"only what you name changes\")}\n ${chalk.blue(\"--name, -n\")} New name\n ${chalk.blue(\"--scopes\")} Replace the scopes ${chalk.gray(\"(never more than you hold)\")}\n ${chalk.blue(\"--roles\")} Replace the roles\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window; ${chalk.blue(\"--no-rate-limit\")} back to the server's\n ${chalk.blue(\"--expires-in\")} Days from now; ${chalk.blue(\"--expires-at\")} an ISO date; ${chalk.blue(\"--no-expiry\")} never\n\n${chalk.green.bold(\"get / update / revoke Options\")}\n ${chalk.blue(\"--id\")} API key ID ${chalk.gray(\"(or the first argument)\")}\n\n${chalk.green.bold(\"Target options\")} ${chalk.gray(\"(every command)\")}\n ${chalk.blue(\"--project <slug>\")} A Rebase Cloud project, through the console's Studio proxy\n ${chalk.blue(\"--cloud\")} The Rebase Cloud project this directory is linked to\n ${chalk.blue(\"--url <server>\")} A server at this address ${chalk.gray(\"(else REBASE_BASE_URL, then \\`rebase dev\\`)\")}\n ${chalk.blue(\"--token <bearer>\")} Send this bearer instead of the service key ${chalk.gray(\"(an rk_ key is always refused here)\")}\n ${chalk.blue(\"--session\")} Send the session \\`rebase auth login\\` stored ${chalk.gray(\"(an admin's)\")}\n ${chalk.blue(\"--anon\")} Send no credential\n ${chalk.blue(\"--json\")} Accepted; these commands print text\n ${chalk.blue(\"--yes\")} Skip the revoke prompt\n\n${chalk.green.bold(\"Scopes\")}\n A scope is ${chalk.blue(\"resource:action\")}, optionally narrowed to one target:\n ${chalk.blue(\"data:read:posts\")} reads the posts table and nothing else.\n Data ${DATA_PLANE_SCOPES.join(\", \")}\n ${chalk.gray(\"target: a table slug, a storage source id (default), a function name\")}\n Admin ${keyable.join(\", \")}\n App whatever the app declares under auth.scopes ${chalk.gray(\"(rebase api-keys scopes)\")}\n\n${chalk.green.bold(\"Examples\")}\n rebase api-keys list\n rebase api-keys create \"Analytics\" --scopes data:read:events\n rebase api-keys create -n \"Blog CI\" --scopes data:read:posts,data:write:posts --expires-in 90\n rebase api-keys create -n \"Mailer\" --scopes \"functions:invoke:send-email,storage:read:(default)\"\n rebase api-keys create -n \"Ops\" --full-access --roles admin --expires-at 2027-01-31\n rebase api-keys get abc123-def456\n rebase api-keys update abc123-def456 --scopes data:read:posts --expires-in 30\n rebase api-keys revoke abc123-def456 --yes\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,uBAAuB;CAAC;CAAQ;CAAO;CAAU;CAAU;CAAU;AAAQ;;;;;;;;;;;;;;AAyD1F,eAAe,QAAQ,SAAwC;CAE3D,MAAM,SAAS,MAAM,cADD,IAAI,sBAAsB;EAAE,MAAM,QAAQ,MAAM,CAAC;EAAG,YAAY;CAAK,CACtD,GAAa,EAAE,SAAS,WAAW,CAAC;CACvE,MAAM,QAAQ,MAAM,OAAO,OAAO;CAClC,MAAM,SAAS,mBAAmB;EAC9B,SAAS,OAAO;EAChB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,UAAU;EACV,SAAS,EAAE,cAAc,aAAa,EAAE;EACxC,MAAM;GAAE,gBAAgB;GAAO,aAAa;EAAM;CACtD,CAAC;CACD,MAAM,cAAc,OAAO,eAAe,gBAAgB,kBAAkB,gBAAgB,CAAC,CAAC,EAAE,WAAW,KAAA;CAC3G,OAAO;EACH;EACA,SAAS,OAAO;EAChB,aAAa,gBAAgB,gBAAgB,gBAAgB;CACjE;AACJ;;;;;;;;AASA,SAAgB,gBACZ,QACA,OACA,SACA,cAAkC,sBAC1B;CACR,IAAI,EAAE,iBAAiB,iBACnB,OAAO,CAAC,KAAK,OAAO,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAEpF,IAAI,MAAM,WAAW,KAAK,MAAM,SAAS,iBACr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K,cAAc,EAAE;IAC5G,MAAM,KAAK,QAAQ,EAAE;IACrB,MAAM,KAAK,QAAQ,EAAE;IACrB,MAAM,KAAK,OAAO,EAAE;;EAEtB,MAAM,MAAM,KAAK,QAAQ,EAAE;eACd,MAAM,KAAK,iBAAiB,EAAE;IACzC,MAAM,KAAK,iBAAiB,EAAE;WACvB,kBAAkB,KAAK,IAAI,EAAE;WAC7B,MAAM,KAAK,sEAAsE,EAAE;WACnF,QAAQ,KAAK,IAAI,EAAE;uDACyB,MAAM,KAAK,0BAA0B,EAAE;;EAE5F,MAAM,MAAM,KAAK,UAAU,EAAE;;;;;;;;;CAS9B;AACD"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
|
|
2
2
|
import { a as wantsHelp, n as parseCommandArgs } from "./args-DHyrshtI.js";
|
|
3
|
-
import { i as failAsJson, p as requireProjectRoot } from "./project-
|
|
4
|
-
import { E as synthesizeManifest, O as writeManifest, T as staticAppAddress, _ as findBackendApp, b as loadManifest, l as ManifestError, p as assessManagedCompatibility, x as manifestExists, y as formatAppAddress } from "./manifest-
|
|
5
|
-
import { i as runningBackendUrl, n as devServerUrl } from "./dev-server-
|
|
6
|
-
import { H as readLink } from "./context-
|
|
7
|
-
import { r as foldableApps } from "./fold-static-
|
|
3
|
+
import { i as failAsJson, p as requireProjectRoot } from "./project-CQ5nKddJ.js";
|
|
4
|
+
import { E as synthesizeManifest, O as writeManifest, T as staticAppAddress, _ as findBackendApp, b as loadManifest, l as ManifestError, p as assessManagedCompatibility, x as manifestExists, y as formatAppAddress } from "./manifest-D6B4LA8x.js";
|
|
5
|
+
import { i as runningBackendUrl, n as devServerUrl } from "./dev-server-dsabI0UT.js";
|
|
6
|
+
import { H as readLink } from "./context-C9lz1vTS.js";
|
|
7
|
+
import { r as foldableApps } from "./fold-static-DzV3EJZm.js";
|
|
8
8
|
import chalk from "chalk";
|
|
9
9
|
import path from "path";
|
|
10
10
|
//#region src/commands/apps.ts
|
|
@@ -328,4 +328,4 @@ function loadManifestOrExit(projectRoot, asJson = false) {
|
|
|
328
328
|
//#endregion
|
|
329
329
|
export { APPS_SUBCOMMANDS, appsCommand };
|
|
330
330
|
|
|
331
|
-
//# sourceMappingURL=apps-
|
|
331
|
+
//# sourceMappingURL=apps-DaaWvv3o.js.map
|