@rebasepro/cli 0.33.2 → 0.34.1
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-Cg_zBWoW.js → agent-setup-kjdKozkF.js} +3 -3
- package/dist/{agent-setup-Cg_zBWoW.js.map → agent-setup-kjdKozkF.js.map} +1 -1
- package/dist/{api-TbmW33D7.js → api-CQh_qTyQ.js} +2 -2
- package/dist/{api-TbmW33D7.js.map → api-CQh_qTyQ.js.map} +1 -1
- package/dist/{api-keys-fPQ55DCm.js → api-keys-CG2IpknI.js} +5 -5
- package/dist/{api-keys-fPQ55DCm.js.map → api-keys-CG2IpknI.js.map} +1 -1
- package/dist/{apps-DBTRoOeP.js → apps-DaaWvv3o.js} +6 -6
- package/dist/{apps-DBTRoOeP.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-BpyYLEFY.js → auth-bi8x2YX1.js} +12 -12
- package/dist/{auth-BpyYLEFY.js.map → auth-bi8x2YX1.js.map} +1 -1
- package/dist/{auth-session-B6aT0Dyj.js → auth-session-BVoxE5tp.js} +4 -4
- package/dist/{auth-session-B6aT0Dyj.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-E5hfEWKj.js → build-D-0VCmbU.js} +11 -11
- package/dist/build-D-0VCmbU.js.map +1 -0
- package/dist/{bundle-CIiKGrte.js → bundle-BDTVS9XE.js} +7 -7
- package/dist/{bundle-CIiKGrte.js.map → bundle-BDTVS9XE.js.map} +1 -1
- package/dist/{cloud-DNJyUU0T.js → cloud-CR6Hps3B.js} +222 -31
- package/dist/cloud-CR6Hps3B.js.map +1 -0
- 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-Bks5xkrQ.js → command-nWgittn1.js} +3 -3
- package/dist/{command-Bks5xkrQ.js.map → command-nWgittn1.js.map} +1 -1
- package/dist/commands/build.d.ts +2 -1
- package/dist/commands/cloud/db-connect.d.ts +31 -1
- package/dist/commands/cloud/db-query.d.ts +16 -0
- package/dist/commands/cloud/index.d.ts +1 -0
- package/dist/commands/cloud/resources.d.ts +19 -1
- package/dist/commands/dev.d.ts +15 -0
- package/dist/commands/users.d.ts +1 -0
- 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-BOMEoKxn.js → context-C9lz1vTS.js} +6 -2
- package/dist/{context-BOMEoKxn.js.map → context-C9lz1vTS.js.map} +1 -1
- package/dist/{cron-ZRXsla0v.js → cron-BzzNxkBH.js} +3 -3
- package/dist/{cron-ZRXsla0v.js.map → cron-BzzNxkBH.js.map} +1 -1
- package/dist/{cron-CpUsQ739.js → cron-DuZ3Svjq.js} +4 -4
- package/dist/{cron-CpUsQ739.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-BJ9AZFUC.js → data-1eipHbxJ.js} +3 -3
- package/dist/{data-BJ9AZFUC.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-nNbbxAeo.js → debug-CkiOcfsU.js} +2 -2
- package/dist/{debug-nNbbxAeo.js.map → debug-CkiOcfsU.js.map} +1 -1
- package/dist/{derive-Mky_u59_.js → derive-BU5kvcOP.js} +3 -3
- package/dist/{derive-Mky_u59_.js.map → derive-BU5kvcOP.js.map} +1 -1
- package/dist/{dev-bj6dEeSQ.js → dev-Ce9PVQS8.js} +34 -13
- package/dist/dev-Ce9PVQS8.js.map +1 -0
- 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-FaBObSlb.js → doctor-Cdu3Llrw.js} +8 -8
- package/dist/{doctor-FaBObSlb.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-2t3UUX4z.js → fold-static-DzV3EJZm.js} +4 -4
- package/dist/{fold-static-2t3UUX4z.js.map → fold-static-DzV3EJZm.js.map} +1 -1
- package/dist/{function-portability-BIvlvR9q.js → function-portability-Dppl6uqg.js} +24 -5
- package/dist/{function-portability-BIvlvR9q.js.map → function-portability-Dppl6uqg.js.map} +1 -1
- package/dist/function-portability.d.ts +9 -0
- package/dist/{functions-B4JR6EZL.js → functions-BCEJnISw.js} +4 -4
- package/dist/{functions-B4JR6EZL.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-ByD-gTsK.js → generate_sdk-MAbUUZoK.js} +6 -6
- package/dist/{generate_sdk-ByD-gTsK.js.map → generate_sdk-MAbUUZoK.js.map} +1 -1
- package/dist/index.es.js +54 -54
- package/dist/{init-DHCe5mJ5.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-DpuMukJe.js → logs-B_mS4gCn.js} +4 -4
- package/dist/{logs-DpuMukJe.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-CSY9ZDKy.js → migrate-DdcgLMyL.js} +3 -3
- package/dist/{migrate-CSY9ZDKy.js.map → migrate-DdcgLMyL.js.map} +1 -1
- package/dist/{normalize-imports-P86NVfpo.js → normalize-imports-CVjOssZ2.js} +2 -2
- package/dist/{normalize-imports-P86NVfpo.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-Cl9EZzjr.js → project-command-5wM_bJQt.js} +7 -7
- package/dist/{project-command-Cl9EZzjr.js.map → project-command-5wM_bJQt.js.map} +1 -1
- package/dist/resolve-GDRel2ne.js +2 -0
- package/dist/{resources-Db3USuPO.js → resources-ecA0MEjy.js} +4 -4
- package/dist/{resources-Db3USuPO.js.map → resources-ecA0MEjy.js.map} +1 -1
- package/dist/{rls-BxrQ0P50.js → rls-B4zGbTKY.js} +3 -3
- package/dist/{rls-BxrQ0P50.js.map → rls-B4zGbTKY.js.map} +1 -1
- package/dist/{schema-_FzZEoB8.js → schema-CWzzn0cY.js} +13 -12
- package/dist/{schema-_FzZEoB8.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-h72UJ9zH.js → schema-show-DwYtOp4S.js} +5 -5
- package/dist/{schema-show-h72UJ9zH.js.map → schema-show-DwYtOp4S.js.map} +1 -1
- package/dist/{skills-DQ2bZGkj.js → skills-CWmBTCRW.js} +6 -6
- package/dist/{skills-DQ2bZGkj.js.map → skills-CWmBTCRW.js.map} +1 -1
- package/dist/{start-Cjx4W0bJ.js → start-4uhCu_md.js} +6 -6
- package/dist/{start-Cjx4W0bJ.js.map → start-4uhCu_md.js.map} +1 -1
- package/dist/{status-CDBk25VO.js → status-CVEzoSwX.js} +7 -7
- package/dist/{status-CDBk25VO.js.map → status-CVEzoSwX.js.map} +1 -1
- package/dist/{storage-Clc8dLG8.js → storage-Dqf5tyhs.js} +9 -9
- package/dist/{storage-Clc8dLG8.js.map → storage-Dqf5tyhs.js.map} +1 -1
- package/dist/{storage-objects-CfRKlTDe.js → storage-objects-DbFsemMV.js} +3 -3
- package/dist/{storage-objects-CfRKlTDe.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-5PkqBY6R.js → users-Cx5HuaTn.js} +9 -6
- package/dist/users-Cx5HuaTn.js.map +1 -0
- 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/.cursorrules +2 -1
- package/templates/template/.github/copilot-instructions.md +2 -1
- package/templates/template/.windsurfrules +2 -1
- package/templates/template/AGENTS.md +2 -1
- package/templates/template/CLAUDE.md +2 -1
- package/templates/template/ai-instructions.md +5 -2
- package/templates/template/frontend/src/index.css +13 -0
- package/dist/build-E5hfEWKj.js.map +0 -1
- package/dist/cloud-DNJyUU0T.js.map +0 -1
- package/dist/dev-bj6dEeSQ.js.map +0 -1
- package/dist/init-DHCe5mJ5.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-DV14XY4o.js +0 -2
- package/dist/users-5PkqBY6R.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"status-CDBk25VO.js","names":[],"sources":["../src/resources/status.ts","../src/commands/status.ts"],"sourcesContent":["/**\n * What a project declared, what the environment binds it to, and whether the\n * two meet.\n *\n * ## Why this exists\n *\n * Every piece of this was already knowable and none of it was visible in one\n * place. `rebase resources` lists what you declared. The environment holds the\n * variables. The resolvers decide whether a source is usable. So the question a\n * developer actually has — *\"why does uploading to `media` answer 501\"* — could\n * only be answered by knowing the suffix rule, deriving the variable name by\n * hand, and checking it against a `.env` they had to find first.\n *\n * The answer is mechanical, so it should be printed rather than taught.\n *\n * ## Why it calls the resolvers instead of re-deciding\n *\n * The verdict comes from `resolveDataSources` and `resolveStorageBackend` — the\n * same functions that run at boot. A status view that decided for itself what\n * \"configured\" means would be a second implementation of the rule, and the\n * first time it disagreed it would be reassuring a developer about a deployment\n * that is about to refuse to start.\n *\n * The variable *names* come from each kind's `envBases`, and the verdicts from\n * the resolver `@rebasepro/server` registers per kind — one object per kind,\n * held to `envBases` by `resource-env-bases.test.ts`. A kind this view has\n * never heard of is judged by whatever resolver its package registered.\n */\nimport { withImplicitDefaults } from \"./derive\";\nimport {\n DEFAULT_RESOURCE_KEY,\n envBasesForResource,\n resourceEnvSuffix,\n resourceToDataSource,\n type DataSourceDefinition,\n type ResourceDeclaration,\n type ResourceGraph\n} from \"@rebasepro/types\";\n\n/** One environment variable a resource reads, and whether it is there. */\nexport interface ResourceBinding {\n /** The variable this resource reads, suffix included. */\n name: string;\n set: boolean;\n /**\n * The account-scoped name consulted when `name` is unset.\n *\n * Only provider-level bindings have one, and only when the resource named\n * an `account`. Shown because a developer looking at an unset\n * `S3_ACCESS_KEY_ID__MEDIA` needs to know it is not the whole story.\n */\n fallback?: { name: string; set: boolean };\n}\n\n/** Whether a declared resource can actually be reached. */\nexport type ResourceState =\n /** Bound and usable. */\n | \"ready\"\n /** Nothing set for it. Legal for a bucket, fatal for a database. */\n | \"unconfigured\"\n /** Set, and set wrongly. The deployment refuses to start. */\n | \"broken\";\n\nexport interface ResourceStatus {\n kind: string;\n key: string;\n engine: string;\n transport: string;\n /** Present when this resource shares another's credentials. */\n account?: string;\n /** True for a resource nobody declared, which exists anyway. */\n implicit: boolean;\n bindings: ResourceBinding[];\n state: ResourceState;\n /** What this means, in the terms the developer will meet it in. */\n detail: string;\n /** Set when a local directory stands in for this engine, in development. */\n standsIn?: string;\n /** What in the project reaches this resource, from the graph. */\n usedBy?: readonly string[];\n}\n\nexport type EnvBag = Record<string, string | undefined>;\n\n/** Set, and not set to the empty string — which the resolvers treat as absent. */\nfunction isSet(env: EnvBag, name: string): boolean {\n const value = env[name];\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * The bindings one declaration reads, in the order a reader should scan them.\n *\n * A `direct`-transport resource gets none: the browser reaches it with a\n * provider SDK and the backend binds nothing for it, so listing variables would\n * invite someone to set variables that are never read.\n */\nexport function bindingsFor(\n declaration: ResourceDeclaration,\n env: EnvBag,\n accountScopedBases: readonly string[]\n): ResourceBinding[] {\n if (declaration.transport !== \"server\") return [];\n\n const suffix = resourceEnvSuffix(declaration.key);\n const account = typeof declaration.options.account === \"string\"\n ? resourceEnvSuffix(declaration.options.account)\n : undefined;\n\n return envBasesForResource(declaration).map((base) => {\n const name = `${base}${suffix}`;\n const binding: ResourceBinding = { name, set: isSet(env, name) };\n\n // Only the provider-level bindings fall back, and only for a resource\n // that named an account. The bucket name never does — it is what\n // distinguishes one source from another.\n if (account !== undefined && !binding.set && accountScopedBases.includes(base)) {\n binding.fallback = { name: `${base}${account}`, set: isSet(env, `${base}${account}`) };\n }\n return binding;\n });\n}\n\n/**\n * What the managed development database covers, when a project is on it.\n *\n * `rebase init` leaves `DATABASE_URL` commented out on purpose and the managed\n * PGlite fills the vacuum — the documented first-run state. Judging that state\n * by the environment alone produced `○ (default) postgres · DATABASE_URL not\n * set` and the remedy \"set DATABASE_URL\", at the same moment `rebase db url`\n * was printing a working connection string for the same project and\n * `rebase dev` was serving from it. The status view was reading the one place\n * the answer deliberately is not.\n *\n * Resolved by the caller, because deciding it needs the project's `.env`, its\n * branch pointer and its compose file, and this module stays free of all three.\n */\nexport interface ManagedDatabaseStatus {\n /**\n * The daemon's connection string, or null when it is not running.\n *\n * Null is not an error: the managed database exists per project and starts\n * on demand. It only means there is nothing to run the whole-set check\n * against, and the row says so rather than implying a misconfiguration.\n */\n url: string | null;\n}\n\n/**\n * The compose `db` service, when a project is on Postgres in Docker.\n *\n * `rebase dev --docker` is remembered, and every command follows it with the\n * scaffold's `DATABASE_URL` still commented out — so, judged by `.env` alone,\n * this view said the default database had no connection string while `rebase\n * dev --docker` served the project from it. Unlike the managed database it\n * stands in for the default only: `dev --docker` hands the backend\n * `DATABASE_URL` and nothing else, so a second declared database still needs\n * its own variable.\n */\nexport interface DockerDatabaseStatus {\n /** The compose service's connection string, which the runtime is given as `DATABASE_URL`. */\n url: string;\n /** What the default database's row says it is. */\n detail: string;\n}\n\n/**\n * The resolver-side of status, as `@rebasepro/server` registers it per kind.\n *\n * Passed in rather than imported so this module stays testable without a\n * server, and so a kind registered by a plugin is judged by the resolver the\n * plugin brought with it rather than by a switch here.\n */\nexport interface StatusResolvers {\n /** `resourceResolver(kind)` from `@rebasepro/server`. */\n resolverFor: (kind: string) => {\n accountScoped?: readonly string[];\n resolve: (\n declaration: ResourceDeclaration,\n env: EnvBag,\n context: { production: boolean; defaultBasePath: string }\n ) => { state: \"ready\" | \"unbound\" | \"blocked\" | \"code\"; detail?: string; standsIn?: string };\n } | undefined;\n /** `resolveDataSources` from `@rebasepro/server`, for the whole-set check. */\n resolveDataSources: (env: EnvBag, definitions: DataSourceDefinition[]) => unknown;\n /** Whether the process being judged is production. Status judges for development by default. */\n production?: boolean;\n /**\n * Set when this project runs on the managed development database.\n *\n * Absent for a project that named its own connection string, and absent in\n * production — where an unset `DATABASE_URL` is the failure it has always\n * been.\n */\n managedDatabase?: ManagedDatabaseStatus;\n /** Set when this project runs on Postgres in Docker. Absent in production, like the managed one. */\n dockerDatabase?: DockerDatabaseStatus;\n}\n\n/**\n * The environment plus the managed database's URL, for the whole-set check.\n *\n * A copy: the bindings a reader sees are computed against the real `.env`, so\n * nothing here can make the view claim a variable is set that is not. This is\n * only what `resolveDataSources` is handed, and it is handed it so the check\n * judges the environment the runtime would actually get rather than throwing\n * \"Data source \"(default)\" has no connection string\" about a database that is\n * running and reachable.\n */\nfunction withManagedUrls(env: EnvBag, graph: ResourceGraph, url: string): EnvBag {\n const filled: EnvBag = { ...env };\n const keys = [\n DEFAULT_RESOURCE_KEY,\n ...graph.resources.filter(r => r.kind === \"database\").map(r => r.key)\n ];\n for (const key of keys) {\n const name = `DATABASE_URL${resourceEnvSuffix(key)}`;\n if (!isSet(filled, name)) filled[name] = url;\n }\n\n return filled;\n}\n\n/**\n * The environment with the default database's URL filled in, when `.env` leaves it out.\n *\n * What a database's resolver is judged against. The resolver checks a source\n * alongside the default one, so a second database bound by its own\n * `DATABASE_URL__ANALYTICS` was marked ✗ with `Data source \"(default)\" has no\n * connection string` — on a project whose default the managed database or the\n * compose service provides, and whose boot worked. Judged against the\n * environment the runtime actually gets, it is judged on its own string.\n */\nfunction withDefaultUrl(env: EnvBag, url: string | null | undefined): EnvBag {\n if (!url || isSet(env, \"DATABASE_URL\")) return env;\n\n return { ...env, DATABASE_URL: url };\n}\n\n/**\n * Resolve every declared resource against an environment.\n *\n * Each kind's verdict comes from the resolver `@rebasepro/server` registered\n * for it — the same one boot calls — so this view cannot say \"ready\" about a\n * binding boot would refuse. A kind with no resolver is reported as such\n * rather than skipped: a resource nobody shows is one nobody remembers to\n * configure, and a kind this runtime cannot bind is exactly what boot will\n * refuse by name.\n *\n * `resolveDataSources` is then run once over the whole set, so anything it\n * would refuse across sources (a driver package it cannot resolve for a custom\n * engine) is reported rather than missed by a view that only looked per row.\n */\nexport function computeStatus(\n graph: ResourceGraph,\n env: EnvBag,\n resolvers: StatusResolvers\n): { resources: ResourceStatus[]; blocked?: string } {\n const resources: ResourceStatus[] = [];\n const production = resolvers.production ?? false;\n const managed = resolvers.managedDatabase;\n const docker = resolvers.dockerDatabase;\n /** The default database's URL as the runtime gets it, when `.env` does not name one. */\n const devDefaultUrl = managed?.url ?? docker?.url ?? null;\n /** Database rows the managed database answered for, so `blocked` can skip them. */\n let managedCovered = 0;\n\n for (const { declaration, implicit } of withImplicitDefaults(graph)) {\n const resolver = resolvers.resolverFor(declaration.kind);\n const bindings = bindingsFor(declaration, env, resolver?.accountScoped ?? []);\n const base: Omit<ResourceStatus, \"state\" | \"detail\"> = {\n kind: declaration.kind,\n key: declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n ...(typeof declaration.options.account === \"string\"\n ? { account: declaration.options.account }\n : {}),\n implicit,\n bindings,\n ...(declaration.usedBy && declaration.usedBy.length > 0 ? { usedBy: declaration.usedBy } : {})\n };\n\n if (!resolver) {\n resources.push({\n ...base,\n state: \"broken\",\n detail: `this runtime has no resolver for a \"${declaration.kind}\" — boot refuses it by name. ` +\n \"Upgrade @rebasepro/server, or remove the declaration.\"\n });\n continue;\n }\n\n // Answered before the resolver, because the resolver reads the\n // environment and the whole point of the managed database is that the\n // environment is deliberately empty. Only for a database nobody bound:\n // a developer who set `DATABASE_URL__ANALYTICS` to a warehouse of their\n // own has said which database that is, and the managed one fills a\n // vacuum, never a choice.\n if (managed && declaration.kind === \"database\" && bindings.every(b => !b.set && !b.fallback?.set)) {\n managedCovered += 1;\n resources.push({\n ...base,\n state: \"ready\",\n detail: managed.url\n ? \"the managed development database (PGlite), this project only\"\n : \"the managed development database (PGlite), this project only — \"\n + \"not running; start it with `rebase dev`\"\n });\n continue;\n }\n\n // The default database on Docker: the compose service, unless `.env`\n // names one itself.\n if (docker && declaration.kind === \"database\" && declaration.key === DEFAULT_RESOURCE_KEY\n && bindings.every(b => !b.set && !b.fallback?.set)) {\n resources.push({ ...base, state: \"ready\", detail: docker.detail });\n continue;\n }\n\n const judged = declaration.kind === \"database\" ? withDefaultUrl(env, devDefaultUrl) : env;\n const verdict = resolver.resolve(declaration, judged, { production, defaultBasePath: \"uploads\" });\n switch (verdict.state) {\n case \"ready\":\n resources.push({\n ...base,\n state: \"ready\",\n ...(verdict.standsIn ? { standsIn: verdict.standsIn } : {}),\n detail: verdict.detail ?? \"\"\n });\n break;\n case \"code\":\n resources.push({ ...base, state: \"ready\", detail: verdict.detail ?? \"needs no environment configuration\" });\n break;\n case \"unbound\":\n resources.push({ ...base, state: \"unconfigured\", detail: verdict.detail ?? \"declared, not configured\" });\n break;\n case \"blocked\":\n resources.push({\n ...base,\n // A database the environment names nothing for is the\n // ordinary first-run state, and reads as unconfigured; a\n // binding that is set and set wrongly is broken.\n state: implicit || bindings.every(b => !b.set && !b.fallback?.set) ? \"unconfigured\" : \"broken\",\n detail: verdict.detail ?? \"boot refuses this binding\"\n });\n break;\n }\n }\n\n // Only asked when every row already looks fine. Its failures overlap with\n // the per-resource ones, and a banner repeating a line printed two rows\n // above teaches nothing — what it is here for is the failure no row models,\n // such as a custom engine whose driver package cannot be resolved.\n let blocked: string | undefined;\n // Not run when the managed database answered for a row and is not running:\n // there is no connection string to check the set against, and inventing one\n // to keep the check formally \"run\" is how a green tick gets printed for\n // work nobody did. The row says the daemon is down; that is the finding.\n const managedSetUnknown = managedCovered > 0 && !managed?.url;\n if (resources.every(r => r.state === \"ready\") && !managedSetUnknown) {\n try {\n resolvers.resolveDataSources(\n // The managed URL for the rows it answered for, so the whole-set\n // check judges the same environment the runtime would get.\n managed?.url ? withManagedUrls(env, graph, managed.url) : withDefaultUrl(env, docker?.url),\n graph.resources.filter(r => r.kind === \"database\").map(resourceToDataSource)\n );\n } catch (err) {\n blocked = err instanceof Error ? err.message : String(err);\n }\n }\n\n return { resources, ...(blocked !== undefined ? { blocked } : {}) };\n}\n","/**\n * `rebase status` — what this project is, and whether it can reach its things.\n *\n * The model a developer has to hold is small and was nowhere visible:\n *\n * rebase.json where the code is, and who runs the server\n * backend/resources.ts what the project needs\n * the environment how to reach each of them\n *\n * Everything else — `rebase.resources.json`, the bundle manifest — is a\n * generated copy of the middle one, for readers that cannot run the code. A\n * developer never writes them and should not have to think about them.\n *\n * This command prints the three together, resolved. It exists because the\n * question people actually arrive with — \"why does uploading to `media` answer\n * 501\" — was answerable only by knowing the `<BASE>__<KEY>` suffix rule,\n * deriving the variable name by hand, and checking it against a `.env` they had\n * to find first. Every step of that is mechanical, so it is printed instead.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError, RESOURCES_FILE } from \"../manifest\";\nimport { deriveOptionsFor, deriveResourceGraph, RESOURCE_GRAPH_FILENAME, readResourceGraphFile, serializeResourceGraph } from \"../resources/derive\";\nimport { computeStatus, type DockerDatabaseStatus, type ManagedDatabaseStatus, type ResourceStatus } from \"../resources/status\";\nimport { findRunningDaemon, managedUrl } from \"../dev-db/daemon\";\nimport { type ResolvedBranch, resolveProjectDatabaseAndBranch } from \"../dev-db/prepare\";\nimport { describeTarget } from \"../dev-db/pull\";\nimport { parseLoopbackDsn, probeTcp } from \"../utils/dev-preflight\";\nimport type { RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase status\")} — what this project declares, and whether it is configured\n\n${chalk.bold(\"Usage\")}\n rebase status Show every resource and the variables it reads\n rebase status --json The same, as JSON\n\n${chalk.bold(\"Reads\")}\n rebase.json which apps exist, and who owns the server process\n backend/resources.ts the databases, buckets, topics and queues declared\n backend/crons, backend/functions the crons and functions, by filename\n .env whether each one's variables are set\n`);\n}\n\nconst MARK = {\n ready: chalk.green(\"✓\"),\n unconfigured: chalk.yellow(\"○\"),\n broken: chalk.red(\"✗\")\n} as const;\n\nfunction printResource(status: ResourceStatus): void {\n const name = status.key === \"(default)\" ? chalk.bold(\"(default)\") : chalk.bold(status.key);\n const tags = [chalk.gray(status.engine)];\n if (status.transport !== \"server\") tags.push(chalk.yellow(status.transport));\n if (status.account) tags.push(chalk.gray(`account:${status.account}`));\n if (status.implicit) tags.push(chalk.gray(\"implicit\"));\n // A stand-in is not a binding. It is shown in yellow beside a green tick:\n // uploads work here, and the same declaration answers 501 in production\n // until the variable is set.\n if (status.standsIn) tags.push(chalk.yellow(`local stand-in for ${status.standsIn}`));\n\n console.log(` ${MARK[status.state]} ${name} ${tags.join(\" · \")}`);\n if (status.usedBy && status.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(status.usedBy.join(\", \"))}`);\n }\n\n let hiddenOptional = 0;\n for (const binding of status.bindings) {\n if (binding.set) {\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.name)}`);\n } else if (binding.fallback?.set) {\n // Not a gap: the account form is the variable this bucket is\n // actually reading, and showing only the unset per-key name would\n // send someone to set the one they were deliberately avoiding.\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.fallback.name)} ${chalk.gray(`(shared, for ${binding.name})`)}`);\n } else if (status.state === \"ready\") {\n // It resolved without this one, so this one is optional — which is\n // the resolver's answer, not a second table of required names kept\n // here. Listing seven unset optionals under a working database is\n // how a status view teaches people to skim past the line that\n // matters.\n hiddenOptional += 1;\n } else {\n const also = binding.fallback ? chalk.gray(` or ${binding.fallback.name}`) : \"\";\n console.log(` ${chalk.gray(\"·\")} ${chalk.gray(binding.name)}${also} ${chalk.gray(\"not set\")}`);\n }\n }\n if (hiddenOptional > 0) {\n console.log(chalk.gray(` ${hiddenOptional} optional variable${hiddenOptional === 1 ? \"\" : \"s\"} not set`));\n }\n\n if (status.detail) {\n const colour = status.state === \"broken\" ? chalk.red : status.state === \"unconfigured\" ? chalk.yellow : chalk.gray;\n console.log(` ${colour(`└ ${status.detail}`)}`);\n }\n}\n\n/** Which database `rebase status` reports the project on, and what it hands the status view about it. */\nexport interface StatusDatabase {\n managedDatabase?: ManagedDatabaseStatus;\n dockerDatabase?: DockerDatabaseStatus;\n /** The branch this checkout is on, when the database is one. */\n branch: ResolvedBranch | null;\n /** A switched-to branch the managed database cannot serve. */\n ignoredBranch: string | null;\n}\n\n/**\n * Which database this project is on, decided by the same ordered rule\n * `rebase dev` and `rebase db url` use — and read from the project's `.env`,\n * not from this shell: `rebase status` asks what *this project* is on.\n *\n * Nothing is started. `status` is a question, and a question that boots a\n * 180 MB Postgres to answer itself is a different command. So a managed\n * database that is not running is reported as exactly that, rather than as a\n * project with no database; and a compose database likewise, after a probe of\n * its port.\n *\n * `envFile` is the parsed `.env`; production stands nothing in, because there\n * an unset `DATABASE_URL` is the failure it has always been.\n *\n * Exported for its tests.\n */\nexport async function statusDatabase(projectRoot: string, envFile: Record<string, string>): Promise<StatusDatabase> {\n const { database, branch, ignoredBranch } = resolveProjectDatabaseAndBranch(projectRoot, { env: {} });\n if (envFile.NODE_ENV === \"production\") return { branch, ignoredBranch };\n\n if (database.kind === \"managed\") {\n const daemon = await findRunningDaemon(projectRoot);\n return { managedDatabase: { url: daemon ? managedUrl(daemon.port) : null }, branch, ignoredBranch };\n }\n\n if (database.kind === \"docker\" && database.url) {\n const target = parseLoopbackDsn(database.url);\n const listening = target ? await probeTcp(target.host, target.port) : true;\n const which = branch ? `branch \"${branch.name}\" (${branch.database}) of Postgres in Docker` : \"Postgres in Docker\";\n return {\n dockerDatabase: {\n url: database.url,\n detail: which + \", as the last `rebase dev --docker` did · \" + describeTarget(database.url)\n + (listening ? \"\" : \" — not running; `rebase dev --docker` starts it\")\n },\n branch,\n ignoredBranch\n };\n }\n\n return { branch, ignoredBranch };\n}\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: { \"--json\": Boolean },\n rawArgs,\n commandWords: 1,\n command: \"status\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, because `--json` means stdout holds\n // one JSON object on *every* exit of the command. It used to mean that for\n // the one failure `requireProjectRoot` owns and nothing else, so a caller\n // parsing stdout got an envelope outside a project and an empty stream\n // inside a broken one — the case it actually has to handle.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backend: { name: string; app: RebaseBackendAppConfig };\n try {\n const loaded = loadManifest(projectRoot);\n const found = findBackendApp(loaded.manifest);\n if (!found) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backend = found;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { name: backendName, app: backendApp } = backend;\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The project's own `.env`, not this process's environment: `rebase status`\n // is asking what a deployment of THIS repository would do, and the shell a\n // developer happens to be standing in is not that.\n const env = readEnvFile(projectRoot);\n\n const production = env.NODE_ENV === \"production\";\n const { managedDatabase, dockerDatabase, branch, ignoredBranch } = await statusDatabase(projectRoot, env);\n\n const server = await import(\"@rebasepro/server\");\n const { resources, blocked } = computeStatus(graph, env, {\n resolverFor: server.resourceResolver,\n resolveDataSources: server.resolveDataSources,\n // Judged as production when the .env says so; a stand-in local\n // directory for an unbound bucket is only ever offered to development.\n production,\n ...(managedDatabase ? { managedDatabase } : {}),\n ...(dockerDatabase ? { dockerDatabase } : {})\n });\n\n if (asJson) {\n console.log(JSON.stringify({\n backend: backendName,\n runtime: backendApp.runtime,\n ...(branch ? { branch: { name: branch.name, database: branch.database } } : {}),\n resources,\n blocked\n }, null, 2));\n return;\n }\n\n const ownership = backendApp.runtime === \"managed\"\n ? \"Rebase's runtime boots your bundle\"\n : \"this project builds its own image and entrypoint\";\n\n console.log(\"\");\n console.log(` ${chalk.bold(backendName)} ${chalk.gray(\"·\")} ${chalk.cyan(backendApp.runtime)} ${chalk.gray(ownership)}`);\n // Named whether or not it exists, and said plainly when it does not. A\n // project with no `resources.ts` is legal — it has one default database and\n // one default bucket — but \"declared in <a file you do not have>\" reads as\n // a broken install rather than as the default it is.\n const resourcesFile = RESOURCES_FILE;\n const declaresAnything = fs.existsSync(path.join(projectRoot, resourcesFile));\n console.log(` ${chalk.gray(\"declared in\")} ${chalk.gray(resourcesFile)}${\n declaresAnything ? \"\" : chalk.gray(\" (none — the defaults below are implicit)\")}`);\n console.log(` ${chalk.gray(\"configured by\")} ${chalk.gray(\".env\")}`);\n // Every database command in this checkout uses the branch, so the view\n // says so: a switch made yesterday is easy to forget.\n if (branch) {\n console.log(` ${chalk.gray(\"on branch\")} ${chalk.bold(branch.name)} ${chalk.gray(`(${branch.database})`)}`\n + chalk.gray(` — ${chalk.cyan(\"rebase db branch switch --off\")} returns to ${branch.parent ?? \"the main database\"}`));\n } else if (ignoredBranch) {\n console.log(` ${chalk.yellow(\"○\")} ${chalk.gray(`switched to branch \"${ignoredBranch}\", which the managed database cannot serve — it uses the main one`)}`);\n }\n\n const kinds = [...new Set(resources.map(r => r.kind))];\n for (const kind of kinds) {\n console.log(\"\");\n console.log(` ${chalk.bold.underline(`${kind}s`)}`);\n for (const status of resources.filter(r => r.kind === kind)) printResource(status);\n }\n\n if (blocked) {\n console.log(\"\");\n console.log(` ${chalk.red(\"✗\")} ${chalk.red(blocked)}`);\n }\n\n // Only worth a line when it is wrong. A generated file that matches its\n // declarations is not news, and a status view that reports its own\n // bookkeeping as an item trains people to skim past the items that matter.\n //\n // Nor is one that has not been written yet: `rebase build` writes it on\n // every build and says \"commit it\" when it changes, so a project that has\n // never been built — every fresh scaffold — has nothing wrong with it.\n // `rebase resources --check` is the gate that refuses a missing one.\n const committed = readResourceGraphFile(projectRoot);\n if (committed !== null && committed !== serializeResourceGraph(graph)) {\n console.log(\"\");\n console.log(` ${chalk.yellow(\"○\")} ${RESOURCE_GRAPH_FILENAME} is stale — ${chalk.blue(\"rebase resources --write\")}`);\n console.log(chalk.gray(\" a host reads it to decide what to provision before it runs anything\"));\n }\n\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAS,MAAM,KAAa,MAAuB;CAC/C,MAAM,QAAQ,IAAI;CAClB,OAAO,OAAO,UAAU,YAAY,UAAU;AAClD;;;;;;;;AASA,SAAgB,YACZ,aACA,KACA,oBACiB;CACjB,IAAI,YAAY,cAAc,UAAU,OAAO,CAAC;CAEhD,MAAM,SAAS,kBAAkB,YAAY,GAAG;CAChD,MAAM,UAAU,OAAO,YAAY,QAAQ,YAAY,WACjD,kBAAkB,YAAY,QAAQ,OAAO,IAC7C,KAAA;CAEN,OAAO,oBAAoB,WAAW,CAAC,CAAC,KAAK,SAAS;EAClD,MAAM,OAAO,GAAG,OAAO;EACvB,MAAM,UAA2B;GAAE;GAAM,KAAK,MAAM,KAAK,IAAI;EAAE;EAK/D,IAAI,YAAY,KAAA,KAAa,CAAC,QAAQ,OAAO,mBAAmB,SAAS,IAAI,GACzE,QAAQ,WAAW;GAAE,MAAM,GAAG,OAAO;GAAW,KAAK,MAAM,KAAK,GAAG,OAAO,SAAS;EAAE;EAEzF,OAAO;CACX,CAAC;AACL;;;;;;;;;;;AAwFA,SAAS,gBAAgB,KAAa,OAAsB,KAAqB;CAC7E,MAAM,SAAiB,E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,YAAY,sBAAsB,WAAW;CACnD,IAAI,cAAc,QAAQ,cAAc,uBAAuB,KAAK,GAAG;EACnE,QAAQ,IAAI,EAAE;EACd,QAAQ,IAAI,KAAK,MAAM,OAAO,GAAG,EAAE,GAAG,wBAAwB,cAAc,MAAM,KAAK,0BAA0B,GAAG;EACpH,QAAQ,IAAI,MAAM,KAAK,2EAA2E,CAAC;CACvG;CAEA,QAAQ,IAAI,EAAE;AAClB"}
|
|
1
|
+
{"version":3,"file":"status-CVEzoSwX.js","names":[],"sources":["../src/resources/status.ts","../src/commands/status.ts"],"sourcesContent":["/**\n * What a project declared, what the environment binds it to, and whether the\n * two meet.\n *\n * ## Why this exists\n *\n * Every piece of this was already knowable and none of it was visible in one\n * place. `rebase resources` lists what you declared. The environment holds the\n * variables. The resolvers decide whether a source is usable. So the question a\n * developer actually has — *\"why does uploading to `media` answer 501\"* — could\n * only be answered by knowing the suffix rule, deriving the variable name by\n * hand, and checking it against a `.env` they had to find first.\n *\n * The answer is mechanical, so it should be printed rather than taught.\n *\n * ## Why it calls the resolvers instead of re-deciding\n *\n * The verdict comes from `resolveDataSources` and `resolveStorageBackend` — the\n * same functions that run at boot. A status view that decided for itself what\n * \"configured\" means would be a second implementation of the rule, and the\n * first time it disagreed it would be reassuring a developer about a deployment\n * that is about to refuse to start.\n *\n * The variable *names* come from each kind's `envBases`, and the verdicts from\n * the resolver `@rebasepro/server` registers per kind — one object per kind,\n * held to `envBases` by `resource-env-bases.test.ts`. A kind this view has\n * never heard of is judged by whatever resolver its package registered.\n */\nimport { withImplicitDefaults } from \"./derive\";\nimport {\n DEFAULT_RESOURCE_KEY,\n envBasesForResource,\n resourceEnvSuffix,\n resourceToDataSource,\n type DataSourceDefinition,\n type ResourceDeclaration,\n type ResourceGraph\n} from \"@rebasepro/types\";\n\n/** One environment variable a resource reads, and whether it is there. */\nexport interface ResourceBinding {\n /** The variable this resource reads, suffix included. */\n name: string;\n set: boolean;\n /**\n * The account-scoped name consulted when `name` is unset.\n *\n * Only provider-level bindings have one, and only when the resource named\n * an `account`. Shown because a developer looking at an unset\n * `S3_ACCESS_KEY_ID__MEDIA` needs to know it is not the whole story.\n */\n fallback?: { name: string; set: boolean };\n}\n\n/** Whether a declared resource can actually be reached. */\nexport type ResourceState =\n /** Bound and usable. */\n | \"ready\"\n /** Nothing set for it. Legal for a bucket, fatal for a database. */\n | \"unconfigured\"\n /** Set, and set wrongly. The deployment refuses to start. */\n | \"broken\";\n\nexport interface ResourceStatus {\n kind: string;\n key: string;\n engine: string;\n transport: string;\n /** Present when this resource shares another's credentials. */\n account?: string;\n /** True for a resource nobody declared, which exists anyway. */\n implicit: boolean;\n bindings: ResourceBinding[];\n state: ResourceState;\n /** What this means, in the terms the developer will meet it in. */\n detail: string;\n /** Set when a local directory stands in for this engine, in development. */\n standsIn?: string;\n /** What in the project reaches this resource, from the graph. */\n usedBy?: readonly string[];\n}\n\nexport type EnvBag = Record<string, string | undefined>;\n\n/** Set, and not set to the empty string — which the resolvers treat as absent. */\nfunction isSet(env: EnvBag, name: string): boolean {\n const value = env[name];\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * The bindings one declaration reads, in the order a reader should scan them.\n *\n * A `direct`-transport resource gets none: the browser reaches it with a\n * provider SDK and the backend binds nothing for it, so listing variables would\n * invite someone to set variables that are never read.\n */\nexport function bindingsFor(\n declaration: ResourceDeclaration,\n env: EnvBag,\n accountScopedBases: readonly string[]\n): ResourceBinding[] {\n if (declaration.transport !== \"server\") return [];\n\n const suffix = resourceEnvSuffix(declaration.key);\n const account = typeof declaration.options.account === \"string\"\n ? resourceEnvSuffix(declaration.options.account)\n : undefined;\n\n return envBasesForResource(declaration).map((base) => {\n const name = `${base}${suffix}`;\n const binding: ResourceBinding = { name, set: isSet(env, name) };\n\n // Only the provider-level bindings fall back, and only for a resource\n // that named an account. The bucket name never does — it is what\n // distinguishes one source from another.\n if (account !== undefined && !binding.set && accountScopedBases.includes(base)) {\n binding.fallback = { name: `${base}${account}`, set: isSet(env, `${base}${account}`) };\n }\n return binding;\n });\n}\n\n/**\n * What the managed development database covers, when a project is on it.\n *\n * `rebase init` leaves `DATABASE_URL` commented out on purpose and the managed\n * PGlite fills the vacuum — the documented first-run state. Judging that state\n * by the environment alone produced `○ (default) postgres · DATABASE_URL not\n * set` and the remedy \"set DATABASE_URL\", at the same moment `rebase db url`\n * was printing a working connection string for the same project and\n * `rebase dev` was serving from it. The status view was reading the one place\n * the answer deliberately is not.\n *\n * Resolved by the caller, because deciding it needs the project's `.env`, its\n * branch pointer and its compose file, and this module stays free of all three.\n */\nexport interface ManagedDatabaseStatus {\n /**\n * The daemon's connection string, or null when it is not running.\n *\n * Null is not an error: the managed database exists per project and starts\n * on demand. It only means there is nothing to run the whole-set check\n * against, and the row says so rather than implying a misconfiguration.\n */\n url: string | null;\n}\n\n/**\n * The compose `db` service, when a project is on Postgres in Docker.\n *\n * `rebase dev --docker` is remembered, and every command follows it with the\n * scaffold's `DATABASE_URL` still commented out — so, judged by `.env` alone,\n * this view said the default database had no connection string while `rebase\n * dev --docker` served the project from it. Unlike the managed database it\n * stands in for the default only: `dev --docker` hands the backend\n * `DATABASE_URL` and nothing else, so a second declared database still needs\n * its own variable.\n */\nexport interface DockerDatabaseStatus {\n /** The compose service's connection string, which the runtime is given as `DATABASE_URL`. */\n url: string;\n /** What the default database's row says it is. */\n detail: string;\n}\n\n/**\n * The resolver-side of status, as `@rebasepro/server` registers it per kind.\n *\n * Passed in rather than imported so this module stays testable without a\n * server, and so a kind registered by a plugin is judged by the resolver the\n * plugin brought with it rather than by a switch here.\n */\nexport interface StatusResolvers {\n /** `resourceResolver(kind)` from `@rebasepro/server`. */\n resolverFor: (kind: string) => {\n accountScoped?: readonly string[];\n resolve: (\n declaration: ResourceDeclaration,\n env: EnvBag,\n context: { production: boolean; defaultBasePath: string }\n ) => { state: \"ready\" | \"unbound\" | \"blocked\" | \"code\"; detail?: string; standsIn?: string };\n } | undefined;\n /** `resolveDataSources` from `@rebasepro/server`, for the whole-set check. */\n resolveDataSources: (env: EnvBag, definitions: DataSourceDefinition[]) => unknown;\n /** Whether the process being judged is production. Status judges for development by default. */\n production?: boolean;\n /**\n * Set when this project runs on the managed development database.\n *\n * Absent for a project that named its own connection string, and absent in\n * production — where an unset `DATABASE_URL` is the failure it has always\n * been.\n */\n managedDatabase?: ManagedDatabaseStatus;\n /** Set when this project runs on Postgres in Docker. Absent in production, like the managed one. */\n dockerDatabase?: DockerDatabaseStatus;\n}\n\n/**\n * The environment plus the managed database's URL, for the whole-set check.\n *\n * A copy: the bindings a reader sees are computed against the real `.env`, so\n * nothing here can make the view claim a variable is set that is not. This is\n * only what `resolveDataSources` is handed, and it is handed it so the check\n * judges the environment the runtime would actually get rather than throwing\n * \"Data source \"(default)\" has no connection string\" about a database that is\n * running and reachable.\n */\nfunction withManagedUrls(env: EnvBag, graph: ResourceGraph, url: string): EnvBag {\n const filled: EnvBag = { ...env };\n const keys = [\n DEFAULT_RESOURCE_KEY,\n ...graph.resources.filter(r => r.kind === \"database\").map(r => r.key)\n ];\n for (const key of keys) {\n const name = `DATABASE_URL${resourceEnvSuffix(key)}`;\n if (!isSet(filled, name)) filled[name] = url;\n }\n\n return filled;\n}\n\n/**\n * The environment with the default database's URL filled in, when `.env` leaves it out.\n *\n * What a database's resolver is judged against. The resolver checks a source\n * alongside the default one, so a second database bound by its own\n * `DATABASE_URL__ANALYTICS` was marked ✗ with `Data source \"(default)\" has no\n * connection string` — on a project whose default the managed database or the\n * compose service provides, and whose boot worked. Judged against the\n * environment the runtime actually gets, it is judged on its own string.\n */\nfunction withDefaultUrl(env: EnvBag, url: string | null | undefined): EnvBag {\n if (!url || isSet(env, \"DATABASE_URL\")) return env;\n\n return { ...env, DATABASE_URL: url };\n}\n\n/**\n * Resolve every declared resource against an environment.\n *\n * Each kind's verdict comes from the resolver `@rebasepro/server` registered\n * for it — the same one boot calls — so this view cannot say \"ready\" about a\n * binding boot would refuse. A kind with no resolver is reported as such\n * rather than skipped: a resource nobody shows is one nobody remembers to\n * configure, and a kind this runtime cannot bind is exactly what boot will\n * refuse by name.\n *\n * `resolveDataSources` is then run once over the whole set, so anything it\n * would refuse across sources (a driver package it cannot resolve for a custom\n * engine) is reported rather than missed by a view that only looked per row.\n */\nexport function computeStatus(\n graph: ResourceGraph,\n env: EnvBag,\n resolvers: StatusResolvers\n): { resources: ResourceStatus[]; blocked?: string } {\n const resources: ResourceStatus[] = [];\n const production = resolvers.production ?? false;\n const managed = resolvers.managedDatabase;\n const docker = resolvers.dockerDatabase;\n /** The default database's URL as the runtime gets it, when `.env` does not name one. */\n const devDefaultUrl = managed?.url ?? docker?.url ?? null;\n /** Database rows the managed database answered for, so `blocked` can skip them. */\n let managedCovered = 0;\n\n for (const { declaration, implicit } of withImplicitDefaults(graph)) {\n const resolver = resolvers.resolverFor(declaration.kind);\n const bindings = bindingsFor(declaration, env, resolver?.accountScoped ?? []);\n const base: Omit<ResourceStatus, \"state\" | \"detail\"> = {\n kind: declaration.kind,\n key: declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n ...(typeof declaration.options.account === \"string\"\n ? { account: declaration.options.account }\n : {}),\n implicit,\n bindings,\n ...(declaration.usedBy && declaration.usedBy.length > 0 ? { usedBy: declaration.usedBy } : {})\n };\n\n if (!resolver) {\n resources.push({\n ...base,\n state: \"broken\",\n detail: `this runtime has no resolver for a \"${declaration.kind}\" — boot refuses it by name. ` +\n \"Upgrade @rebasepro/server, or remove the declaration.\"\n });\n continue;\n }\n\n // Answered before the resolver, because the resolver reads the\n // environment and the whole point of the managed database is that the\n // environment is deliberately empty. Only for a database nobody bound:\n // a developer who set `DATABASE_URL__ANALYTICS` to a warehouse of their\n // own has said which database that is, and the managed one fills a\n // vacuum, never a choice.\n if (managed && declaration.kind === \"database\" && bindings.every(b => !b.set && !b.fallback?.set)) {\n managedCovered += 1;\n resources.push({\n ...base,\n state: \"ready\",\n detail: managed.url\n ? \"the managed development database (PGlite), this project only\"\n : \"the managed development database (PGlite), this project only — \"\n + \"not running; start it with `rebase dev`\"\n });\n continue;\n }\n\n // The default database on Docker: the compose service, unless `.env`\n // names one itself.\n if (docker && declaration.kind === \"database\" && declaration.key === DEFAULT_RESOURCE_KEY\n && bindings.every(b => !b.set && !b.fallback?.set)) {\n resources.push({ ...base, state: \"ready\", detail: docker.detail });\n continue;\n }\n\n const judged = declaration.kind === \"database\" ? withDefaultUrl(env, devDefaultUrl) : env;\n const verdict = resolver.resolve(declaration, judged, { production, defaultBasePath: \"uploads\" });\n switch (verdict.state) {\n case \"ready\":\n resources.push({\n ...base,\n state: \"ready\",\n ...(verdict.standsIn ? { standsIn: verdict.standsIn } : {}),\n detail: verdict.detail ?? \"\"\n });\n break;\n case \"code\":\n resources.push({ ...base, state: \"ready\", detail: verdict.detail ?? \"needs no environment configuration\" });\n break;\n case \"unbound\":\n resources.push({ ...base, state: \"unconfigured\", detail: verdict.detail ?? \"declared, not configured\" });\n break;\n case \"blocked\":\n resources.push({\n ...base,\n // A database the environment names nothing for is the\n // ordinary first-run state, and reads as unconfigured; a\n // binding that is set and set wrongly is broken.\n state: implicit || bindings.every(b => !b.set && !b.fallback?.set) ? \"unconfigured\" : \"broken\",\n detail: verdict.detail ?? \"boot refuses this binding\"\n });\n break;\n }\n }\n\n // Only asked when every row already looks fine. Its failures overlap with\n // the per-resource ones, and a banner repeating a line printed two rows\n // above teaches nothing — what it is here for is the failure no row models,\n // such as a custom engine whose driver package cannot be resolved.\n let blocked: string | undefined;\n // Not run when the managed database answered for a row and is not running:\n // there is no connection string to check the set against, and inventing one\n // to keep the check formally \"run\" is how a green tick gets printed for\n // work nobody did. The row says the daemon is down; that is the finding.\n const managedSetUnknown = managedCovered > 0 && !managed?.url;\n if (resources.every(r => r.state === \"ready\") && !managedSetUnknown) {\n try {\n resolvers.resolveDataSources(\n // The managed URL for the rows it answered for, so the whole-set\n // check judges the same environment the runtime would get.\n managed?.url ? withManagedUrls(env, graph, managed.url) : withDefaultUrl(env, docker?.url),\n graph.resources.filter(r => r.kind === \"database\").map(resourceToDataSource)\n );\n } catch (err) {\n blocked = err instanceof Error ? err.message : String(err);\n }\n }\n\n return { resources, ...(blocked !== undefined ? { blocked } : {}) };\n}\n","/**\n * `rebase status` — what this project is, and whether it can reach its things.\n *\n * The model a developer has to hold is small and was nowhere visible:\n *\n * rebase.json where the code is, and who runs the server\n * backend/resources.ts what the project needs\n * the environment how to reach each of them\n *\n * Everything else — `rebase.resources.json`, the bundle manifest — is a\n * generated copy of the middle one, for readers that cannot run the code. A\n * developer never writes them and should not have to think about them.\n *\n * This command prints the three together, resolved. It exists because the\n * question people actually arrive with — \"why does uploading to `media` answer\n * 501\" — was answerable only by knowing the `<BASE>__<KEY>` suffix rule,\n * deriving the variable name by hand, and checking it against a `.env` they had\n * to find first. Every step of that is mechanical, so it is printed instead.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError, RESOURCES_FILE } from \"../manifest\";\nimport { deriveOptionsFor, deriveResourceGraph, RESOURCE_GRAPH_FILENAME, readResourceGraphFile, serializeResourceGraph } from \"../resources/derive\";\nimport { computeStatus, type DockerDatabaseStatus, type ManagedDatabaseStatus, type ResourceStatus } from \"../resources/status\";\nimport { findRunningDaemon, managedUrl } from \"../dev-db/daemon\";\nimport { type ResolvedBranch, resolveProjectDatabaseAndBranch } from \"../dev-db/prepare\";\nimport { describeTarget } from \"../dev-db/pull\";\nimport { parseLoopbackDsn, probeTcp } from \"../utils/dev-preflight\";\nimport type { RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase status\")} — what this project declares, and whether it is configured\n\n${chalk.bold(\"Usage\")}\n rebase status Show every resource and the variables it reads\n rebase status --json The same, as JSON\n\n${chalk.bold(\"Reads\")}\n rebase.json which apps exist, and who owns the server process\n backend/resources.ts the databases, buckets, topics and queues declared\n backend/crons, backend/functions the crons and functions, by filename\n .env whether each one's variables are set\n`);\n}\n\nconst MARK = {\n ready: chalk.green(\"✓\"),\n unconfigured: chalk.yellow(\"○\"),\n broken: chalk.red(\"✗\")\n} as const;\n\nfunction printResource(status: ResourceStatus): void {\n const name = status.key === \"(default)\" ? chalk.bold(\"(default)\") : chalk.bold(status.key);\n const tags = [chalk.gray(status.engine)];\n if (status.transport !== \"server\") tags.push(chalk.yellow(status.transport));\n if (status.account) tags.push(chalk.gray(`account:${status.account}`));\n if (status.implicit) tags.push(chalk.gray(\"implicit\"));\n // A stand-in is not a binding. It is shown in yellow beside a green tick:\n // uploads work here, and the same declaration answers 501 in production\n // until the variable is set.\n if (status.standsIn) tags.push(chalk.yellow(`local stand-in for ${status.standsIn}`));\n\n console.log(` ${MARK[status.state]} ${name} ${tags.join(\" · \")}`);\n if (status.usedBy && status.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(status.usedBy.join(\", \"))}`);\n }\n\n let hiddenOptional = 0;\n for (const binding of status.bindings) {\n if (binding.set) {\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.name)}`);\n } else if (binding.fallback?.set) {\n // Not a gap: the account form is the variable this bucket is\n // actually reading, and showing only the unset per-key name would\n // send someone to set the one they were deliberately avoiding.\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.fallback.name)} ${chalk.gray(`(shared, for ${binding.name})`)}`);\n } else if (status.state === \"ready\") {\n // It resolved without this one, so this one is optional — which is\n // the resolver's answer, not a second table of required names kept\n // here. Listing seven unset optionals under a working database is\n // how a status view teaches people to skim past the line that\n // matters.\n hiddenOptional += 1;\n } else {\n const also = binding.fallback ? chalk.gray(` or ${binding.fallback.name}`) : \"\";\n console.log(` ${chalk.gray(\"·\")} ${chalk.gray(binding.name)}${also} ${chalk.gray(\"not set\")}`);\n }\n }\n if (hiddenOptional > 0) {\n console.log(chalk.gray(` ${hiddenOptional} optional variable${hiddenOptional === 1 ? \"\" : \"s\"} not set`));\n }\n\n if (status.detail) {\n const colour = status.state === \"broken\" ? chalk.red : status.state === \"unconfigured\" ? chalk.yellow : chalk.gray;\n console.log(` ${colour(`└ ${status.detail}`)}`);\n }\n}\n\n/** Which database `rebase status` reports the project on, and what it hands the status view about it. */\nexport interface StatusDatabase {\n managedDatabase?: ManagedDatabaseStatus;\n dockerDatabase?: DockerDatabaseStatus;\n /** The branch this checkout is on, when the database is one. */\n branch: ResolvedBranch | null;\n /** A switched-to branch the managed database cannot serve. */\n ignoredBranch: string | null;\n}\n\n/**\n * Which database this project is on, decided by the same ordered rule\n * `rebase dev` and `rebase db url` use — and read from the project's `.env`,\n * not from this shell: `rebase status` asks what *this project* is on.\n *\n * Nothing is started. `status` is a question, and a question that boots a\n * 180 MB Postgres to answer itself is a different command. So a managed\n * database that is not running is reported as exactly that, rather than as a\n * project with no database; and a compose database likewise, after a probe of\n * its port.\n *\n * `envFile` is the parsed `.env`; production stands nothing in, because there\n * an unset `DATABASE_URL` is the failure it has always been.\n *\n * Exported for its tests.\n */\nexport async function statusDatabase(projectRoot: string, envFile: Record<string, string>): Promise<StatusDatabase> {\n const { database, branch, ignoredBranch } = resolveProjectDatabaseAndBranch(projectRoot, { env: {} });\n if (envFile.NODE_ENV === \"production\") return { branch, ignoredBranch };\n\n if (database.kind === \"managed\") {\n const daemon = await findRunningDaemon(projectRoot);\n return { managedDatabase: { url: daemon ? managedUrl(daemon.port) : null }, branch, ignoredBranch };\n }\n\n if (database.kind === \"docker\" && database.url) {\n const target = parseLoopbackDsn(database.url);\n const listening = target ? await probeTcp(target.host, target.port) : true;\n const which = branch ? `branch \"${branch.name}\" (${branch.database}) of Postgres in Docker` : \"Postgres in Docker\";\n return {\n dockerDatabase: {\n url: database.url,\n detail: which + \", as the last `rebase dev --docker` did · \" + describeTarget(database.url)\n + (listening ? \"\" : \" — not running; `rebase dev --docker` starts it\")\n },\n branch,\n ignoredBranch\n };\n }\n\n return { branch, ignoredBranch };\n}\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: { \"--json\": Boolean },\n rawArgs,\n commandWords: 1,\n command: \"status\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, because `--json` means stdout holds\n // one JSON object on *every* exit of the command. It used to mean that for\n // the one failure `requireProjectRoot` owns and nothing else, so a caller\n // parsing stdout got an envelope outside a project and an empty stream\n // inside a broken one — the case it actually has to handle.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backend: { name: string; app: RebaseBackendAppConfig };\n try {\n const loaded = loadManifest(projectRoot);\n const found = findBackendApp(loaded.manifest);\n if (!found) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backend = found;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { name: backendName, app: backendApp } = backend;\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The project's own `.env`, not this process's environment: `rebase status`\n // is asking what a deployment of THIS repository would do, and the shell a\n // developer happens to be standing in is not that.\n const env = readEnvFile(projectRoot);\n\n const production = env.NODE_ENV === \"production\";\n const { managedDatabase, dockerDatabase, branch, ignoredBranch } = await statusDatabase(projectRoot, env);\n\n const server = await import(\"@rebasepro/server\");\n const { resources, blocked } = computeStatus(graph, env, {\n resolverFor: server.resourceResolver,\n resolveDataSources: server.resolveDataSources,\n // Judged as production when the .env says so; a stand-in local\n // directory for an unbound bucket is only ever offered to development.\n production,\n ...(managedDatabase ? { managedDatabase } : {}),\n ...(dockerDatabase ? { dockerDatabase } : {})\n });\n\n if (asJson) {\n console.log(JSON.stringify({\n backend: backendName,\n runtime: backendApp.runtime,\n ...(branch ? { branch: { name: branch.name, database: branch.database } } : {}),\n resources,\n blocked\n }, null, 2));\n return;\n }\n\n const ownership = backendApp.runtime === \"managed\"\n ? \"Rebase's runtime boots your bundle\"\n : \"this project builds its own image and entrypoint\";\n\n console.log(\"\");\n console.log(` ${chalk.bold(backendName)} ${chalk.gray(\"·\")} ${chalk.cyan(backendApp.runtime)} ${chalk.gray(ownership)}`);\n // Named whether or not it exists, and said plainly when it does not. A\n // project with no `resources.ts` is legal — it has one default database and\n // one default bucket — but \"declared in <a file you do not have>\" reads as\n // a broken install rather than as the default it is.\n const resourcesFile = RESOURCES_FILE;\n const declaresAnything = fs.existsSync(path.join(projectRoot, resourcesFile));\n console.log(` ${chalk.gray(\"declared in\")} ${chalk.gray(resourcesFile)}${\n declaresAnything ? \"\" : chalk.gray(\" (none — the defaults below are implicit)\")}`);\n console.log(` ${chalk.gray(\"configured by\")} ${chalk.gray(\".env\")}`);\n // Every database command in this checkout uses the branch, so the view\n // says so: a switch made yesterday is easy to forget.\n if (branch) {\n console.log(` ${chalk.gray(\"on branch\")} ${chalk.bold(branch.name)} ${chalk.gray(`(${branch.database})`)}`\n + chalk.gray(` — ${chalk.cyan(\"rebase db branch switch --off\")} returns to ${branch.parent ?? \"the main database\"}`));\n } else if (ignoredBranch) {\n console.log(` ${chalk.yellow(\"○\")} ${chalk.gray(`switched to branch \"${ignoredBranch}\", which the managed database cannot serve — it uses the main one`)}`);\n }\n\n const kinds = [...new Set(resources.map(r => r.kind))];\n for (const kind of kinds) {\n console.log(\"\");\n console.log(` ${chalk.bold.underline(`${kind}s`)}`);\n for (const status of resources.filter(r => r.kind === kind)) printResource(status);\n }\n\n if (blocked) {\n console.log(\"\");\n console.log(` ${chalk.red(\"✗\")} ${chalk.red(blocked)}`);\n }\n\n // Only worth a line when it is wrong. A generated file that matches its\n // declarations is not news, and a status view that reports its own\n // bookkeeping as an item trains people to skim past the items that matter.\n //\n // Nor is one that has not been written yet: `rebase build` writes it on\n // every build and says \"commit it\" when it changes, so a project that has\n // never been built — every fresh scaffold — has nothing wrong with it.\n // `rebase resources --check` is the gate that refuses a missing one.\n const committed = readResourceGraphFile(projectRoot);\n if (committed !== null && committed !== serializeResourceGraph(graph)) {\n console.log(\"\");\n console.log(` ${chalk.yellow(\"○\")} ${RESOURCE_GRAPH_FILENAME} is stale — ${chalk.blue(\"rebase resources --write\")}`);\n console.log(chalk.gray(\" a host reads it to decide what to provision before it runs anything\"));\n }\n\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAS,MAAM,KAAa,MAAuB;CAC/C,MAAM,QAAQ,IAAI;CAClB,OAAO,OAAO,UAAU,YAAY,UAAU;AAClD;;;;;;;;AASA,SAAgB,YACZ,aACA,KACA,oBACiB;CACjB,IAAI,YAAY,cAAc,UAAU,OAAO,CAAC;CAEhD,MAAM,SAAS,kBAAkB,YAAY,GAAG;CAChD,MAAM,UAAU,OAAO,YAAY,QAAQ,YAAY,WACjD,kBAAkB,YAAY,QAAQ,OAAO,IAC7C,KAAA;CAEN,OAAO,oBAAoB,WAAW,CAAC,CAAC,KAA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AE,IAAI,CAAC,CAAC;CACrD,KAAK,MAAM,QAAQ,OAAO;EACtB,QAAQ,IAAI,EAAE;EACd,QAAQ,IAAI,KAAK,MAAM,KAAK,UAAU,GAAG,KAAK,EAAE,GAAG;EACnD,KAAK,MAAM,UAAU,UAAU,QAAO,MAAK,EAAE,SAAS,IAAI,GAAG,cAAc,MAAM;CACrF;CAEA,IAAI,SAAS;EACT,QAAQ,IAAI,EAAE;EACd,QAAQ,IAAI,KAAK,MAAM,IAAI,GAAG,EAAE,GAAG,MAAM,IAAI,OAAO,GAAG;CAC3D;CAUA,MAAM,YAAY,sBAAsB,WAAW;CACnD,IAAI,cAAc,QAAQ,cAAc,uBAAuB,KAAK,GAAG;EACnE,QAAQ,IAAI,EAAE;EACd,QAAQ,IAAI,KAAK,MAAM,OAAO,GAAG,EAAE,GAAG,wBAAwB,cAAc,MAAM,KAAK,0BAA0B,GAAG;EACpH,QAAQ,IAAI,MAAM,KAAK,2EAA2E,CAAC;CACvG;CAEA,QAAQ,IAAI,EAAE;AAClB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
|
|
2
2
|
import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
|
|
3
|
-
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, l as startProjectCommand } from "./project-command-
|
|
4
|
-
import { l as confirmDestructive } from "./context-
|
|
5
|
-
import { n as describeFailure } from "./api-keys-
|
|
3
|
+
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, l as startProjectCommand } from "./project-command-5wM_bJQt.js";
|
|
4
|
+
import { l as confirmDestructive } from "./context-C9lz1vTS.js";
|
|
5
|
+
import { n as describeFailure } from "./api-keys-CG2IpknI.js";
|
|
6
6
|
import chalk from "chalk";
|
|
7
7
|
import { RebaseApiError } from "@rebasepro/client";
|
|
8
8
|
import readline from "node:readline/promises";
|
|
@@ -406,23 +406,23 @@ async function storageCommand(subcommand, rawArgs) {
|
|
|
406
406
|
break;
|
|
407
407
|
case "ls":
|
|
408
408
|
startProjectCommand(rawArgs);
|
|
409
|
-
await (await import("./storage-objects-
|
|
409
|
+
await (await import("./storage-objects-DbFsemMV.js")).storageLs(rawArgs);
|
|
410
410
|
break;
|
|
411
411
|
case "cp":
|
|
412
412
|
startProjectCommand(rawArgs);
|
|
413
|
-
await (await import("./storage-objects-
|
|
413
|
+
await (await import("./storage-objects-DbFsemMV.js")).storageCp(rawArgs);
|
|
414
414
|
break;
|
|
415
415
|
case "rm":
|
|
416
416
|
startProjectCommand(rawArgs);
|
|
417
|
-
await (await import("./storage-objects-
|
|
417
|
+
await (await import("./storage-objects-DbFsemMV.js")).storageRm(rawArgs);
|
|
418
418
|
break;
|
|
419
419
|
case "url":
|
|
420
420
|
startProjectCommand(rawArgs);
|
|
421
|
-
await (await import("./storage-objects-
|
|
421
|
+
await (await import("./storage-objects-DbFsemMV.js")).storageUrl(rawArgs);
|
|
422
422
|
break;
|
|
423
423
|
case "stat":
|
|
424
424
|
startProjectCommand(rawArgs);
|
|
425
|
-
await (await import("./storage-objects-
|
|
425
|
+
await (await import("./storage-objects-DbFsemMV.js")).storageStat(rawArgs);
|
|
426
426
|
break;
|
|
427
427
|
default: unknownCommand(subcommand, STORAGE_SUBCOMMANDS, "storage");
|
|
428
428
|
}
|
|
@@ -490,4 +490,4 @@ ${chalk.green.bold("Notes")}
|
|
|
490
490
|
//#endregion
|
|
491
491
|
export { STORAGE_SUBCOMMANDS, storageCommand };
|
|
492
492
|
|
|
493
|
-
//# sourceMappingURL=storage-
|
|
493
|
+
//# sourceMappingURL=storage-Dqf5tyhs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-Clc8dLG8.js","names":[],"sources":["../src/commands/storage.ts"],"sourcesContent":["/**\n * CLI command: rebase storage <action>\n *\n * Whole-store maintenance through the running backend's `/api/admin/storage`,\n * authenticated with the service key from `.env`.\n *\n * Subcommands:\n * orphans — Stored files no row names; `--delete` deletes them\n * move — Copy a folder of files to another storage source, same keys\n */\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport { PROJECT_TARGET_FLAGS } from \"../utils/project-target\";\nimport { projectTarget, startProjectCommand } from \"../utils/project-command\";\nimport { confirmDestructive } from \"./cloud/context\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { describeFailure } from \"./api-keys\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const STORAGE_SUBCOMMANDS = [\"orphans\", \"move\", \"ls\", \"cp\", \"rm\", \"url\", \"stat\"] as const;\n\n/** The flags `rebase storage orphans` takes. */\nexport const ORPHANS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--source\": String,\n \"--older-than\": Number,\n \"--delete\": Boolean\n} as const;\n\n/** The flags `rebase storage move` takes. */\nexport const MOVE_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--from\": String,\n \"--to\": String,\n \"--prefix\": String,\n \"--delete-source\": Boolean\n} as const;\n\n/** One stored object, as the backend lists it. */\ninterface StoredObjectEntry {\n key: string;\n size?: number;\n updated?: string;\n}\n\n/** What `GET /admin/storage/orphans` answers. */\nexport interface OrphanReport {\n storageId: string;\n objects: number;\n orphans: StoredObjectEntry[];\n recent: number;\n scanned: string[];\n unscanned: { collection: string; reason: string }[];\n}\n\n/** An orphan scan's record, as `GET /admin/storage/orphans/scans/:id` answers it. */\ninterface OrphanScanState {\n id: string;\n storageId: string;\n runner: \"worker\" | \"in-process\";\n status: \"queued\" | \"running\" | \"completed\" | \"failed\";\n progress: {\n phase: string;\n filesScanned: number;\n rowsScanned: number;\n historyEntriesScanned: number;\n collectionsScanned: number;\n collectionsTotal: number;\n unscanned: { collection: string; reason: string }[];\n };\n result?: Omit<OrphanReport, \"storageId\">;\n error?: string;\n note?: string;\n deletion?: {\n status: \"queued\" | \"running\" | \"completed\" | \"failed\";\n progress: OrphanScanState[\"progress\"] & { candidates: number; deleted: number };\n result?: { deleted: string[]; kept: { key: string; reason: string }[]; failed: { key: string; error: string }[] };\n error?: string;\n note?: string;\n };\n}\n\n/** How often a running scan is asked about. A setting so the tests need not wait. */\nexport const orphanScanPolling = { intervalMs: 1_000 };\n\ninterface MovedObject {\n key: string;\n outcome: \"copied\" | \"exists\" | \"failed\";\n deleted?: boolean;\n error?: string;\n}\n\ninterface Backend {\n baseUrl: string;\n request<T>(method: string, path: string, body?: unknown): Promise<T>;\n}\n\n/**\n * The project's backend, holding the service key — the `admin` role, every\n * scope — or whatever credential the target flags name, resolved the way\n * every project command resolves it (`utils/project-target.ts`): the local\n * `rebase dev`, `--url`, `REBASE_BASE_URL`, or `--project` for Rebase Cloud.\n */\nasync function connect(flags: Readonly<Record<string, unknown>>, command: string): Promise<Backend> {\n const target = await projectTarget(flags, { command });\n return {\n baseUrl: target.label,\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n let response: Response;\n try {\n response = await target.request(`/api/admin/storage${path}`, { method, ...(body === undefined ? {} : { json: body }) });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return (answer as { data: T }).data;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404 && error.code !== \"UNKNOWN_STORAGE_SOURCE\") {\n console.error(chalk.gray(\" This backend has no storage maintenance routes: they arrived in 0.25, and need storage configured.\"));\n }\n process.exit(1);\n}\n\n/** Bytes, as a person reads them. */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n const units = [\"KB\", \"MB\", \"GB\", \"TB\"];\n let value = bytes / 1024;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;\n}\n\n/**\n * The lines that describe an orphan scan. Exported so its tests can read them\n * without a server.\n */\nexport function describeOrphanReport(report: OrphanReport, olderThanHours: number): string[] {\n const lines: string[] = [];\n const bytes = report.orphans.reduce((sum, orphan) => sum + (orphan.size ?? 0), 0);\n lines.push(` ${report.objects} file(s) in source \"${report.storageId}\", ${report.scanned.length} table(s) read.`);\n if (report.orphans.length === 0) {\n lines.push(\" No file older than \" + `${olderThanHours}h is unused.`);\n } else {\n lines.push(` ${report.orphans.length} file(s) no row names, ${formatBytes(bytes)}:`);\n for (const orphan of report.orphans) {\n lines.push(` ${orphan.key}${orphan.size !== undefined ? ` ${formatBytes(orphan.size)}` : \"\"}${orphan.updated ? ` ${orphan.updated}` : \"\"}`);\n }\n }\n if (report.recent > 0) {\n const one = report.recent === 1;\n const more = report.orphans.length > 0 ? \"more \" : \"\";\n lines.push(` ${report.recent} ${more}unused ${one ? \"file is\" : \"files are\"} left out: ` +\n `${one ? \"it is\" : \"they are\"} newer than ${olderThanHours}h, or ${one ? \"its\" : \"their\"} age is unknown, ` +\n \"and an upload can be saved before the row that names it.\");\n }\n for (const entry of report.unscanned) {\n lines.push(` ⚠ ${entry.collection} could not be read (${entry.reason}): a file only it names is listed above.`);\n }\n return lines;\n}\n\nasync function confirm(question: string): Promise<boolean> {\n const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n return /^y(es)?$/i.test((await prompt.question(question)).trim());\n } finally {\n prompt.close();\n }\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\n/** Whether an error is a backend without the route asked for, as opposed to a source it does not serve. */\nconst isMissingRoute = (error: unknown) => error instanceof RebaseApiError && error.status === 404\n && error.code !== \"UNKNOWN_STORAGE_SOURCE\" && error.code !== \"STORAGE_SCAN_NOT_FOUND\";\n\n/** One line of a running scan's progress, rewritten in place on a terminal. */\nfunction progressLine(text: string, quiet: boolean): void {\n if (!quiet && process.stdout.isTTY) process.stdout.write(`\\r\\x1b[2K ${text}`);\n}\n\nfunction endProgressLine(quiet: boolean): void {\n if (!quiet && process.stdout.isTTY) process.stdout.write(\"\\n\");\n}\n\n/** Ask for a scan's record until `done` says so, printing its progress. */\nasync function pollScan(\n backend: Backend,\n id: string,\n sourceQuery: string,\n done: (state: OrphanScanState) => boolean,\n describe: (state: OrphanScanState) => string,\n quiet: boolean\n): Promise<OrphanScanState> {\n let noted = false;\n for (;;) {\n let state: OrphanScanState;\n try {\n state = await backend.request<OrphanScanState>(\"GET\", `/orphans/scans/${encodeURIComponent(id)}${sourceQuery}`);\n } catch (error: unknown) {\n endProgressLine(quiet);\n fail(\"Failed to read the scan's progress\", error, backend.baseUrl);\n }\n if (done(state)) {\n endProgressLine(quiet);\n return state;\n }\n progressLine(describe(state), quiet);\n const note = state.note ?? state.deletion?.note;\n if (note && !noted && !quiet) {\n noted = true;\n endProgressLine(quiet);\n console.log(chalk.yellow(` ${note}`));\n }\n await sleep(orphanScanPolling.intervalMs);\n }\n}\n\n/**\n * Scan for orphans: started on the backend and asked about until it is done,\n * so a scan longer than any request timeout still finishes. A backend from\n * before scans ran in the background is asked the old way, in one request.\n */\nasync function scanForOrphans(\n backend: Backend,\n query: URLSearchParams,\n sourceQuery: string,\n quiet: boolean\n): Promise<{ report: OrphanReport; scanId?: string }> {\n let started: OrphanScanState;\n try {\n started = await backend.request<OrphanScanState>(\"POST\", `/orphans/scans?${query}`);\n } catch (error: unknown) {\n if (!isMissingRoute(error)) fail(\"Failed to start a storage scan\", error, backend.baseUrl);\n try {\n return { report: await backend.request<OrphanReport>(\"GET\", `/orphans?${query}`) };\n } catch (legacyError: unknown) {\n fail(\"Failed to scan storage\", legacyError, backend.baseUrl);\n }\n }\n if (!quiet && started.runner === \"in-process\") {\n console.log(chalk.gray(\" This backend runs no job queue, so the scan runs inside the server process, in the background. A restart of that process stops it.\"));\n }\n const finished = await pollScan(\n backend,\n started.id,\n sourceQuery,\n state => state.status === \"completed\" || state.status === \"failed\",\n state => state.status === \"queued\"\n ? \"Waiting for the scan to start…\"\n : `Scanning \"${state.storageId}\": ${state.progress.filesScanned} file(s) listed, ${state.progress.rowsScanned} row(s) read, ` +\n `${state.progress.collectionsScanned}/${state.progress.collectionsTotal} table(s)` +\n (state.progress.unscanned.length > 0 ? `, ${state.progress.unscanned.length} unreadable` : \"\") + \"…\",\n quiet\n );\n if (finished.status === \"failed\" || !finished.result) {\n console.error(chalk.red(`✗ The scan failed: ${finished.error ?? \"no reason was recorded\"}`));\n process.exit(1);\n }\n return { report: { storageId: finished.storageId, ...finished.result }, scanId: finished.id };\n}\n\n/** Delete a completed scan's orphans, in the background, and wait for it. */\nasync function deleteFromScan(\n backend: Backend,\n scanId: string,\n sourceQuery: string,\n quiet: boolean\n): Promise<{ deleted: string[]; failed: { key: string; error: string }[]; kept: { key: string; reason: string }[]; error?: string }> {\n const deleteQuery = new URLSearchParams(sourceQuery.replace(/^\\?/, \"\"));\n deleteQuery.set(\"scan\", scanId);\n try {\n await backend.request(\"DELETE\", `/orphans?${deleteQuery}`);\n } catch (error: unknown) {\n fail(\"Failed to delete unused files\", error, backend.baseUrl);\n }\n const finished = await pollScan(\n backend,\n scanId,\n sourceQuery,\n state => state.deletion?.status === \"completed\" || state.deletion?.status === \"failed\",\n state => {\n const progress = state.deletion?.progress;\n if (!progress || state.deletion?.status === \"queued\") return \"Waiting for the delete to start…\";\n return progress.phase === \"deleting\"\n ? `Deleting: ${progress.deleted} of ${progress.candidates} file(s)…`\n : `Checking every row again before deleting: ${progress.rowsScanned} row(s) read, ` +\n `${progress.collectionsScanned}/${progress.collectionsTotal} table(s)…`;\n },\n quiet\n );\n const deletion = finished.deletion!;\n return {\n deleted: deletion.result?.deleted ?? [],\n failed: deletion.result?.failed ?? [],\n kept: deletion.result?.kept ?? [],\n ...(deletion.status === \"failed\" ? { error: deletion.error ?? \"no reason was recorded\" } : {})\n };\n}\n\nasync function orphans(rawArgs: string[]): Promise<void> {\n const { flags } = parseCommandArgs({ spec: ORPHANS_FLAGS, rawArgs, commandWords: 2, command: \"storage orphans\", maxPositionals: 0 });\n const olderThan = flags[\"--older-than\"] ?? 24;\n if (!Number.isFinite(olderThan) || olderThan < 0) {\n throw new UsageError(\"--older-than takes a number of hours, 0 or more.\");\n }\n const query = new URLSearchParams({ olderThanHours: String(olderThan) });\n if (flags[\"--source\"]) query.set(\"storageId\", flags[\"--source\"]);\n const sourceQuery = flags[\"--source\"] ? `?${new URLSearchParams({ storageId: flags[\"--source\"] })}` : \"\";\n const quiet = flags[\"--json\"] === true;\n const backend = await connect(flags, \"storage orphans\");\n\n const { report, scanId } = await scanForOrphans(backend, query, sourceQuery, quiet);\n\n if (!flags[\"--delete\"]) {\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ ...report, ...(scanId ? { scanId } : {}) }, null, 2));\n return;\n }\n console.log(\"\");\n for (const line of describeOrphanReport(report, olderThan)) console.log(line);\n if (report.orphans.length > 0) {\n console.log(\"\");\n console.log(chalk.gray(\" Nothing was deleted. Run again with --delete to delete them.\"));\n }\n console.log(\"\");\n return;\n }\n\n if (!flags[\"--json\"]) {\n console.log(\"\");\n for (const line of describeOrphanReport(report, olderThan)) console.log(line);\n console.log(\"\");\n }\n if (report.orphans.length === 0) return;\n if (report.unscanned.length > 0) {\n console.error(chalk.red(\"✗ Not deleting: some tables could not be read, so a file they name would look unused.\"));\n process.exit(1);\n }\n if (!flags[\"--yes\"]) {\n if (!process.stdin.isTTY) {\n throw new UsageError(\"--delete deletes files for good; pass --yes to confirm when there is no terminal to ask.\");\n }\n if (!await confirm(` Delete these ${report.orphans.length} file(s) for good? [y/N] `)) {\n console.log(chalk.gray(\" Nothing was deleted.\"));\n return;\n }\n }\n\n let result: { deleted: string[]; failed: { key: string; error: string }[]; kept?: { key: string; reason: string }[]; error?: string };\n if (scanId) {\n // The server reads every row again against these files, and asks for\n // each file again right before deleting it: one a row has named since\n // the list was printed, or that was uploaded again, is kept.\n result = await deleteFromScan(backend, scanId, sourceQuery, quiet);\n } else {\n try {\n // A backend from before background scans finds them again, inside the request.\n result = await backend.request(\"DELETE\", `/orphans?${query}`);\n } catch (error: unknown) {\n fail(\"Failed to delete unused files\", error, backend.baseUrl);\n }\n }\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ storageId: report.storageId, ...result, recent: report.recent }, null, 2));\n } else {\n if (result.error) console.error(chalk.red(` ✗ ${result.error}`));\n console.log(chalk.green(` ✓ Deleted ${result.deleted.length} file(s).`));\n for (const kept of result.kept ?? []) console.log(chalk.yellow(` Kept ${kept.key}: ${kept.reason}`));\n for (const failure of result.failed) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error}`));\n console.log(\"\");\n }\n if (result.failed.length > 0 || result.error) process.exitCode = 1;\n}\n\nasync function move(rawArgs: string[]): Promise<void> {\n const { flags } = parseCommandArgs({ spec: MOVE_FLAGS, rawArgs, commandWords: 2, command: \"storage move\", maxPositionals: 0 });\n const from = flags[\"--from\"];\n const to = flags[\"--to\"];\n if (!from && !to) {\n throw new UsageError(\"Name the sources: --from <source> --to <source>. The default source is \\\"(default)\\\", and either may be left out for it.\");\n }\n if (flags[\"--delete-source\"]) {\n // The originals go once each copy is verified, and nothing brings them back.\n await confirmDestructive({\n yes: flags[\"--yes\"] === true,\n prompt: `Copy ${flags[\"--prefix\"] ? `${flags[\"--prefix\"]} ` : \"every file \"}from ${from ?? \"(default)\"} to ${to ?? \"(default)\"}, deleting each original once its copy is in place?`\n });\n }\n const backend = await connect(flags, \"storage move\");\n const counts = { copied: 0, exists: 0, failed: 0, deleted: 0 };\n const failures: MovedObject[] = [];\n let cursor: string | undefined;\n do {\n let page: { moved: MovedObject[]; cursor?: string };\n try {\n page = await backend.request(\"POST\", \"/move\", {\n from,\n to,\n prefix: flags[\"--prefix\"],\n cursor,\n deleteSource: flags[\"--delete-source\"] === true\n });\n } catch (error: unknown) {\n fail(\"Failed to move files\", error, backend.baseUrl);\n }\n for (const object of page.moved) {\n counts[object.outcome]++;\n if (object.deleted) counts.deleted++;\n if (object.outcome === \"failed\") failures.push(object);\n }\n if (!flags[\"--json\"] && process.stdout.isTTY) {\n process.stdout.write(`\\r ${counts.copied} copied, ${counts.exists} already there, ${counts.failed} failed…`);\n }\n cursor = page.cursor;\n } while (cursor);\n\n // The source listed again, by a walk of its own: a move reports what its\n // walk saw, and a walk that skipped files once reported success over the\n // half it moved.\n const verified = await listLeftBehind(backend, {\n from,\n to,\n prefix: flags[\"--prefix\"],\n deleteSource: flags[\"--delete-source\"] === true\n }, flags[\"--json\"] === true);\n const reported = new Set(failures.map(failure => failure.key));\n const leftBehind = verified?.filter(entry => !reported.has(entry.key)) ?? [];\n\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ ...counts, failures, verified: verified !== undefined, notMoved: verified ?? [] }, null, 2));\n } else {\n if (process.stdout.isTTY) process.stdout.write(\"\\n\");\n console.log(chalk.green(` ✓ ${counts.copied} copied, ${counts.exists} already there` +\n `${flags[\"--delete-source\"] ? `, ${counts.deleted} deleted from the source` : \"\"}.`));\n for (const failure of failures) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error ?? \"failed\"}`));\n if (verified === undefined) {\n console.log(chalk.gray(\" This backend cannot list the source again (it needs a backend newer than 0.25.1), so the CLI did not check for files the move left behind.\"));\n } else if (leftBehind.length > 0) {\n console.error(chalk.red(` ✗ Listed again, the source holds ${leftBehind.length} more file(s) the move did not report: ${leftBehind.length} file(s) were not moved.`));\n for (const entry of leftBehind) console.error(chalk.red(` ${entry.key}: ${entry.reason}`));\n console.error(chalk.gray(\" Run the same move again to pick them up.\"));\n }\n if (counts.copied + counts.exists > 0 && !flags[\"--delete-source\"]) {\n console.log(chalk.gray(\" The source keeps its copies. Point the property at the new source, then run again with --delete-source.\"));\n }\n }\n if (failures.length > 0 || leftBehind.length > 0) process.exitCode = 1;\n}\n\n/**\n * Every file under the moved folder the move did not move, read by the\n * backend's `/move/verify` — or `undefined` from a backend without it.\n */\nasync function listLeftBehind(\n backend: Backend,\n request: { from?: string; to?: string; prefix?: string; deleteSource: boolean },\n quiet: boolean\n): Promise<{ key: string; reason: string }[] | undefined> {\n const notMoved: { key: string; reason: string }[] = [];\n let cursor: string | undefined;\n let checked = 0;\n do {\n let page: { checked: number; notMoved: { key: string; reason: string }[]; cursor?: string };\n try {\n page = await backend.request(\"POST\", \"/move/verify\", { ...request, ...(cursor ? { cursor } : {}), limit: 500 });\n } catch (error: unknown) {\n if (error instanceof RebaseApiError && error.status === 404 && error.code !== \"UNKNOWN_STORAGE_SOURCE\") return undefined;\n fail(\"Failed to list the source again after the move\", error, backend.baseUrl);\n }\n checked += page.checked;\n notMoved.push(...page.notMoved);\n if (!quiet && process.stdout.isTTY) {\n process.stdout.write(`\\r Checking the source again: ${checked} file(s) listed…`);\n }\n cursor = page.cursor;\n } while (cursor);\n return notMoved;\n}\n\nexport async function storageCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printStorageHelp();\n return;\n }\n switch (subcommand) {\n case \"orphans\":\n await orphans(rawArgs);\n break;\n case \"move\":\n await move(rawArgs);\n break;\n case \"ls\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageLs(rawArgs);\n break;\n case \"cp\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageCp(rawArgs);\n break;\n case \"rm\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageRm(rawArgs);\n break;\n case \"url\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageUrl(rawArgs);\n break;\n case \"stat\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageStat(rawArgs);\n break;\n default:\n unknownCommand(subcommand, STORAGE_SUBCOMMANDS, \"storage\");\n }\n}\n\nfunction printStorageHelp(): void {\n console.log(`\n${chalk.bold(\"rebase storage\")} — Stored files, through the running backend\n\n${chalk.green.bold(\"Usage\")}\n rebase storage ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"ls\")} ${chalk.gray(\"[:prefix]\")} List stored files and folders\n ${chalk.blue.bold(\"cp\")} ${chalk.gray(\"<from> <to>\")} Upload or download: the stored side starts with a colon ${chalk.gray(\"(:key, or <source>:key)\")}\n ${chalk.blue.bold(\"rm\")} ${chalk.gray(\"<:key>\")} Delete a stored file ${chalk.gray(\"(asks first)\")}\n ${chalk.blue.bold(\"url\")} ${chalk.gray(\"<:key>\")} A signed download link: whoever holds it reads the file until it expires\n ${chalk.blue.bold(\"stat\")} ${chalk.gray(\"<:key>\")} A stored file's metadata\n ${chalk.blue.bold(\"orphans\")} List the stored files no row names\n ${chalk.blue.bold(\"move\")} Copy a folder of files to another storage source, same keys\n\n${chalk.green.bold(\"ls, cp Options\")}\n ${chalk.blue(\"--limit, -n\")} At most this many entries ${chalk.gray(\"(ls)\")}\n ${chalk.blue(\"--page-token\")} Continue a listing ${chalk.gray(\"(ls)\")}\n ${chalk.blue(\"--content-type\")} The uploaded file's type ${chalk.gray(\"(cp; else inferred by the server)\")}\n ${chalk.blue(\"--public\")} Upload under the public prefix: a permanent, token-less URL ${chalk.gray(\"(cp)\")}\n ${chalk.blue(\"--force\")} Overwrite a local file on download ${chalk.gray(\"(cp)\")}\n\n${chalk.green.bold(\"orphans Options\")}\n ${chalk.blue(\"--source\")} Storage source key ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--older-than\")} Hours a file must be old to count ${chalk.gray(\"(default: 24)\")}\n ${chalk.blue(\"--delete\")} Delete them, after asking\n ${chalk.blue(\"--yes, -y\")} Do not ask ${chalk.gray(\"(required with --delete when there is no terminal)\")}\n ${chalk.blue(\"--json\")} Print the report as JSON\n\n${chalk.green.bold(\"move Options\")}\n ${chalk.blue(\"--from\")} Source to copy from ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--to\")} Source to copy to ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--prefix\")} Folder to copy ${chalk.gray(\"(default: everything)\")}\n ${chalk.blue(\"--delete-source\")} Delete each file from the source once the target holds it ${chalk.gray(\"(asks first)\")}\n ${chalk.blue(\"--json\")} Print the counts as JSON\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\n ${chalk.blue(\"--session\")} Send the session \\`rebase auth login\\` stored\n ${chalk.blue(\"--anon\")} Send no credential\n\n${chalk.green.bold(\"Notes\")}\n A file is unused when no string in any row of any table names it —\n a key, a URL, a ${chalk.blue(\"rebase-storage:\")} reference in text — whatever column\n or source holds it. Files newer than ${chalk.blue(\"--older-than\")} are left out: the admin\n panel uploads a file before the row that names it is saved. Files named only\n by tables backend/schema does not declare are not seen: check before deleting.\n\n The scan runs on the backend in the background — a ${chalk.blue(\"storage.orphans\")} job\n on the job queue, or inside the server process when there is none — and the\n CLI shows its progress until it is done. ${chalk.blue(\"--delete\")} deletes from that scan\n only; the backend reads every row again and asks for each file again first.\n\n They send ${chalk.blue(\"REBASE_SERVICE_KEY\")} from .env unless a target option says otherwise, and need the backend running.\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA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AK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,SAAS,EAAE;IACtB,MAAM,KAAK,gBAAgB,EAAE,+BAA+B,MAAM,KAAK,2CAA6C,EAAE;IACtH,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,WAAW,EAAE;IACxB,MAAM,KAAK,QAAQ,EAAE;;EAEvB,MAAM,MAAM,KAAK,OAAO,EAAE;;oBAER,MAAM,KAAK,iBAAiB,EAAE;yCACT,MAAM,KAAK,cAAc,EAAE;;;;uDAIb,MAAM,KAAK,iBAAiB,EAAE;;6CAExC,MAAM,KAAK,UAAU,EAAE;;;cAGtD,MAAM,KAAK,oBAAoB,EAAE;CAC9C;AACD"}
|
|
1
|
+
{"version":3,"file":"storage-Dqf5tyhs.js","names":[],"sources":["../src/commands/storage.ts"],"sourcesContent":["/**\n * CLI command: rebase storage <action>\n *\n * Whole-store maintenance through the running backend's `/api/admin/storage`,\n * authenticated with the service key from `.env`.\n *\n * Subcommands:\n * orphans — Stored files no row names; `--delete` deletes them\n * move — Copy a folder of files to another storage source, same keys\n */\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport { PROJECT_TARGET_FLAGS } from \"../utils/project-target\";\nimport { projectTarget, startProjectCommand } from \"../utils/project-command\";\nimport { confirmDestructive } from \"./cloud/context\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { describeFailure } from \"./api-keys\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const STORAGE_SUBCOMMANDS = [\"orphans\", \"move\", \"ls\", \"cp\", \"rm\", \"url\", \"stat\"] as const;\n\n/** The flags `rebase storage orphans` takes. */\nexport const ORPHANS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--source\": String,\n \"--older-than\": Number,\n \"--delete\": Boolean\n} as const;\n\n/** The flags `rebase storage move` takes. */\nexport const MOVE_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--from\": String,\n \"--to\": String,\n \"--prefix\": String,\n \"--delete-source\": Boolean\n} as const;\n\n/** One stored object, as the backend lists it. */\ninterface StoredObjectEntry {\n key: string;\n size?: number;\n updated?: string;\n}\n\n/** What `GET /admin/storage/orphans` answers. */\nexport interface OrphanReport {\n storageId: string;\n objects: number;\n orphans: StoredObjectEntry[];\n recent: number;\n scanned: string[];\n unscanned: { collection: string; reason: string }[];\n}\n\n/** An orphan scan's record, as `GET /admin/storage/orphans/scans/:id` answers it. */\ninterface OrphanScanState {\n id: string;\n storageId: string;\n runner: \"worker\" | \"in-process\";\n status: \"queued\" | \"running\" | \"completed\" | \"failed\";\n progress: {\n phase: string;\n filesScanned: number;\n rowsScanned: number;\n historyEntriesScanned: number;\n collectionsScanned: number;\n collectionsTotal: number;\n unscanned: { collection: string; reason: string }[];\n };\n result?: Omit<OrphanReport, \"storageId\">;\n error?: string;\n note?: string;\n deletion?: {\n status: \"queued\" | \"running\" | \"completed\" | \"failed\";\n progress: OrphanScanState[\"progress\"] & { candidates: number; deleted: number };\n result?: { deleted: string[]; kept: { key: string; reason: string }[]; failed: { key: string; error: string }[] };\n error?: string;\n note?: string;\n };\n}\n\n/** How often a running scan is asked about. A setting so the tests need not wait. */\nexport const orphanScanPolling = { intervalMs: 1_000 };\n\ninterface MovedObject {\n key: string;\n outcome: \"copied\" | \"exists\" | \"failed\";\n deleted?: boolean;\n error?: string;\n}\n\ninterface Backend {\n baseUrl: string;\n request<T>(method: string, path: string, body?: unknown): Promise<T>;\n}\n\n/**\n * The project's backend, holding the service key — the `admin` role, every\n * scope — or whatever credential the target flags name, resolved the way\n * every project command resolves it (`utils/project-target.ts`): the local\n * `rebase dev`, `--url`, `REBASE_BASE_URL`, or `--project` for Rebase Cloud.\n */\nasync function connect(flags: Readonly<Record<string, unknown>>, command: string): Promise<Backend> {\n const target = await projectTarget(flags, { command });\n return {\n baseUrl: target.label,\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n let response: Response;\n try {\n response = await target.request(`/api/admin/storage${path}`, { method, ...(body === undefined ? {} : { json: body }) });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return (answer as { data: T }).data;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404 && error.code !== \"UNKNOWN_STORAGE_SOURCE\") {\n console.error(chalk.gray(\" This backend has no storage maintenance routes: they arrived in 0.25, and need storage configured.\"));\n }\n process.exit(1);\n}\n\n/** Bytes, as a person reads them. */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n const units = [\"KB\", \"MB\", \"GB\", \"TB\"];\n let value = bytes / 1024;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;\n}\n\n/**\n * The lines that describe an orphan scan. Exported so its tests can read them\n * without a server.\n */\nexport function describeOrphanReport(report: OrphanReport, olderThanHours: number): string[] {\n const lines: string[] = [];\n const bytes = report.orphans.reduce((sum, orphan) => sum + (orphan.size ?? 0), 0);\n lines.push(` ${report.objects} file(s) in source \"${report.storageId}\", ${report.scanned.length} table(s) read.`);\n if (report.orphans.length === 0) {\n lines.push(\" No file older than \" + `${olderThanHours}h is unused.`);\n } else {\n lines.push(` ${report.orphans.length} file(s) no row names, ${formatBytes(bytes)}:`);\n for (const orphan of report.orphans) {\n lines.push(` ${orphan.key}${orphan.size !== undefined ? ` ${formatBytes(orphan.size)}` : \"\"}${orphan.updated ? ` ${orphan.updated}` : \"\"}`);\n }\n }\n if (report.recent > 0) {\n const one = report.recent === 1;\n const more = report.orphans.length > 0 ? \"more \" : \"\";\n lines.push(` ${report.recent} ${more}unused ${one ? \"file is\" : \"files are\"} left out: ` +\n `${one ? \"it is\" : \"they are\"} newer than ${olderThanHours}h, or ${one ? \"its\" : \"their\"} age is unknown, ` +\n \"and an upload can be saved before the row that names it.\");\n }\n for (const entry of report.unscanned) {\n lines.push(` ⚠ ${entry.collection} could not be read (${entry.reason}): a file only it names is listed above.`);\n }\n return lines;\n}\n\nasync function confirm(question: string): Promise<boolean> {\n const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n return /^y(es)?$/i.test((await prompt.question(question)).trim());\n } finally {\n prompt.close();\n }\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\n/** Whether an error is a backend without the route asked for, as opposed to a source it does not serve. */\nconst isMissingRoute = (error: unknown) => error instanceof RebaseApiError && error.status === 404\n && error.code !== \"UNKNOWN_STORAGE_SOURCE\" && error.code !== \"STORAGE_SCAN_NOT_FOUND\";\n\n/** One line of a running scan's progress, rewritten in place on a terminal. */\nfunction progressLine(text: string, quiet: boolean): void {\n if (!quiet && process.stdout.isTTY) process.stdout.write(`\\r\\x1b[2K ${text}`);\n}\n\nfunction endProgressLine(quiet: boolean): void {\n if (!quiet && process.stdout.isTTY) process.stdout.write(\"\\n\");\n}\n\n/** Ask for a scan's record until `done` says so, printing its progress. */\nasync function pollScan(\n backend: Backend,\n id: string,\n sourceQuery: string,\n done: (state: OrphanScanState) => boolean,\n describe: (state: OrphanScanState) => string,\n quiet: boolean\n): Promise<OrphanScanState> {\n let noted = false;\n for (;;) {\n let state: OrphanScanState;\n try {\n state = await backend.request<OrphanScanState>(\"GET\", `/orphans/scans/${encodeURIComponent(id)}${sourceQuery}`);\n } catch (error: unknown) {\n endProgressLine(quiet);\n fail(\"Failed to read the scan's progress\", error, backend.baseUrl);\n }\n if (done(state)) {\n endProgressLine(quiet);\n return state;\n }\n progressLine(describe(state), quiet);\n const note = state.note ?? state.deletion?.note;\n if (note && !noted && !quiet) {\n noted = true;\n endProgressLine(quiet);\n console.log(chalk.yellow(` ${note}`));\n }\n await sleep(orphanScanPolling.intervalMs);\n }\n}\n\n/**\n * Scan for orphans: started on the backend and asked about until it is done,\n * so a scan longer than any request timeout still finishes. A backend from\n * before scans ran in the background is asked the old way, in one request.\n */\nasync function scanForOrphans(\n backend: Backend,\n query: URLSearchParams,\n sourceQuery: string,\n quiet: boolean\n): Promise<{ report: OrphanReport; scanId?: string }> {\n let started: OrphanScanState;\n try {\n started = await backend.request<OrphanScanState>(\"POST\", `/orphans/scans?${query}`);\n } catch (error: unknown) {\n if (!isMissingRoute(error)) fail(\"Failed to start a storage scan\", error, backend.baseUrl);\n try {\n return { report: await backend.request<OrphanReport>(\"GET\", `/orphans?${query}`) };\n } catch (legacyError: unknown) {\n fail(\"Failed to scan storage\", legacyError, backend.baseUrl);\n }\n }\n if (!quiet && started.runner === \"in-process\") {\n console.log(chalk.gray(\" This backend runs no job queue, so the scan runs inside the server process, in the background. A restart of that process stops it.\"));\n }\n const finished = await pollScan(\n backend,\n started.id,\n sourceQuery,\n state => state.status === \"completed\" || state.status === \"failed\",\n state => state.status === \"queued\"\n ? \"Waiting for the scan to start…\"\n : `Scanning \"${state.storageId}\": ${state.progress.filesScanned} file(s) listed, ${state.progress.rowsScanned} row(s) read, ` +\n `${state.progress.collectionsScanned}/${state.progress.collectionsTotal} table(s)` +\n (state.progress.unscanned.length > 0 ? `, ${state.progress.unscanned.length} unreadable` : \"\") + \"…\",\n quiet\n );\n if (finished.status === \"failed\" || !finished.result) {\n console.error(chalk.red(`✗ The scan failed: ${finished.error ?? \"no reason was recorded\"}`));\n process.exit(1);\n }\n return { report: { storageId: finished.storageId, ...finished.result }, scanId: finished.id };\n}\n\n/** Delete a completed scan's orphans, in the background, and wait for it. */\nasync function deleteFromScan(\n backend: Backend,\n scanId: string,\n sourceQuery: string,\n quiet: boolean\n): Promise<{ deleted: string[]; failed: { key: string; error: string }[]; kept: { key: string; reason: string }[]; error?: string }> {\n const deleteQuery = new URLSearchParams(sourceQuery.replace(/^\\?/, \"\"));\n deleteQuery.set(\"scan\", scanId);\n try {\n await backend.request(\"DELETE\", `/orphans?${deleteQuery}`);\n } catch (error: unknown) {\n fail(\"Failed to delete unused files\", error, backend.baseUrl);\n }\n const finished = await pollScan(\n backend,\n scanId,\n sourceQuery,\n state => state.deletion?.status === \"completed\" || state.deletion?.status === \"failed\",\n state => {\n const progress = state.deletion?.progress;\n if (!progress || state.deletion?.status === \"queued\") return \"Waiting for the delete to start…\";\n return progress.phase === \"deleting\"\n ? `Deleting: ${progress.deleted} of ${progress.candidates} file(s)…`\n : `Checking every row again before deleting: ${progress.rowsScanned} row(s) read, ` +\n `${progress.collectionsScanned}/${progress.collectionsTotal} table(s)…`;\n },\n quiet\n );\n const deletion = finished.deletion!;\n return {\n deleted: deletion.result?.deleted ?? [],\n failed: deletion.result?.failed ?? [],\n kept: deletion.result?.kept ?? [],\n ...(deletion.status === \"failed\" ? { error: deletion.error ?? \"no reason was recorded\" } : {})\n };\n}\n\nasync function orphans(rawArgs: string[]): Promise<void> {\n const { flags } = parseCommandArgs({ spec: ORPHANS_FLAGS, rawArgs, commandWords: 2, command: \"storage orphans\", maxPositionals: 0 });\n const olderThan = flags[\"--older-than\"] ?? 24;\n if (!Number.isFinite(olderThan) || olderThan < 0) {\n throw new UsageError(\"--older-than takes a number of hours, 0 or more.\");\n }\n const query = new URLSearchParams({ olderThanHours: String(olderThan) });\n if (flags[\"--source\"]) query.set(\"storageId\", flags[\"--source\"]);\n const sourceQuery = flags[\"--source\"] ? `?${new URLSearchParams({ storageId: flags[\"--source\"] })}` : \"\";\n const quiet = flags[\"--json\"] === true;\n const backend = await connect(flags, \"storage orphans\");\n\n const { report, scanId } = await scanForOrphans(backend, query, sourceQuery, quiet);\n\n if (!flags[\"--delete\"]) {\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ ...report, ...(scanId ? { scanId } : {}) }, null, 2));\n return;\n }\n console.log(\"\");\n for (const line of describeOrphanReport(report, olderThan)) console.log(line);\n if (report.orphans.length > 0) {\n console.log(\"\");\n console.log(chalk.gray(\" Nothing was deleted. Run again with --delete to delete them.\"));\n }\n console.log(\"\");\n return;\n }\n\n if (!flags[\"--json\"]) {\n console.log(\"\");\n for (const line of describeOrphanReport(report, olderThan)) console.log(line);\n console.log(\"\");\n }\n if (report.orphans.length === 0) return;\n if (report.unscanned.length > 0) {\n console.error(chalk.red(\"✗ Not deleting: some tables could not be read, so a file they name would look unused.\"));\n process.exit(1);\n }\n if (!flags[\"--yes\"]) {\n if (!process.stdin.isTTY) {\n throw new UsageError(\"--delete deletes files for good; pass --yes to confirm when there is no terminal to ask.\");\n }\n if (!await confirm(` Delete these ${report.orphans.length} file(s) for good? [y/N] `)) {\n console.log(chalk.gray(\" Nothing was deleted.\"));\n return;\n }\n }\n\n let result: { deleted: string[]; failed: { key: string; error: string }[]; kept?: { key: string; reason: string }[]; error?: string };\n if (scanId) {\n // The server reads every row again against these files, and asks for\n // each file again right before deleting it: one a row has named since\n // the list was printed, or that was uploaded again, is kept.\n result = await deleteFromScan(backend, scanId, sourceQuery, quiet);\n } else {\n try {\n // A backend from before background scans finds them again, inside the request.\n result = await backend.request(\"DELETE\", `/orphans?${query}`);\n } catch (error: unknown) {\n fail(\"Failed to delete unused files\", error, backend.baseUrl);\n }\n }\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ storageId: report.storageId, ...result, recent: report.recent }, null, 2));\n } else {\n if (result.error) console.error(chalk.red(` ✗ ${result.error}`));\n console.log(chalk.green(` ✓ Deleted ${result.deleted.length} file(s).`));\n for (const kept of result.kept ?? []) console.log(chalk.yellow(` Kept ${kept.key}: ${kept.reason}`));\n for (const failure of result.failed) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error}`));\n console.log(\"\");\n }\n if (result.failed.length > 0 || result.error) process.exitCode = 1;\n}\n\nasync function move(rawArgs: string[]): Promise<void> {\n const { flags } = parseCommandArgs({ spec: MOVE_FLAGS, rawArgs, commandWords: 2, command: \"storage move\", maxPositionals: 0 });\n const from = flags[\"--from\"];\n const to = flags[\"--to\"];\n if (!from && !to) {\n throw new UsageError(\"Name the sources: --from <source> --to <source>. The default source is \\\"(default)\\\", and either may be left out for it.\");\n }\n if (flags[\"--delete-source\"]) {\n // The originals go once each copy is verified, and nothing brings them back.\n await confirmDestructive({\n yes: flags[\"--yes\"] === true,\n prompt: `Copy ${flags[\"--prefix\"] ? `${flags[\"--prefix\"]} ` : \"every file \"}from ${from ?? \"(default)\"} to ${to ?? \"(default)\"}, deleting each original once its copy is in place?`\n });\n }\n const backend = await connect(flags, \"storage move\");\n const counts = { copied: 0, exists: 0, failed: 0, deleted: 0 };\n const failures: MovedObject[] = [];\n let cursor: string | undefined;\n do {\n let page: { moved: MovedObject[]; cursor?: string };\n try {\n page = await backend.request(\"POST\", \"/move\", {\n from,\n to,\n prefix: flags[\"--prefix\"],\n cursor,\n deleteSource: flags[\"--delete-source\"] === true\n });\n } catch (error: unknown) {\n fail(\"Failed to move files\", error, backend.baseUrl);\n }\n for (const object of page.moved) {\n counts[object.outcome]++;\n if (object.deleted) counts.deleted++;\n if (object.outcome === \"failed\") failures.push(object);\n }\n if (!flags[\"--json\"] && process.stdout.isTTY) {\n process.stdout.write(`\\r ${counts.copied} copied, ${counts.exists} already there, ${counts.failed} failed…`);\n }\n cursor = page.cursor;\n } while (cursor);\n\n // The source listed again, by a walk of its own: a move reports what its\n // walk saw, and a walk that skipped files once reported success over the\n // half it moved.\n const verified = await listLeftBehind(backend, {\n from,\n to,\n prefix: flags[\"--prefix\"],\n deleteSource: flags[\"--delete-source\"] === true\n }, flags[\"--json\"] === true);\n const reported = new Set(failures.map(failure => failure.key));\n const leftBehind = verified?.filter(entry => !reported.has(entry.key)) ?? [];\n\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ ...counts, failures, verified: verified !== undefined, notMoved: verified ?? [] }, null, 2));\n } else {\n if (process.stdout.isTTY) process.stdout.write(\"\\n\");\n console.log(chalk.green(` ✓ ${counts.copied} copied, ${counts.exists} already there` +\n `${flags[\"--delete-source\"] ? `, ${counts.deleted} deleted from the source` : \"\"}.`));\n for (const failure of failures) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error ?? \"failed\"}`));\n if (verified === undefined) {\n console.log(chalk.gray(\" This backend cannot list the source again (it needs a backend newer than 0.25.1), so the CLI did not check for files the move left behind.\"));\n } else if (leftBehind.length > 0) {\n console.error(chalk.red(` ✗ Listed again, the source holds ${leftBehind.length} more file(s) the move did not report: ${leftBehind.length} file(s) were not moved.`));\n for (const entry of leftBehind) console.error(chalk.red(` ${entry.key}: ${entry.reason}`));\n console.error(chalk.gray(\" Run the same move again to pick them up.\"));\n }\n if (counts.copied + counts.exists > 0 && !flags[\"--delete-source\"]) {\n console.log(chalk.gray(\" The source keeps its copies. Point the property at the new source, then run again with --delete-source.\"));\n }\n }\n if (failures.length > 0 || leftBehind.length > 0) process.exitCode = 1;\n}\n\n/**\n * Every file under the moved folder the move did not move, read by the\n * backend's `/move/verify` — or `undefined` from a backend without it.\n */\nasync function listLeftBehind(\n backend: Backend,\n request: { from?: string; to?: string; prefix?: string; deleteSource: boolean },\n quiet: boolean\n): Promise<{ key: string; reason: string }[] | undefined> {\n const notMoved: { key: string; reason: string }[] = [];\n let cursor: string | undefined;\n let checked = 0;\n do {\n let page: { checked: number; notMoved: { key: string; reason: string }[]; cursor?: string };\n try {\n page = await backend.request(\"POST\", \"/move/verify\", { ...request, ...(cursor ? { cursor } : {}), limit: 500 });\n } catch (error: unknown) {\n if (error instanceof RebaseApiError && error.status === 404 && error.code !== \"UNKNOWN_STORAGE_SOURCE\") return undefined;\n fail(\"Failed to list the source again after the move\", error, backend.baseUrl);\n }\n checked += page.checked;\n notMoved.push(...page.notMoved);\n if (!quiet && process.stdout.isTTY) {\n process.stdout.write(`\\r Checking the source again: ${checked} file(s) listed…`);\n }\n cursor = page.cursor;\n } while (cursor);\n return notMoved;\n}\n\nexport async function storageCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printStorageHelp();\n return;\n }\n switch (subcommand) {\n case \"orphans\":\n await orphans(rawArgs);\n break;\n case \"move\":\n await move(rawArgs);\n break;\n case \"ls\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageLs(rawArgs);\n break;\n case \"cp\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageCp(rawArgs);\n break;\n case \"rm\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageRm(rawArgs);\n break;\n case \"url\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageUrl(rawArgs);\n break;\n case \"stat\":\n startProjectCommand(rawArgs);\n await (await import(\"./storage-objects\")).storageStat(rawArgs);\n break;\n default:\n unknownCommand(subcommand, STORAGE_SUBCOMMANDS, \"storage\");\n }\n}\n\nfunction printStorageHelp(): void {\n console.log(`\n${chalk.bold(\"rebase storage\")} — Stored files, through the running backend\n\n${chalk.green.bold(\"Usage\")}\n rebase storage ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"ls\")} ${chalk.gray(\"[:prefix]\")} List stored files and folders\n ${chalk.blue.bold(\"cp\")} ${chalk.gray(\"<from> <to>\")} Upload or download: the stored side starts with a colon ${chalk.gray(\"(:key, or <source>:key)\")}\n ${chalk.blue.bold(\"rm\")} ${chalk.gray(\"<:key>\")} Delete a stored file ${chalk.gray(\"(asks first)\")}\n ${chalk.blue.bold(\"url\")} ${chalk.gray(\"<:key>\")} A signed download link: whoever holds it reads the file until it expires\n ${chalk.blue.bold(\"stat\")} ${chalk.gray(\"<:key>\")} A stored file's metadata\n ${chalk.blue.bold(\"orphans\")} List the stored files no row names\n ${chalk.blue.bold(\"move\")} Copy a folder of files to another storage source, same keys\n\n${chalk.green.bold(\"ls, cp Options\")}\n ${chalk.blue(\"--limit, -n\")} At most this many entries ${chalk.gray(\"(ls)\")}\n ${chalk.blue(\"--page-token\")} Continue a listing ${chalk.gray(\"(ls)\")}\n ${chalk.blue(\"--content-type\")} The uploaded file's type ${chalk.gray(\"(cp; else inferred by the server)\")}\n ${chalk.blue(\"--public\")} Upload under the public prefix: a permanent, token-less URL ${chalk.gray(\"(cp)\")}\n ${chalk.blue(\"--force\")} Overwrite a local file on download ${chalk.gray(\"(cp)\")}\n\n${chalk.green.bold(\"orphans Options\")}\n ${chalk.blue(\"--source\")} Storage source key ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--older-than\")} Hours a file must be old to count ${chalk.gray(\"(default: 24)\")}\n ${chalk.blue(\"--delete\")} Delete them, after asking\n ${chalk.blue(\"--yes, -y\")} Do not ask ${chalk.gray(\"(required with --delete when there is no terminal)\")}\n ${chalk.blue(\"--json\")} Print the report as JSON\n\n${chalk.green.bold(\"move Options\")}\n ${chalk.blue(\"--from\")} Source to copy from ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--to\")} Source to copy to ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--prefix\")} Folder to copy ${chalk.gray(\"(default: everything)\")}\n ${chalk.blue(\"--delete-source\")} Delete each file from the source once the target holds it ${chalk.gray(\"(asks first)\")}\n ${chalk.blue(\"--json\")} Print the counts as JSON\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\n ${chalk.blue(\"--session\")} Send the session \\`rebase auth login\\` stored\n ${chalk.blue(\"--anon\")} Send no credential\n\n${chalk.green.bold(\"Notes\")}\n A file is unused when no string in any row of any table names it —\n a key, a URL, a ${chalk.blue(\"rebase-storage:\")} reference in text — whatever column\n or source holds it. Files newer than ${chalk.blue(\"--older-than\")} are left out: the admin\n panel uploads a file before the row that names it is saved. Files named only\n by tables backend/schema does not declare are not seen: check before deleting.\n\n The scan runs on the backend in the background — a ${chalk.blue(\"storage.orphans\")} job\n on the job queue, or inside the server process when there is none — and the\n CLI shows its progress until it is done. ${chalk.blue(\"--delete\")} deletes from that scan\n only; the backend reads every row again and asks for each file again first.\n\n They send ${chalk.blue(\"REBASE_SERVICE_KEY\")} from .env unless a target option says otherwise, and need the backend running.\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,IAAa,sBAAsB;CAAC;CAAW;CAAQ;CAAM;CAAM;CAAM;CAAO;AAAM;;AAGtF,IAAa,gBAAgB;CACzB,GAAG;CACH,YAAY;CACZ,gBAAgB;CAChB,YAAY;AAChB;;AAGA,IAAa,aAAa;CACtB,GAAG;CACH,UAAU;CACV,QAAQ;CACR,YAAY;CACZ,mBAAmB;AACvB;;AA+CA,IAAa,oBAAoB,EAAE,YAAY,IAAM;;;;;;;AAoBrD,eAAe,QAAQ,OAA0C,SAAmC;CAChG,MAAM,SAAS,MAAM,cAAc,OAAO,EAAE,QAAQ,CAAC;CACrD,OAAO;EACH,SAAS,OAAO;EAChB,MAAM,QAAW,QAAgB,MAAc,MAA4B;GACvE,IAAI;GACJ,IAAI;IACA,WAAW,MAAM,OAAO,QAAQ,qBAAqB,QAAQ;KAAE;KAAQ,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK;IAAG,CAAC;GAC1H,SAAS,OAAgB;IACrB,MAA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AE;IAClG,MAAM,KAAK,cAAc,EAAE,0CAA0C,MAAM,KAAK,eAAe,EAAE;IACjG,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,WAAW,EAAE,sBAAsB,MAAM,KAAK,oDAAoD,EAAE;IAC/G,MAAM,KAAK,QAAQ,EAAE;;EAEvB,MAAM,MAAM,KAAK,cAAc,EAAE;IAC/B,MAAM,KAAK,QAAQ,EAAE,kCAAkC,MAAM,KAAK,+BAA+B,EAAE;IACnG,MAAM,KAAK,MAAM,EAAE,kCAAkC,MAAM,KAAK,+BAA+B,EAAE;IACjG,MAAM,KAAK,UAAU,EAAE,2BAA2B,MAAM,KAAK,uBAAuB,EAAE;IACtF,MAAM,KAAK,iBAAiB,EAAE,+DAA+D,MAAM,KAAK,cAAc,EAAE;IACxH,MAAM,KAAK,QAAQ,EAAE;;EAEvB,MAAM,MAAM,KAAK,gBAAgB,EAAE,IAAI,MAAM,KAAK,iBAAiB,EAAE;IACnE,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,SAAS,EAAE;IACtB,MAAM,KAAK,gBAAgB,EAAE,+BAA+B,MAAM,KAAK,2CAA6C,EAAE;IACtH,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,WAAW,EAAE;IACxB,MAAM,KAAK,QAAQ,EAAE;;EAEvB,MAAM,MAAM,KAAK,OAAO,EAAE;;oBAER,MAAM,KAAK,iBAAiB,EAAE;yCACT,MAAM,KAAK,cAAc,EAAE;;;;uDAIb,MAAM,KAAK,iBAAiB,EAAE;;6CAExC,MAAM,KAAK,UAAU,EAAE;;;cAGtD,MAAM,KAAK,oBAAoB,EAAE;CAC9C;AACD"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
|
|
2
2
|
import { t as cliUserAgent } from "./version-ONIeo7jl.js";
|
|
3
|
-
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, n as isRecord, r as parsedLine, u as stringOf } from "./project-command-
|
|
4
|
-
import { D as isJsonMode, M as note, l as confirmDestructive, m as emit, st as success, v as fail } from "./context-
|
|
3
|
+
import { a as projectTarget, d as PROJECT_TARGET_FLAGS, n as isRecord, r as parsedLine, u as stringOf } from "./project-command-5wM_bJQt.js";
|
|
4
|
+
import { D as isJsonMode, M as note, l as confirmDestructive, m as emit, st as success, v as fail } from "./context-C9lz1vTS.js";
|
|
5
5
|
import chalk from "chalk";
|
|
6
6
|
import fs from "fs";
|
|
7
7
|
import path from "path";
|
|
@@ -276,4 +276,4 @@ async function storageStat(rawArgs) {
|
|
|
276
276
|
//#endregion
|
|
277
277
|
export { storageCp, storageLs, storageRm, storageStat, storageUrl };
|
|
278
278
|
|
|
279
|
-
//# sourceMappingURL=storage-objects-
|
|
279
|
+
//# sourceMappingURL=storage-objects-DbFsemMV.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-objects-CfRKlTDe.js","names":[],"sources":["../src/commands/storage-objects.ts"],"sourcesContent":["/**\n * CLI commands: rebase storage ls | cp | rm | url | stat\n *\n * A running app's stored files, through its `/api/storage` routes and the\n * SDK's storage client — so the storage policies (`storageAuthorize`,\n * `storagePolicies`) decide, as they do for the app's own users. The same\n * target and credential every project command resolves.\n *\n * A remote object is written with a colon: `:avatars/me.png` in the default\n * storage source, `media:avatars/me.png` in the source keyed `media`. A local\n * path never starts with one, so `cp` reads its direction from which side has\n * it: `rebase storage cp ./me.png :avatars/me.png` uploads,\n * `rebase storage cp :avatars/me.png ./me.png` downloads.\n *\n * `orphans` and `move` (the whole-store maintenance in `storage.ts`) are the\n * other half of the group.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError } from \"../utils/args\";\nimport { PROJECT_TARGET_FLAGS, type ProjectTarget } from \"../utils/project-target\";\nimport {\n emit,\n fail,\n isJsonMode,\n isRecord,\n parsedLine,\n projectTarget,\n stringOf\n} from \"../utils/project-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { confirmDestructive, note, success } from \"./cloud/context\";\n\n/** The subcommands this module answers, beside `orphans` and `move`. */\nexport const STORAGE_OBJECT_SUBCOMMANDS = [\"ls\", \"cp\", \"rm\", \"url\", \"stat\"] as const;\n\n/** A remote object named on the line: the source key (empty: the default) and the object key. */\nexport interface RemoteObject {\n source: string;\n key: string;\n}\n\n/**\n * `:key` or `source:key` — or undefined for a local path. A Windows drive\n * (`C:\\…`, `C:/…`) is local. Exported for its tests.\n */\nexport function remoteObjectOf(raw: string): RemoteObject | undefined {\n if (/^[a-zA-Z]:[\\\\/]/.test(raw)) return undefined;\n const match = /^([A-Za-z0-9_-]*):(.*)$/s.exec(raw);\n if (!match) return undefined;\n return { source: match[1], key: match[2].replace(/^\\/+/, \"\") };\n}\n\nfunction describeRemote(object: RemoteObject): string {\n return `${object.source}:${object.key}`;\n}\n\n/** The SDK's storage source for a target and a source key. */\nasync function storageFor(target: ProjectTarget, source: string) {\n const { createRebaseClient } = await import(\"@rebasepro/client\");\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 return source ? client.createStorageSource(source) : client.storage;\n}\n\n/** An SDK failure in this command's words: the server's code and message when it sent them. */\nfunction reportStorageError(e: unknown, action: string): never {\n const status = isRecord(e) && typeof e.status === \"number\" ? e.status : undefined;\n const code = isRecord(e) && typeof e.code === \"string\" ? e.code : status === 404 ? \"not_found\" : \"error\";\n const message = e instanceof Error ? e.message : String(e);\n fail(`${action} — ${code}${status ? ` (${status})` : \"\"}: ${message}`, status === 501 ? \"This server has no storage configured.\" : undefined, code);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n ls\n ═══════════════════════════════════════════════════════════════ */\n\nexport const STORAGE_LS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--limit\": Number,\n \"-n\": \"--limit\",\n \"--page-token\": String\n} satisfies arg.Spec;\n\nexport async function storageLs(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_LS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage ls\",\n maxPositionals: 1\n }));\n const where = positionals[0] ? remoteObjectOf(positionals[0]) ?? { source: \"\", key: positionals[0] } : { source: \"\", key: \"\" };\n const target = await projectTarget(flags, { command: \"storage ls\" });\n const storage = await storageFor(target, where.source);\n let result: Awaited<ReturnType<typeof storage.listObjects>>;\n try {\n result = await storage.listObjects(where.key, {\n ...(flags[\"--limit\"] ? { maxResults: flags[\"--limit\"] } : {}),\n ...(flags[\"--page-token\"] ? { pageToken: flags[\"--page-token\"] } : {})\n });\n } catch (e) {\n reportStorageError(e, `Failed to list ${describeRemote(where)}`);\n }\n emit(() => {\n const prefixes = result.prefixes ?? [];\n const items = result.items ?? [];\n if (prefixes.length === 0 && items.length === 0) return note(`Nothing under ${describeRemote(where)}.`);\n for (const prefix of prefixes) console.log(` ${chalk.blue(`${stringOf(prefix.fullPath) ?? stringOf(prefix.name) ?? \"?\"}/`)}`);\n for (const item of items) console.log(` ${stringOf(item.fullPath) ?? stringOf(item.name) ?? \"?\"}`);\n if (result.nextPageToken) note(chalk.gray(`More: --page-token ${result.nextPageToken}`));\n }, result);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cp\n ═══════════════════════════════════════════════════════════════ */\n\nexport const STORAGE_CP_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--content-type\": String,\n \"--public\": Boolean,\n \"--force\": Boolean,\n \"-f\": \"--force\"\n} satisfies arg.Spec;\n\nexport async function storageCp(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_CP_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage cp\",\n maxPositionals: 2\n }));\n const { from, to } = parsedLine(() => {\n if (positionals.length !== 2) {\n throw new UsageError(\"rebase storage cp takes a source and a destination; a remote object starts with a colon: rebase storage cp ./me.png :avatars/me.png.\");\n }\n const [a, b] = positionals;\n const remoteA = remoteObjectOf(a);\n const remoteB = remoteObjectOf(b);\n if (remoteA && remoteB) throw new UsageError(\"Both sides are remote objects; copying between sources is `rebase storage move`.\");\n if (!remoteA && !remoteB) throw new UsageError(\"Neither side is a remote object: write the stored one with a colon, :key or <source>:key.\");\n return { from: remoteA ?? a, to: remoteB ?? b };\n });\n const target = await projectTarget(flags, { command: \"storage cp\" });\n\n if (typeof from === \"string\" && typeof to !== \"string\") {\n // Upload.\n let bytes: Buffer;\n try {\n bytes = fs.readFileSync(from);\n } catch (e) {\n fail(`Cannot read ${from}: ${e instanceof Error ? e.message : String(e)}`, undefined, \"usage\");\n }\n const key = to.key.endsWith(\"/\") || to.key === \"\" ? `${to.key}${path.basename(from)}` : to.key;\n const storage = await storageFor(target, to.source);\n const file = new File([new Uint8Array(bytes)], path.basename(from), flags[\"--content-type\"] ? { type: flags[\"--content-type\"] } : {});\n try {\n const result = await storage.putObject({ file, key, ...(flags[\"--public\"] ? { public: true } : {}) });\n emit(() => success(`Uploaded ${from} to ${describeRemote({ source: to.source, key })} (${bytes.length} bytes).`), result);\n } catch (e) {\n reportStorageError(e, `Failed to upload ${from}`);\n }\n return;\n }\n\n if (typeof from !== \"string\" && typeof to === \"string\") {\n // Download.\n const storage = await storageFor(target, from.source);\n let file: File | null;\n try {\n file = await storage.getObject(from.key);\n } catch (e) {\n reportStorageError(e, `Failed to download ${describeRemote(from)}`);\n }\n if (!file) fail(`${describeRemote(from)} does not exist on ${target.label}.`, undefined, \"not_found\");\n const bytes = Buffer.from(await file.arrayBuffer());\n if (to === \"-\") {\n process.stdout.write(bytes);\n return;\n }\n const destination = fs.existsSync(to) && fs.statSync(to).isDirectory() ? path.join(to, path.basename(from.key)) : to;\n if (fs.existsSync(destination) && !flags[\"--force\"]) {\n fail(`${destination} exists; pass --force to overwrite it.`, undefined, \"exists\");\n }\n fs.writeFileSync(destination, bytes);\n emit(() => success(`Downloaded ${describeRemote(from)} to ${destination} (${bytes.length} bytes).`), {\n object: describeRemote(from),\n path: destination,\n bytes: bytes.length\n });\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n rm / url / stat\n ═══════════════════════════════════════════════════════════════ */\n\nexport const STORAGE_RM_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nexport async function storageRm(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_RM_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage rm\",\n maxPositionals: 1\n }));\n const object = parsedLine(() => requireRemote(positionals[0], \"storage rm\"));\n const target = await projectTarget(flags, { command: \"storage rm\" });\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Delete ${describeRemote(object)} on ${target.label}? A row that names it keeps a dangling path.` });\n const storage = await storageFor(target, object.source);\n try {\n await storage.deleteObject(object.key);\n } catch (e) {\n reportStorageError(e, `Failed to delete ${describeRemote(object)}`);\n }\n emit(() => success(`Deleted ${describeRemote(object)}.`), { object: describeRemote(object), deleted: true });\n}\n\n/** A remote object, or a refusal naming the colon syntax. Takes a bare key as the default source's. */\nfunction requireRemote(raw: string | undefined, command: string): RemoteObject {\n if (!raw) throw new UsageError(`rebase ${command} needs a stored object: rebase ${command} :avatars/me.png (or <source>:key).`);\n return remoteObjectOf(raw) ?? { source: \"\", key: raw };\n}\n\nexport const STORAGE_URL_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\n/**\n * A download link for an object, signed by the server: whoever holds it can\n * read the object until it expires, with no credential of their own.\n */\nexport async function storageUrl(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_URL_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage url\",\n maxPositionals: 1\n }));\n const object = parsedLine(() => requireRemote(positionals[0], \"storage url\"));\n const target = await projectTarget(flags, { command: \"storage url\" });\n const storage = await storageFor(target, object.source);\n let config: Awaited<ReturnType<typeof storage.getSignedUrl>>;\n try {\n config = await storage.getSignedUrl(object.key);\n } catch (e) {\n reportStorageError(e, `Failed to sign a link to ${describeRemote(object)}`);\n }\n if (config.fileNotFound || !config.url) fail(`${describeRemote(object)} does not exist on ${target.label}.`, undefined, \"not_found\");\n const url = /^https?:\\/\\//.test(config.url) ? config.url : `${target.baseUrl}${config.url.startsWith(\"/\") ? \"\" : \"/\"}${config.url}`;\n if (isJsonMode()) emit(() => undefined, { object: describeRemote(object), url });\n else process.stdout.write(`${url}\\n`);\n}\n\nexport const STORAGE_STAT_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nexport async function storageStat(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_STAT_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage stat\",\n maxPositionals: 1\n }));\n const object = parsedLine(() => requireRemote(positionals[0], \"storage stat\"));\n const target = await projectTarget(flags, { command: \"storage stat\" });\n const storage = await storageFor(target, object.source);\n let config: Awaited<ReturnType<typeof storage.getSignedUrl>>;\n try {\n config = await storage.getSignedUrl(object.key);\n } catch (e) {\n reportStorageError(e, `Failed to read ${describeRemote(object)}`);\n }\n if (config.fileNotFound) fail(`${describeRemote(object)} does not exist on ${target.label}.`, undefined, \"not_found\");\n const metadata = isRecord(config.metadata) ? config.metadata : {};\n emit(() => {\n console.log(` ${chalk.bold(describeRemote(object))}`);\n for (const [key, value] of Object.entries(metadata)) {\n if (value === undefined || value === null || typeof value === \"object\") continue;\n console.log(` ${chalk.gray(key.padEnd(16))}${String(value)}`);\n }\n }, { object: describeRemote(object), metadata });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,eAAe,KAAuC;CAClE,IAAI,kBAAkB,KAAK,GAAG,GA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{"version":3,"file":"storage-objects-DbFsemMV.js","names":[],"sources":["../src/commands/storage-objects.ts"],"sourcesContent":["/**\n * CLI commands: rebase storage ls | cp | rm | url | stat\n *\n * A running app's stored files, through its `/api/storage` routes and the\n * SDK's storage client — so the storage policies (`storageAuthorize`,\n * `storagePolicies`) decide, as they do for the app's own users. The same\n * target and credential every project command resolves.\n *\n * A remote object is written with a colon: `:avatars/me.png` in the default\n * storage source, `media:avatars/me.png` in the source keyed `media`. A local\n * path never starts with one, so `cp` reads its direction from which side has\n * it: `rebase storage cp ./me.png :avatars/me.png` uploads,\n * `rebase storage cp :avatars/me.png ./me.png` downloads.\n *\n * `orphans` and `move` (the whole-store maintenance in `storage.ts`) are the\n * other half of the group.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError } from \"../utils/args\";\nimport { PROJECT_TARGET_FLAGS, type ProjectTarget } from \"../utils/project-target\";\nimport {\n emit,\n fail,\n isJsonMode,\n isRecord,\n parsedLine,\n projectTarget,\n stringOf\n} from \"../utils/project-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { confirmDestructive, note, success } from \"./cloud/context\";\n\n/** The subcommands this module answers, beside `orphans` and `move`. */\nexport const STORAGE_OBJECT_SUBCOMMANDS = [\"ls\", \"cp\", \"rm\", \"url\", \"stat\"] as const;\n\n/** A remote object named on the line: the source key (empty: the default) and the object key. */\nexport interface RemoteObject {\n source: string;\n key: string;\n}\n\n/**\n * `:key` or `source:key` — or undefined for a local path. A Windows drive\n * (`C:\\…`, `C:/…`) is local. Exported for its tests.\n */\nexport function remoteObjectOf(raw: string): RemoteObject | undefined {\n if (/^[a-zA-Z]:[\\\\/]/.test(raw)) return undefined;\n const match = /^([A-Za-z0-9_-]*):(.*)$/s.exec(raw);\n if (!match) return undefined;\n return { source: match[1], key: match[2].replace(/^\\/+/, \"\") };\n}\n\nfunction describeRemote(object: RemoteObject): string {\n return `${object.source}:${object.key}`;\n}\n\n/** The SDK's storage source for a target and a source key. */\nasync function storageFor(target: ProjectTarget, source: string) {\n const { createRebaseClient } = await import(\"@rebasepro/client\");\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 return source ? client.createStorageSource(source) : client.storage;\n}\n\n/** An SDK failure in this command's words: the server's code and message when it sent them. */\nfunction reportStorageError(e: unknown, action: string): never {\n const status = isRecord(e) && typeof e.status === \"number\" ? e.status : undefined;\n const code = isRecord(e) && typeof e.code === \"string\" ? e.code : status === 404 ? \"not_found\" : \"error\";\n const message = e instanceof Error ? e.message : String(e);\n fail(`${action} — ${code}${status ? ` (${status})` : \"\"}: ${message}`, status === 501 ? \"This server has no storage configured.\" : undefined, code);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n ls\n ═══════════════════════════════════════════════════════════════ */\n\nexport const STORAGE_LS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--limit\": Number,\n \"-n\": \"--limit\",\n \"--page-token\": String\n} satisfies arg.Spec;\n\nexport async function storageLs(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_LS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage ls\",\n maxPositionals: 1\n }));\n const where = positionals[0] ? remoteObjectOf(positionals[0]) ?? { source: \"\", key: positionals[0] } : { source: \"\", key: \"\" };\n const target = await projectTarget(flags, { command: \"storage ls\" });\n const storage = await storageFor(target, where.source);\n let result: Awaited<ReturnType<typeof storage.listObjects>>;\n try {\n result = await storage.listObjects(where.key, {\n ...(flags[\"--limit\"] ? { maxResults: flags[\"--limit\"] } : {}),\n ...(flags[\"--page-token\"] ? { pageToken: flags[\"--page-token\"] } : {})\n });\n } catch (e) {\n reportStorageError(e, `Failed to list ${describeRemote(where)}`);\n }\n emit(() => {\n const prefixes = result.prefixes ?? [];\n const items = result.items ?? [];\n if (prefixes.length === 0 && items.length === 0) return note(`Nothing under ${describeRemote(where)}.`);\n for (const prefix of prefixes) console.log(` ${chalk.blue(`${stringOf(prefix.fullPath) ?? stringOf(prefix.name) ?? \"?\"}/`)}`);\n for (const item of items) console.log(` ${stringOf(item.fullPath) ?? stringOf(item.name) ?? \"?\"}`);\n if (result.nextPageToken) note(chalk.gray(`More: --page-token ${result.nextPageToken}`));\n }, result);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cp\n ═══════════════════════════════════════════════════════════════ */\n\nexport const STORAGE_CP_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--content-type\": String,\n \"--public\": Boolean,\n \"--force\": Boolean,\n \"-f\": \"--force\"\n} satisfies arg.Spec;\n\nexport async function storageCp(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_CP_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage cp\",\n maxPositionals: 2\n }));\n const { from, to } = parsedLine(() => {\n if (positionals.length !== 2) {\n throw new UsageError(\"rebase storage cp takes a source and a destination; a remote object starts with a colon: rebase storage cp ./me.png :avatars/me.png.\");\n }\n const [a, b] = positionals;\n const remoteA = remoteObjectOf(a);\n const remoteB = remoteObjectOf(b);\n if (remoteA && remoteB) throw new UsageError(\"Both sides are remote objects; copying between sources is `rebase storage move`.\");\n if (!remoteA && !remoteB) throw new UsageError(\"Neither side is a remote object: write the stored one with a colon, :key or <source>:key.\");\n return { from: remoteA ?? a, to: remoteB ?? b };\n });\n const target = await projectTarget(flags, { command: \"storage cp\" });\n\n if (typeof from === \"string\" && typeof to !== \"string\") {\n // Upload.\n let bytes: Buffer;\n try {\n bytes = fs.readFileSync(from);\n } catch (e) {\n fail(`Cannot read ${from}: ${e instanceof Error ? e.message : String(e)}`, undefined, \"usage\");\n }\n const key = to.key.endsWith(\"/\") || to.key === \"\" ? `${to.key}${path.basename(from)}` : to.key;\n const storage = await storageFor(target, to.source);\n const file = new File([new Uint8Array(bytes)], path.basename(from), flags[\"--content-type\"] ? { type: flags[\"--content-type\"] } : {});\n try {\n const result = await storage.putObject({ file, key, ...(flags[\"--public\"] ? { public: true } : {}) });\n emit(() => success(`Uploaded ${from} to ${describeRemote({ source: to.source, key })} (${bytes.length} bytes).`), result);\n } catch (e) {\n reportStorageError(e, `Failed to upload ${from}`);\n }\n return;\n }\n\n if (typeof from !== \"string\" && typeof to === \"string\") {\n // Download.\n const storage = await storageFor(target, from.source);\n let file: File | null;\n try {\n file = await storage.getObject(from.key);\n } catch (e) {\n reportStorageError(e, `Failed to download ${describeRemote(from)}`);\n }\n if (!file) fail(`${describeRemote(from)} does not exist on ${target.label}.`, undefined, \"not_found\");\n const bytes = Buffer.from(await file.arrayBuffer());\n if (to === \"-\") {\n process.stdout.write(bytes);\n return;\n }\n const destination = fs.existsSync(to) && fs.statSync(to).isDirectory() ? path.join(to, path.basename(from.key)) : to;\n if (fs.existsSync(destination) && !flags[\"--force\"]) {\n fail(`${destination} exists; pass --force to overwrite it.`, undefined, \"exists\");\n }\n fs.writeFileSync(destination, bytes);\n emit(() => success(`Downloaded ${describeRemote(from)} to ${destination} (${bytes.length} bytes).`), {\n object: describeRemote(from),\n path: destination,\n bytes: bytes.length\n });\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n rm / url / stat\n ═══════════════════════════════════════════════════════════════ */\n\nexport const STORAGE_RM_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nexport async function storageRm(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_RM_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage rm\",\n maxPositionals: 1\n }));\n const object = parsedLine(() => requireRemote(positionals[0], \"storage rm\"));\n const target = await projectTarget(flags, { command: \"storage rm\" });\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Delete ${describeRemote(object)} on ${target.label}? A row that names it keeps a dangling path.` });\n const storage = await storageFor(target, object.source);\n try {\n await storage.deleteObject(object.key);\n } catch (e) {\n reportStorageError(e, `Failed to delete ${describeRemote(object)}`);\n }\n emit(() => success(`Deleted ${describeRemote(object)}.`), { object: describeRemote(object), deleted: true });\n}\n\n/** A remote object, or a refusal naming the colon syntax. Takes a bare key as the default source's. */\nfunction requireRemote(raw: string | undefined, command: string): RemoteObject {\n if (!raw) throw new UsageError(`rebase ${command} needs a stored object: rebase ${command} :avatars/me.png (or <source>:key).`);\n return remoteObjectOf(raw) ?? { source: \"\", key: raw };\n}\n\nexport const STORAGE_URL_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\n/**\n * A download link for an object, signed by the server: whoever holds it can\n * read the object until it expires, with no credential of their own.\n */\nexport async function storageUrl(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_URL_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage url\",\n maxPositionals: 1\n }));\n const object = parsedLine(() => requireRemote(positionals[0], \"storage url\"));\n const target = await projectTarget(flags, { command: \"storage url\" });\n const storage = await storageFor(target, object.source);\n let config: Awaited<ReturnType<typeof storage.getSignedUrl>>;\n try {\n config = await storage.getSignedUrl(object.key);\n } catch (e) {\n reportStorageError(e, `Failed to sign a link to ${describeRemote(object)}`);\n }\n if (config.fileNotFound || !config.url) fail(`${describeRemote(object)} does not exist on ${target.label}.`, undefined, \"not_found\");\n const url = /^https?:\\/\\//.test(config.url) ? config.url : `${target.baseUrl}${config.url.startsWith(\"/\") ? \"\" : \"/\"}${config.url}`;\n if (isJsonMode()) emit(() => undefined, { object: describeRemote(object), url });\n else process.stdout.write(`${url}\\n`);\n}\n\nexport const STORAGE_STAT_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nexport async function storageStat(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: STORAGE_STAT_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"storage stat\",\n maxPositionals: 1\n }));\n const object = parsedLine(() => requireRemote(positionals[0], \"storage stat\"));\n const target = await projectTarget(flags, { command: \"storage stat\" });\n const storage = await storageFor(target, object.source);\n let config: Awaited<ReturnType<typeof storage.getSignedUrl>>;\n try {\n config = await storage.getSignedUrl(object.key);\n } catch (e) {\n reportStorageError(e, `Failed to read ${describeRemote(object)}`);\n }\n if (config.fileNotFound) fail(`${describeRemote(object)} does not exist on ${target.label}.`, undefined, \"not_found\");\n const metadata = isRecord(config.metadata) ? config.metadata : {};\n emit(() => {\n console.log(` ${chalk.bold(describeRemote(object))}`);\n for (const [key, value] of Object.entries(metadata)) {\n if (value === undefined || value === null || typeof value === \"object\") continue;\n console.log(` ${chalk.gray(key.padEnd(16))}${String(value)}`);\n }\n }, { object: describeRemote(object), metadata });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,eAAe,KAAuC;CAClE,IAAI,kBAAkB,KAAK,GAAG,GAAG,OAAO,KAAA;CACxC,MAAM,QAAQ,2BAA2B,KAAK,GAAG;CACjD,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,OAAO;EAAE,QAAQ,MAAM;EAAI,KAAK,MAAM,EAAE,CAAC,QAAQ,QAAQ,EAAE;CAAE;AACjE;AAEA,SAAS,eAAe,QAA8B;CAClD,OAAO,GAAG,OAAO,OAAO,GAAG,OAAO;AACtC;;AAGA,eAAe,WAAW,QAAuB,QAAgB;CAC7D,MAAM,EAAE,uBAAuB,MAAM,OAAO;CAC5C,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,OAAO,SA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tD,IAAI;CACJ,IAAI;EACA,SAAS,MAAM,QAAQ,aAAa,OAAO,GAAG;CAClD,SAAS,GAAG;EACR,mBAAmB,GAAG,kBAAkB,eAAe,MAAM,GAAG;CACpE;CACA,IAAI,OAAO,cAAc,KAAK,GAAG,eAAe,MAAM,EAAE,qBAAqB,OAAO,MAAM,IAAI,KAAA,GAAW,WAAW;CACpH,MAAM,WAAW,SAAS,OAAO,QAAQ,IAAI,OAAO,WAAW,CAAC;CAChE,WAAW;EACP,QAAQ,IAAI,KAAK,MAAM,KAAK,eAAe,MAAM,CAAC,GAAG;EACrD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAAG;GACjD,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,OAAO,UAAU,UAAU;GACxE,QAAQ,IAAI,OAAO,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC,IAAI,OAAO,KAAK,GAAG;EACnE;CACJ,GAAG;EAAE,QAAQ,eAAe,MAAM;EAAG;CAAS,CAAC;AACnD"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as setConsent, d as configPath, f as readConfig, r as previewEvent, s as readProjectPolicy, t as endpoint } from "./telemetry-
|
|
1
|
+
import { a as setConsent, d as configPath, f as readConfig, r as previewEvent, s as readProjectPolicy, t as endpoint } from "./telemetry-CJbrRuG3.js";
|
|
2
2
|
import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
|
|
3
3
|
import { a as wantsHelp, n as parseCommandArgs } from "./args-DHyrshtI.js";
|
|
4
|
-
import { r as renderPreview, t as describeState } from "./consent-
|
|
4
|
+
import { r as renderPreview, t as describeState } from "./consent-C8_Ik_GK.js";
|
|
5
5
|
import chalk from "chalk";
|
|
6
6
|
//#region src/commands/telemetry.ts
|
|
7
7
|
/**
|
|
@@ -126,4 +126,4 @@ ${chalk.gray("URLs, hostnames, error messages, stack traces, or exact record cou
|
|
|
126
126
|
//#endregion
|
|
127
127
|
export { TELEMETRY_SUBCOMMANDS, telemetryCommand };
|
|
128
128
|
|
|
129
|
-
//# sourceMappingURL=telemetry-
|
|
129
|
+
//# sourceMappingURL=telemetry-B5RSeQIc.js.map
|