@rebasepro/cli 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/bin/rebase.js +143 -4
- package/dist/{agent-setup-B5AKHOgt.js → agent-setup-D9mHRZ5R.js} +125 -3
- package/dist/agent-setup-D9mHRZ5R.js.map +1 -0
- package/dist/{api-keys-Tm7zvAPe.js → api-keys-CyJ26KEJ.js} +41 -10
- package/dist/api-keys-CyJ26KEJ.js.map +1 -0
- package/dist/{apps-BsU_ILbP.js → apps-CnLDV5b6.js} +6 -7
- package/dist/{apps-BsU_ILbP.js.map → apps-CnLDV5b6.js.map} +1 -1
- package/dist/{atlas-dev-database-OWtqnG7W.js → atlas-dev-database-BODqdCWt.js} +4 -4
- package/dist/{atlas-dev-database-OWtqnG7W.js.map → atlas-dev-database-BODqdCWt.js.map} +1 -1
- package/dist/{auth-Vl2hFKXP.js → auth-dII2jCO1.js} +10 -8
- package/dist/auth-dII2jCO1.js.map +1 -0
- package/dist/{branch-pointer-9DnwkFJJ.js → branch-pointer-BQUF6lYa.js} +1 -1
- package/dist/{build-BBgT8EJZ.js → build-Cza7ZQrp.js} +6 -7
- package/dist/{build-BBgT8EJZ.js.map → build-Cza7ZQrp.js.map} +1 -1
- package/dist/{bundle-DtCCCr4w.js → bundle-C6yEtMJ-.js} +53 -5
- package/dist/bundle-C6yEtMJ-.js.map +1 -0
- package/dist/bundle.d.ts +14 -0
- package/dist/{cloud-BpH0_bmV.js → cloud-BdnmqQaZ.js} +8528 -4342
- package/dist/cloud-BdnmqQaZ.js.map +1 -0
- package/dist/collections-dir-DlvDhime.js +69 -0
- package/dist/collections-dir-DlvDhime.js.map +1 -0
- package/dist/commands/agent-setup.d.ts +58 -0
- package/dist/commands/api-keys.d.ts +13 -0
- package/dist/commands/cloud/activity.d.ts +25 -0
- package/dist/commands/cloud/app-key.d.ts +18 -0
- package/dist/commands/cloud/auth.d.ts +1 -0
- package/dist/commands/cloud/billing-invoices.d.ts +39 -0
- package/dist/commands/cloud/claim.d.ts +7 -0
- package/dist/commands/cloud/context.d.ts +115 -6
- package/dist/commands/cloud/deploy-summary.d.ts +162 -0
- package/dist/commands/cloud/deploy.d.ts +64 -0
- package/dist/commands/cloud/env.d.ts +24 -0
- package/dist/commands/cloud/index.d.ts +13 -1
- package/dist/commands/cloud/init.d.ts +143 -0
- package/dist/commands/cloud/login-flow.d.ts +51 -0
- package/dist/commands/cloud/notifications.d.ts +28 -0
- package/dist/commands/cloud/orgs.d.ts +13 -0
- package/dist/commands/cloud/previews.d.ts +123 -0
- package/dist/commands/cloud/resources.d.ts +68 -14
- package/dist/commands/cloud/runtime-logs.d.ts +176 -0
- package/dist/commands/cloud/service-key.d.ts +15 -0
- package/dist/commands/cloud/token-capabilities.d.ts +61 -8
- package/dist/commands/cloud/tokens.d.ts +18 -3
- package/dist/commands/cloud/usage.d.ts +63 -0
- package/dist/commands/dev.d.ts +22 -0
- package/dist/commands/doctor.d.ts +1 -1
- package/dist/commands/generate-view.d.ts +94 -0
- package/dist/commands/generate_sdk.d.ts +19 -2
- package/dist/commands/init.d.ts +20 -0
- package/dist/commands/skills.d.ts +4 -3
- package/dist/commands/start.d.ts +10 -0
- package/dist/commands/storage.d.ts +4 -0
- package/dist/commands/upgrade.d.ts +12 -0
- package/dist/commands/verify.d.ts +96 -0
- package/dist/{consent-ClRHmcxf.js → consent-BD7F29T3.js} +2 -2
- package/dist/{consent-ClRHmcxf.js.map → consent-BD7F29T3.js.map} +1 -1
- package/dist/{console-CEGm0XNc.js → console-BXB6-8GT.js} +12 -6
- package/dist/console-BXB6-8GT.js.map +1 -0
- package/dist/{context-CyflUrKg.js → context-GUxkZm-S.js} +482 -26
- package/dist/context-GUxkZm-S.js.map +1 -0
- package/dist/{daemon-CknkDjd6.js → daemon-Cp7oNXth.js} +160 -5
- package/dist/daemon-Cp7oNXth.js.map +1 -0
- package/dist/{daemon-entry-CbLRrgzy.js → daemon-entry-zOC1revO.js} +6 -3
- package/dist/daemon-entry-zOC1revO.js.map +1 -0
- package/dist/{db-CRNpA5mH.js → db-KzlqddGD.js} +101 -54
- package/dist/db-KzlqddGD.js.map +1 -0
- package/dist/{derive-CsoFGAnK.js → derive-ae9UOoOB.js} +2 -2
- package/dist/{derive-CsoFGAnK.js.map → derive-ae9UOoOB.js.map} +1 -1
- package/dist/{dev-C0pbMmhS.js → dev-DTqVMgB3.js} +231 -44
- package/dist/dev-DTqVMgB3.js.map +1 -0
- package/dist/dev-db/daemon.d.ts +41 -0
- package/dist/dev-db/pull.d.ts +33 -5
- package/dist/dev-db/state.d.ts +9 -0
- package/dist/{dev-preflight-unHpiYO1.js → dev-preflight-Cxv3TiD1.js} +73 -27
- package/dist/dev-preflight-Cxv3TiD1.js.map +1 -0
- package/dist/{dev-server-B1UYifZJ.js → dev-server-OJsUGZEB.js} +14 -3
- package/dist/dev-server-OJsUGZEB.js.map +1 -0
- package/dist/{doctor-CATRdWm6.js → doctor-BRWOlqeG.js} +14 -12
- package/dist/doctor-BRWOlqeG.js.map +1 -0
- package/dist/{eject-DuasTr-F.js → eject-DABcDnPN.js} +3 -4
- package/dist/{eject-DuasTr-F.js.map → eject-DABcDnPN.js.map} +1 -1
- package/dist/{fold-static-hDHtDfTq.js → fold-static-BnAK-anQ.js} +3 -3
- package/dist/{fold-static-hDHtDfTq.js.map → fold-static-BnAK-anQ.js.map} +1 -1
- package/dist/generate-view-IFwCADvb.js +662 -0
- package/dist/generate-view-IFwCADvb.js.map +1 -0
- package/dist/{generate_sdk-Cvg5jjJF.js → generate_sdk-BvcWvoUh.js} +49 -13
- package/dist/generate_sdk-BvcWvoUh.js.map +1 -0
- package/dist/index.es.js +58 -40
- package/dist/index.es.js.map +1 -1
- package/dist/{init-BWAwHPtz.js → init-CaU6GhwI.js} +50 -62
- package/dist/init-CaU6GhwI.js.map +1 -0
- package/dist/invoked-command-CG_rIa_o.js +55 -0
- package/dist/invoked-command-CG_rIa_o.js.map +1 -0
- package/dist/last-dev-database-DpW5dfoX.js +2 -0
- package/dist/{manifest-DRp0UVTj.js → manifest-BtzDy7KQ.js} +36 -3
- package/dist/{manifest-DRp0UVTj.js.map → manifest-BtzDy7KQ.js.map} +1 -1
- package/dist/{normalize-imports-BoBVh5tU.js → normalize-imports-D0zXlM6g.js} +3 -3
- package/dist/{normalize-imports-BoBVh5tU.js.map → normalize-imports-D0zXlM6g.js.map} +1 -1
- package/dist/{path-flags-BFgG9V6y.js → path-flags-DNvtEi2-.js} +5 -4
- package/dist/path-flags-DNvtEi2-.js.map +1 -0
- package/dist/{prepare-DdnU70z8.js → prepare-CTw9NEkh.js} +5 -4
- package/dist/{prepare-DdnU70z8.js.map → prepare-CTw9NEkh.js.map} +1 -1
- package/dist/project-CasK56vN.js +701 -0
- package/dist/project-CasK56vN.js.map +1 -0
- package/dist/{pull-C3PXduzl.js → pull-DDMpsZ5r.js} +131 -24
- package/dist/pull-DDMpsZ5r.js.map +1 -0
- package/dist/refusal-ReeeGP8a.js +26 -0
- package/dist/refusal-ReeeGP8a.js.map +1 -0
- package/dist/resolve-D647F1LA.js +2 -0
- package/dist/{resources-BdNRDEAy.js → resources-CPSC5Kcu.js} +4 -5
- package/dist/{resources-BdNRDEAy.js.map → resources-CPSC5Kcu.js.map} +1 -1
- package/dist/{schema-B0-p6T1O.js → schema-BSXwZSiI.js} +9 -8
- package/dist/schema-BSXwZSiI.js.map +1 -0
- package/dist/{skills-DfnTeyRz.js → skills-BU2flMOy.js} +52 -8
- package/dist/skills-BU2flMOy.js.map +1 -0
- package/dist/{start-BmEZkS0n.js → start-mVb6upwY.js} +20 -7
- package/dist/start-mVb6upwY.js.map +1 -0
- package/dist/{state-CCB-FAQ9.js → state-CYdBvnwA.js} +3 -2
- package/dist/state-CYdBvnwA.js.map +1 -0
- package/dist/static-syntax-check.d.ts +64 -0
- package/dist/{status-BJ26yZOo.js → status-BREvtzJm.js} +8 -9
- package/dist/{status-BJ26yZOo.js.map → status-BREvtzJm.js.map} +1 -1
- package/dist/{storage-DKPUBTWG.js → storage-DtOXGflp.js} +159 -16
- package/dist/storage-DtOXGflp.js.map +1 -0
- package/dist/{telemetry-EMFRVRQi.js → telemetry-CgwJPVMO.js} +2 -2
- package/dist/{telemetry-EMFRVRQi.js.map → telemetry-CgwJPVMO.js.map} +1 -1
- package/dist/{telemetry-m9czTNGR.js → telemetry-DwK5RQJl.js} +4 -4
- package/dist/{telemetry-m9czTNGR.js.map → telemetry-DwK5RQJl.js.map} +1 -1
- package/dist/{upgrade-DjihWuZL.js → upgrade-B7sVwL8S.js} +26 -4
- package/dist/{upgrade-DjihWuZL.js.map → upgrade-B7sVwL8S.js.map} +1 -1
- package/dist/utils/args.d.ts +32 -3
- package/dist/utils/boot-retry.d.ts +41 -0
- package/dist/utils/collections-dir.d.ts +14 -0
- package/dist/utils/dev-preflight.d.ts +34 -1
- package/dist/utils/dev-server.d.ts +11 -0
- package/dist/utils/path-flags.d.ts +2 -1
- package/dist/utils/project.d.ts +5 -1
- package/dist/utils/tool-stdio.d.ts +1 -1
- package/dist/utils/unknown-command.d.ts +4 -0
- package/dist/verify-D7UsV_qe.js +730 -0
- package/dist/verify-D7UsV_qe.js.map +1 -0
- package/package.json +9 -7
- package/templates/eject/backend/src/index.ts +9 -1
- package/templates/generated-schemas/ecommerce.ts +3 -0
- package/templates/overlays/baas/ai-instructions.md +13 -0
- package/templates/resource-graphs/blank.json +25 -0
- package/templates/resource-graphs/blog.json +28 -0
- package/templates/resource-graphs/ecommerce.json +28 -0
- package/templates/resource-graphs/headless.json +22 -0
- package/templates/template/.claude/hooks/post-edit-collection.sh +99 -0
- package/templates/template/.claude/settings.json +17 -0
- package/templates/template/.env.example +15 -5
- package/templates/template/ai-instructions.md +21 -1
- package/templates/template/config/collections/presets/ecommerce/index.ts +23 -0
- package/templates/template/docker-compose.yml +4 -1
- package/templates/template/frontend/package.json +1 -0
- package/templates/template/frontend/src/App.tsx +10 -9
- package/templates/views/AppView.tsx.tmpl +138 -0
- package/templates/views/EntityView.tsx.tmpl +64 -0
- package/templates/views/index.ts.tmpl +8 -0
- package/dist/agent-setup-B5AKHOgt.js.map +0 -1
- package/dist/api-keys-Tm7zvAPe.js.map +0 -1
- package/dist/args-BX0YD14a.js +0 -266
- package/dist/args-BX0YD14a.js.map +0 -1
- package/dist/auth-Vl2hFKXP.js.map +0 -1
- package/dist/bundle-DtCCCr4w.js.map +0 -1
- package/dist/cloud-BpH0_bmV.js.map +0 -1
- package/dist/console-CEGm0XNc.js.map +0 -1
- package/dist/context-CyflUrKg.js.map +0 -1
- package/dist/daemon-CknkDjd6.js.map +0 -1
- package/dist/daemon-entry-CbLRrgzy.js.map +0 -1
- package/dist/db-CRNpA5mH.js.map +0 -1
- package/dist/dev-C0pbMmhS.js.map +0 -1
- package/dist/dev-preflight-unHpiYO1.js.map +0 -1
- package/dist/dev-server-B1UYifZJ.js.map +0 -1
- package/dist/doctor-CATRdWm6.js.map +0 -1
- package/dist/generate_sdk-Cvg5jjJF.js.map +0 -1
- package/dist/init-BWAwHPtz.js.map +0 -1
- package/dist/last-dev-database-c_dKz1S3.js +0 -2
- package/dist/path-flags-BFgG9V6y.js.map +0 -1
- package/dist/project-Wp2zoyeN.js +0 -349
- package/dist/project-Wp2zoyeN.js.map +0 -1
- package/dist/pull-C3PXduzl.js.map +0 -1
- package/dist/resolve-CNQjsatH.js +0 -2
- package/dist/schema-B0-p6T1O.js.map +0 -1
- package/dist/skills-DfnTeyRz.js.map +0 -1
- package/dist/start-BmEZkS0n.js.map +0 -1
- package/dist/state-CCB-FAQ9.js.map +0 -1
- package/dist/storage-DKPUBTWG.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"path-flags-BFgG9V6y.js","names":[],"sources":["../src/utils/path-flags.ts"],"sourcesContent":["/**\n * Where a path typed on a `rebase` command line resolves: one rule, one sentence.\n *\n * The driver CLI runs with `cwd: backend/` — that is where it and its\n * dependencies resolve from — while people type commands from the project root\n * (or anywhere else in it). So every relative path on the line is resolved by\n * the CLI, from the directory the command was run in, before the driver is\n * handed a different one (`absolutizeLocalPathArgs` in `commands/db.ts`).\n * `generate-sdk` and `db backup --out` already worked that way; `--collections`\n * was resolved from `backend/` and was the odd one out.\n *\n * The sentence below is printed by every help page that takes `--collections`,\n * and by the refusal when the path is not there, so the rule is stated in one\n * set of words wherever a reader meets it.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\n\n/** The rule, as every help page and error states it. */\nexport const COLLECTIONS_PATH_RULE = \"relative paths are resolved from where you run the command\";\n\n/** The `--collections` line of a help page. */\nexport const COLLECTIONS_FLAG_HELP = `Collections directory (default: config/collections); ${COLLECTIONS_PATH_RULE}`;\n\n/** The flags that carry a collections path, in every spelling the driver accepts. */\nconst COLLECTIONS_FLAGS = [\"--collections\", \"-c\"];\n\n/** The `--collections` value on a line, as typed, or `null` when there is none. */\nfunction typedCollectionsPath(args: readonly string[]): string | null {\n for (let i = 0; i < args.length; i++) {\n const token = args[i];\n const eq = token.indexOf(\"=\");\n if (eq > 0 && COLLECTIONS_FLAGS.includes(token.slice(0, eq))) return token.slice(eq + 1) || null;\n if (COLLECTIONS_FLAGS.includes(token)) {\n const value = args[i + 1];\n return value && !value.startsWith(\"-\") ? value : null;\n }\n }\n return null;\n}\n\n/**\n * What a refusal over a missing `--collections` path spared, by what the command\n * would have done with it. Only a schema writer drops tables; a console or a\n * doctor run over nothing does something else wrong, and says so.\n */\nconst MISSING_COLLECTIONS_CONSEQUENCE = {\n schema: [\n \"Nothing was generated and nothing was applied — a schema generated from a\",\n \"directory that is not there is an empty one, and applying it would drop\",\n \"every table it does not describe.\"\n ],\n console: [\n \"Nothing was started — a console over a directory that is not there would\",\n \"load none of this project's collections.\"\n ],\n doctor: [\n \"Nothing was checked — a directory that is not there has no collections, so\",\n \"every collection check would pass over it.\"\n ]\n} as const;\n\n/** What a command does with its `--collections` path. */\nexport type CollectionsPathUse = keyof typeof MISSING_COLLECTIONS_CONSEQUENCE;\n\n/**\n * The refusal for a `--collections` path that does not exist, or `null`.\n *\n * Checked by the CLI, in the reader's terms, before the driver is spawned: the\n * driver's own check runs in `backend/` and can only describe the path it was\n * handed. A generator pointed at a directory that is not there writes an empty\n * schema, and a push of an empty schema drops every table — so nothing runs.\n *\n * Scripts written for the old rule (`--collections ../config/collections`,\n * run from the root) land here, and the message says exactly what to change.\n */\nexport function missingCollectionsPath(\n args: readonly string[],\n cwd: string,\n backendDir: string,\n use: CollectionsPathUse = \"schema\"\n): string[] | null {\n const typed = typedCollectionsPath(args);\n if (typed === null) return null;\n const resolved = path.resolve(cwd, typed);\n if (fs.existsSync(resolved)) return null;\n\n const lines = [\n chalk.red(`✗ Collections path not found: \"${typed}\"`),\n chalk.gray(` Resolved to: ${resolved}`),\n chalk.gray(` (${COLLECTIONS_PATH_RULE}: ${cwd})`)\n ];\n const fromBackend = path.resolve(backendDir, typed);\n if (!path.isAbsolute(typed) && fs.existsSync(fromBackend)) {\n lines.push(\n \"\",\n chalk.yellow(` From backend/ it would be ${fromBackend} — the driver used to resolve paths from there.`),\n chalk.yellow(` Leave the flag out (config/collections is the default), or write it from here: ${path.relative(cwd, fromBackend) || \".\"}`)\n );\n }\n lines.push(\"\", ...MISSING_COLLECTIONS_CONSEQUENCE[use].map(line => chalk.gray(` ${line}`)));\n return lines;\n}\n\n/** Print {@link missingCollectionsPath}'s refusal and exit 1, or return. */\nexport function refuseMissingCollectionsPath(\n args: readonly string[],\n cwd: string,\n backendDir: string,\n use: CollectionsPathUse = \"schema\"\n): void {\n const lines = missingCollectionsPath(args, cwd, backendDir, use);\n if (!lines) return;\n console.error(\"\");\n for (const line of lines) console.error(line);\n console.error(\"\");\n process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,wBAAwB;;AAGrC,IAAa,wBAAwB,wDAAwD;;AAG7F,IAAM,oBAAoB,CAAC,iBAAiB,IAAI;;AAGhD,SAAS,q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;;AAGA,SAAgB,6BACZ,MACA,KACA,YACA,MAA0B,UACtB;CACJ,MAAM,QAAQ,uBAAuB,MAAM,KAAK,YAAY,GAAG;CAC/D,IAAI,CAAC,OAAO;CACZ,QAAQ,MAAM,EAAE;CAChB,KAAK,MAAM,QAAQ,OAAO,QAAQ,MAAM,IAAI;CAC5C,QAAQ,MAAM,EAAE;CAChB,QAAQ,KAAK,CAAC;AAClB"}
|
package/dist/project-Wp2zoyeN.js
DELETED
|
@@ -1,349 +0,0 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import { n as getPMCommands, t as detectPackageManager } from "./package-manager-DSEOwTqM.js";
|
|
3
|
-
import chalk from "chalk";
|
|
4
|
-
import fs from "fs";
|
|
5
|
-
import path from "path";
|
|
6
|
-
import { pathToFileURL } from "url";
|
|
7
|
-
import { createRequire } from "module";
|
|
8
|
-
import { execSync } from "child_process";
|
|
9
|
-
import dotenv from "dotenv";
|
|
10
|
-
//#region src/utils/project.ts
|
|
11
|
-
/**
|
|
12
|
-
* Project discovery utilities for the Rebase CLI.
|
|
13
|
-
*
|
|
14
|
-
* These helpers locate the project root, backend directory, .env file,
|
|
15
|
-
* and local binaries — used by all CLI command modules.
|
|
16
|
-
*/
|
|
17
|
-
var project_exports = /* @__PURE__ */ __exportAll({
|
|
18
|
-
MANIFEST_FILENAME: () => MANIFEST_FILENAME,
|
|
19
|
-
dependenciesNotInstalled: () => dependenciesNotInstalled,
|
|
20
|
-
exitDependenciesNotInstalled: () => exitDependenciesNotInstalled,
|
|
21
|
-
failAsJson: () => failAsJson,
|
|
22
|
-
findBackendDir: () => findBackendDir,
|
|
23
|
-
findEnvFile: () => findEnvFile,
|
|
24
|
-
findFrontendDir: () => findFrontendDir,
|
|
25
|
-
findProjectRoot: () => findProjectRoot,
|
|
26
|
-
getActiveBackendPlugin: () => getActiveBackendPlugin,
|
|
27
|
-
readEnvFile: () => readEnvFile,
|
|
28
|
-
requireBackendDir: () => requireBackendDir,
|
|
29
|
-
requireProjectRoot: () => requireProjectRoot,
|
|
30
|
-
resolveLocalBin: () => resolveLocalBin,
|
|
31
|
-
resolvePluginCliScript: () => resolvePluginCliScript,
|
|
32
|
-
resolveTsx: () => resolveTsx,
|
|
33
|
-
resolveTsxLoader: () => resolveTsxLoader,
|
|
34
|
-
validateTsxInstallation: () => validateTsxInstallation,
|
|
35
|
-
wantsJsonOutput: () => wantsJsonOutput
|
|
36
|
-
});
|
|
37
|
-
/** The authored project manifest. Its presence alone marks a project root. */
|
|
38
|
-
var MANIFEST_FILENAME = "rebase.json";
|
|
39
|
-
/**
|
|
40
|
-
* Walk up from `startDir` to find the Rebase project root.
|
|
41
|
-
*
|
|
42
|
-
* A directory is the root when it holds a `rebase.json`, or when it holds a
|
|
43
|
-
* `package.json` that either lists `backend` as a workspace or sits beside both
|
|
44
|
-
* `backend/` and `config/`.
|
|
45
|
-
*
|
|
46
|
-
* `rebase.json` is checked first and needs no `package.json` beside it, because
|
|
47
|
-
* the conventions below all describe a repository that *contains the backend*.
|
|
48
|
-
* A repository holding only a frontend — the normal shape once a project's apps
|
|
49
|
-
* live in separate repositories — matches none of them, so without this the
|
|
50
|
-
* tooling could not run there at all.
|
|
51
|
-
*/
|
|
52
|
-
function findProjectRoot(startDir = process.cwd()) {
|
|
53
|
-
let dir = path.resolve(startDir);
|
|
54
|
-
const root = path.parse(dir).root;
|
|
55
|
-
while (dir !== root) {
|
|
56
|
-
if (fs.existsSync(path.join(dir, "rebase.json"))) return dir;
|
|
57
|
-
const pkgPath = path.join(dir, "package.json");
|
|
58
|
-
if (fs.existsSync(pkgPath)) {
|
|
59
|
-
try {
|
|
60
|
-
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
61
|
-
if (pkg.workspaces && Array.isArray(pkg.workspaces)) {
|
|
62
|
-
if (pkg.workspaces.some((w) => w === "backend")) return dir;
|
|
63
|
-
}
|
|
64
|
-
} catch {}
|
|
65
|
-
if (fs.existsSync(path.join(dir, "backend")) && fs.existsSync(path.join(dir, "config"))) return dir;
|
|
66
|
-
}
|
|
67
|
-
dir = path.dirname(dir);
|
|
68
|
-
}
|
|
69
|
-
return null;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Locate the backend directory within the project root.
|
|
73
|
-
*/
|
|
74
|
-
function findBackendDir(projectRoot) {
|
|
75
|
-
const backendDir = path.join(projectRoot, "backend");
|
|
76
|
-
return fs.existsSync(backendDir) ? backendDir : null;
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Detect the active backend plugin (e.g. @rebasepro/server-postgres) from the backend's package.json.
|
|
80
|
-
*/
|
|
81
|
-
function getActiveBackendPlugin(backendDir) {
|
|
82
|
-
const pkgPath = path.join(backendDir, "package.json");
|
|
83
|
-
if (!fs.existsSync(pkgPath)) return null;
|
|
84
|
-
try {
|
|
85
|
-
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
86
|
-
const deps = {
|
|
87
|
-
...pkg.dependencies,
|
|
88
|
-
...pkg.devDependencies
|
|
89
|
-
};
|
|
90
|
-
const candidates = Object.keys(deps).filter((dep) => dep.startsWith("@rebasepro/server-") && dep !== "@rebasepro/server");
|
|
91
|
-
if (candidates.length === 0) return null;
|
|
92
|
-
if (candidates.includes("@rebasepro/server-postgres")) return "@rebasepro/server-postgres";
|
|
93
|
-
for (const candidate of candidates) if (resolvePluginCliScript(backendDir, candidate)) return candidate;
|
|
94
|
-
return candidates[0];
|
|
95
|
-
} catch {}
|
|
96
|
-
return null;
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Resolve the active plugin's CLI script.
|
|
100
|
-
*/
|
|
101
|
-
function resolvePluginCliScript(backendDir, pluginName) {
|
|
102
|
-
const candidates = [];
|
|
103
|
-
let dir = path.resolve(backendDir);
|
|
104
|
-
const fsRoot = path.parse(dir).root;
|
|
105
|
-
while (dir !== fsRoot) {
|
|
106
|
-
candidates.push(path.join(dir, "node_modules", pluginName, "src", "cli.ts"), path.join(dir, "node_modules", pluginName, "dist", "cli.js"));
|
|
107
|
-
dir = path.dirname(dir);
|
|
108
|
-
}
|
|
109
|
-
candidates.push(path.resolve(backendDir, "..", "..", "..", "packages", pluginName.replace("@rebasepro/", ""), "src", "cli.ts"), path.resolve(backendDir, "..", "..", "packages", pluginName.replace("@rebasepro/", ""), "src", "cli.ts"), path.resolve(backendDir, "..", "packages", pluginName.replace("@rebasepro/", ""), "src", "cli.ts"));
|
|
110
|
-
for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
|
|
111
|
-
return null;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Locate the frontend directory within the project root.
|
|
115
|
-
*/
|
|
116
|
-
function findFrontendDir(projectRoot) {
|
|
117
|
-
const frontendDir = path.join(projectRoot, "frontend");
|
|
118
|
-
return fs.existsSync(frontendDir) ? frontendDir : null;
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Find the .env file. Checks the project root first, then backend.
|
|
122
|
-
*/
|
|
123
|
-
function findEnvFile(projectRoot) {
|
|
124
|
-
const candidates = [path.join(projectRoot, ".env"), path.join(projectRoot, "backend", ".env")];
|
|
125
|
-
for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
|
|
126
|
-
return null;
|
|
127
|
-
}
|
|
128
|
-
/**
|
|
129
|
-
* Read the project's `.env` into a plain object.
|
|
130
|
-
*
|
|
131
|
-
* One reader, because there were four: `dotenv` in `start`, a hand-rolled
|
|
132
|
-
* `indexOf("=")` loop in `api-keys`, a single-key regex in `auth`, and its own
|
|
133
|
-
* splitting in `cloud env`. `dotenv` is a declared dependency of this package,
|
|
134
|
-
* so the other three existed for no reason and disagreed with the correct one
|
|
135
|
-
* on the two things people actually write in a `.env`:
|
|
136
|
-
*
|
|
137
|
-
* - `export KEY=value`, which the hand-rolled parser keyed as
|
|
138
|
-
* `export KEY` — so the command reported the key as unset while it was
|
|
139
|
-
* right there in the file;
|
|
140
|
-
* - `KEY=value # comment`, whose comment travelled into the value and then
|
|
141
|
-
* into an `Authorization` header, coming back as a 401 with nothing
|
|
142
|
-
* pointing at the cause.
|
|
143
|
-
*
|
|
144
|
-
* Returns `{}` when the project has no `.env`, so callers can treat "absent"
|
|
145
|
-
* and "empty" alike.
|
|
146
|
-
*/
|
|
147
|
-
function readEnvFile(projectRoot) {
|
|
148
|
-
const envFile = findEnvFile(projectRoot);
|
|
149
|
-
if (!envFile || !fs.existsSync(envFile)) return {};
|
|
150
|
-
try {
|
|
151
|
-
return dotenv.parse(fs.readFileSync(envFile, "utf-8"));
|
|
152
|
-
} catch {
|
|
153
|
-
return {};
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
|
-
* Resolve a binary from the project's node_modules/.bin.
|
|
158
|
-
* Checks backend, root, parent monorepo root, then falls back to PATH.
|
|
159
|
-
*/
|
|
160
|
-
function resolveLocalBin(projectRoot, binName) {
|
|
161
|
-
const candidates = [path.join(projectRoot, "backend", "node_modules", ".bin", binName), path.join(projectRoot, "node_modules", ".bin", binName)];
|
|
162
|
-
let parent = path.dirname(projectRoot);
|
|
163
|
-
const rootDir = path.parse(parent).root;
|
|
164
|
-
while (parent !== rootDir) {
|
|
165
|
-
candidates.push(path.join(parent, "node_modules", ".bin", binName));
|
|
166
|
-
parent = path.dirname(parent);
|
|
167
|
-
}
|
|
168
|
-
for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
|
|
169
|
-
try {
|
|
170
|
-
const globalPath = execSync(`which ${binName}`, { encoding: "utf-8" }).trim();
|
|
171
|
-
if (globalPath && fs.existsSync(globalPath)) return globalPath;
|
|
172
|
-
} catch {}
|
|
173
|
-
return null;
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* Resolve the tsx binary. Checks backend node_modules first, then root.
|
|
177
|
-
*/
|
|
178
|
-
function resolveTsx(projectRoot) {
|
|
179
|
-
return resolveLocalBin(projectRoot, "tsx");
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* tsx's loader, as the URL `node --import` takes, or null when none resolves.
|
|
183
|
-
*
|
|
184
|
-
* For running a TypeScript entry in one Node process. The `tsx` binary is a
|
|
185
|
-
* relay — pnpm's `.bin/tsx` shell shim, then tsx's CLI in one Node, which
|
|
186
|
-
* spawns a second Node with this same loader to run the script — so spawning
|
|
187
|
-
* through it costs a shell and a Node start (~50–100 ms) on every hop, and
|
|
188
|
-
* `rebase dev` pays a hop on every start and every collection save.
|
|
189
|
-
*
|
|
190
|
-
* Resolved the way Node resolves the package, from the project first — the
|
|
191
|
-
* backend, where a scaffold declares tsx, then the root and everything above it
|
|
192
|
-
* — so the tsx used is the one {@link resolveTsx} would have found; then from
|
|
193
|
-
* this package, as the repository's own tests resolve `tsx/cli`. A URL rather
|
|
194
|
-
* than a path: a Windows path is not a valid `--import` specifier.
|
|
195
|
-
*/
|
|
196
|
-
function resolveTsxLoader(projectRoot) {
|
|
197
|
-
const bases = [
|
|
198
|
-
path.join(projectRoot, "backend", "noop.js"),
|
|
199
|
-
path.join(projectRoot, "noop.js"),
|
|
200
|
-
import.meta.url
|
|
201
|
-
];
|
|
202
|
-
for (const base of bases) try {
|
|
203
|
-
return pathToFileURL(createRequire(base).resolve("tsx")).href;
|
|
204
|
-
} catch {}
|
|
205
|
-
return null;
|
|
206
|
-
}
|
|
207
|
-
/**
|
|
208
|
-
* Validate that a resolved tsx binary actually has an intact installation.
|
|
209
|
-
*
|
|
210
|
-
* `resolveLocalBin` only checks whether `node_modules/.bin/tsx` (a symlink)
|
|
211
|
-
* exists. If the pnpm content-addressable store was cleaned or a previous
|
|
212
|
-
* install was interrupted, the symlink can exist while critical files inside
|
|
213
|
-
* the tsx package (e.g. `dist/preflight.cjs`) are missing — causing a
|
|
214
|
-
* confusing MODULE_NOT_FOUND error at runtime.
|
|
215
|
-
*
|
|
216
|
-
* This function follows the symlink, walks up to find the tsx package root
|
|
217
|
-
* (`package.json` with `name: "tsx"`), and verifies that `dist/preflight.cjs`
|
|
218
|
-
* is present. Returns `null` when the installation looks healthy, or an
|
|
219
|
-
* error description string when it appears corrupted.
|
|
220
|
-
*/
|
|
221
|
-
function validateTsxInstallation(tsxBinPath) {
|
|
222
|
-
try {
|
|
223
|
-
const realPath = fs.realpathSync(tsxBinPath);
|
|
224
|
-
let dir = path.dirname(realPath);
|
|
225
|
-
const fsRoot = path.parse(dir).root;
|
|
226
|
-
for (let depth = 0; depth < 10 && dir !== fsRoot; depth++) {
|
|
227
|
-
const pkgPath = path.join(dir, "package.json");
|
|
228
|
-
if (fs.existsSync(pkgPath)) try {
|
|
229
|
-
if (JSON.parse(fs.readFileSync(pkgPath, "utf-8")).name === "tsx") {
|
|
230
|
-
const preflightPath = path.join(dir, "dist", "preflight.cjs");
|
|
231
|
-
if (!fs.existsSync(preflightPath)) return `tsx package at ${dir} is missing dist/preflight.cjs`;
|
|
232
|
-
return null;
|
|
233
|
-
}
|
|
234
|
-
} catch {}
|
|
235
|
-
dir = path.dirname(dir);
|
|
236
|
-
}
|
|
237
|
-
return null;
|
|
238
|
-
} catch (err) {
|
|
239
|
-
return `tsx binary symlink is broken: ${err instanceof Error ? err.message : String(err)}`;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* The one sentence a command says when the project's dependencies are missing.
|
|
244
|
-
*
|
|
245
|
-
* Six commands each had their own wording for the same state, and none of them
|
|
246
|
-
* named the remedy:
|
|
247
|
-
*
|
|
248
|
-
* ✗ Could not find CLI entry point for @rebasepro/server-postgres.
|
|
249
|
-
* ✗ Could not find tsx binary.
|
|
250
|
-
* ✗ Could not find tsx binary for backend.
|
|
251
|
-
*
|
|
252
|
-
* All three mean "you have not installed yet" — `getActiveBackendPlugin` has
|
|
253
|
-
* already read the driver out of `backend/package.json` by the time the first
|
|
254
|
-
* one fires, so the package is declared and simply not on disk, and `tsx` is a
|
|
255
|
-
* devDependency of every scaffold. But they read as *Rebase* being broken, and
|
|
256
|
-
* they name an internal path or a binary the developer never asked for rather
|
|
257
|
-
* than the command that fixes it. That is the whole of the failure someone sees
|
|
258
|
-
* on a fresh clone, where `node_modules/` is the one thing a checkout does not
|
|
259
|
-
* carry.
|
|
260
|
-
*
|
|
261
|
-
* So: one sentence, naming the package manager this project uses and the
|
|
262
|
-
* directory to run it in — the working directory is usually neither.
|
|
263
|
-
*/
|
|
264
|
-
function dependenciesNotInstalled(projectRoot) {
|
|
265
|
-
return `Dependencies are not installed — run \`${getPMCommands(detectPackageManager(projectRoot)).install.join(" ")}\` in ${projectRoot}`;
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Print {@link dependenciesNotInstalled} and exit 1.
|
|
269
|
-
*
|
|
270
|
-
* For the five commands that report and stop. `db.ts` throws instead, because
|
|
271
|
-
* its caller adds the `✗` and the exit itself.
|
|
272
|
-
*/
|
|
273
|
-
function exitDependenciesNotInstalled(projectRoot) {
|
|
274
|
-
console.error(chalk.red(`✗ ${dependenciesNotInstalled(projectRoot)}`));
|
|
275
|
-
process.exit(1);
|
|
276
|
-
}
|
|
277
|
-
/**
|
|
278
|
-
* The refusal envelope, for a caller that asked for JSON.
|
|
279
|
-
*
|
|
280
|
-
* Same shape as the cloud family's `fail()` — `{ error: { message, code, hint } }`
|
|
281
|
-
* — because there is one CLI and a caller should not have to know which half of
|
|
282
|
-
* it answered. `code` is what a caller branches on and is never absent; the
|
|
283
|
-
* cloud family's reasoning about that applies here unchanged. `issues` carries
|
|
284
|
-
* the per-problem detail a human reader gets as a bullet list, because a
|
|
285
|
-
* refusal that says "2 problem(s)" and does not say which two is not
|
|
286
|
-
* machine-readable in any useful sense.
|
|
287
|
-
*
|
|
288
|
-
* On **stdout**, like every other `--json` result: the contract those commands
|
|
289
|
-
* make is that stdout holds one JSON value, and a caller that pipes stdout to a
|
|
290
|
-
* parser must get a parseable refusal rather than an empty stream and a
|
|
291
|
-
* human sentence it never sees. That contract used to hold for exactly one
|
|
292
|
-
* failure of each command — the one that goes through `requireProjectRoot` —
|
|
293
|
-
* while every other exit of the *same* command wrote human text to stderr and
|
|
294
|
-
* left stdout empty. So `rebase status --json` was parseable outside a project
|
|
295
|
-
* and unparseable inside a broken one, which is the case a caller actually has
|
|
296
|
-
* to handle.
|
|
297
|
-
*
|
|
298
|
-
* The flag is read off `process.argv` because the failure happens inside a
|
|
299
|
-
* helper the command calls before it has parsed anything. Coarse — a literal
|
|
300
|
-
* `--json` as some other flag's value would count — and worth it: the failure
|
|
301
|
-
* mode of being coarse is a JSON error where a human one was wanted, and the
|
|
302
|
-
* failure mode of not doing it is an unparseable stream.
|
|
303
|
-
*/
|
|
304
|
-
function failAsJson(message, code, hint, issues) {
|
|
305
|
-
const error = {
|
|
306
|
-
message,
|
|
307
|
-
code
|
|
308
|
-
};
|
|
309
|
-
if (hint !== void 0) error.hint = hint;
|
|
310
|
-
if (issues !== void 0) error.issues = issues;
|
|
311
|
-
console.log(JSON.stringify({ error }, null, 2));
|
|
312
|
-
process.exit(1);
|
|
313
|
-
}
|
|
314
|
-
/** Did the command line ask for machine-readable output? */
|
|
315
|
-
function wantsJsonOutput(argv = process.argv) {
|
|
316
|
-
return argv.includes("--json");
|
|
317
|
-
}
|
|
318
|
-
/**
|
|
319
|
-
* Require the project root or exit with a helpful error.
|
|
320
|
-
*/
|
|
321
|
-
function requireProjectRoot() {
|
|
322
|
-
const root = findProjectRoot();
|
|
323
|
-
if (!root) {
|
|
324
|
-
if (wantsJsonOutput()) failAsJson("Could not find a Rebase project root.", "no_project_root", `Looked in this directory and every parent for a ${MANIFEST_FILENAME}, a package.json with a "backend" workspace, or a backend/ next to a config/.`);
|
|
325
|
-
console.error(chalk.red("✗ Could not find a Rebase project root."));
|
|
326
|
-
console.error(chalk.gray(` Looked in this directory and every parent for a ${MANIFEST_FILENAME},`));
|
|
327
|
-
console.error(chalk.gray(" a package.json with a \"backend\" workspace, or a backend/ next to a config/."));
|
|
328
|
-
console.error(chalk.gray(" Run this from inside a project, or create one with `rebase init`."));
|
|
329
|
-
process.exit(1);
|
|
330
|
-
}
|
|
331
|
-
return root;
|
|
332
|
-
}
|
|
333
|
-
/**
|
|
334
|
-
* Require the backend directory or exit with a helpful error.
|
|
335
|
-
*/
|
|
336
|
-
function requireBackendDir(projectRoot) {
|
|
337
|
-
const backendDir = findBackendDir(projectRoot);
|
|
338
|
-
if (!backendDir) {
|
|
339
|
-
if (wantsJsonOutput()) failAsJson("Could not find a backend/ directory.", "no_backend_dir", `Expected at: ${path.join(projectRoot, "backend")}`);
|
|
340
|
-
console.error(chalk.red("✗ Could not find a backend/ directory."));
|
|
341
|
-
console.error(chalk.gray(` Expected at: ${path.join(projectRoot, "backend")}`));
|
|
342
|
-
process.exit(1);
|
|
343
|
-
}
|
|
344
|
-
return backendDir;
|
|
345
|
-
}
|
|
346
|
-
//#endregion
|
|
347
|
-
export { resolveTsxLoader as _, findBackendDir as a, findProjectRoot as c, readEnvFile as d, requireBackendDir as f, resolveTsx as g, resolvePluginCliScript as h, failAsJson as i, getActiveBackendPlugin as l, resolveLocalBin as m, dependenciesNotInstalled as n, findEnvFile as o, requireProjectRoot as p, exitDependenciesNotInstalled as r, findFrontendDir as s, MANIFEST_FILENAME as t, project_exports as u, validateTsxInstallation as v };
|
|
348
|
-
|
|
349
|
-
//# sourceMappingURL=project-Wp2zoyeN.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"project-Wp2zoyeN.js","names":[],"sources":["../src/utils/project.ts"],"sourcesContent":["/**\n * Project discovery utilities for the Rebase CLI.\n *\n * These helpers locate the project root, backend directory, .env file,\n * and local binaries — used by all CLI command modules.\n */\nimport fs from \"fs\";\nimport { createRequire } from \"module\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { execSync } from \"child_process\";\nimport dotenv from \"dotenv\";\nimport chalk from \"chalk\";\nimport { detectPackageManager, getPMCommands } from \"./package-manager\";\n\n/** The authored project manifest. Its presence alone marks a project root. */\nexport const MANIFEST_FILENAME = \"rebase.json\";\n\n/**\n * Walk up from `startDir` to find the Rebase project root.\n *\n * A directory is the root when it holds a `rebase.json`, or when it holds a\n * `package.json` that either lists `backend` as a workspace or sits beside both\n * `backend/` and `config/`.\n *\n * `rebase.json` is checked first and needs no `package.json` beside it, because\n * the conventions below all describe a repository that *contains the backend*.\n * A repository holding only a frontend — the normal shape once a project's apps\n * live in separate repositories — matches none of them, so without this the\n * tooling could not run there at all.\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n if (fs.existsSync(path.join(dir, MANIFEST_FILENAME))) {\n return dir;\n }\n\n const pkgPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n // Check for workspace-based project (monorepo root)\n if (pkg.workspaces && Array.isArray(pkg.workspaces)) {\n const hasBackend = pkg.workspaces.some((w: string) =>\n w === \"backend\"\n );\n if (hasBackend) return dir;\n }\n } catch {\n // ignore parse errors\n }\n\n // Check for sibling backend directory\n if (fs.existsSync(path.join(dir, \"backend\")) && fs.existsSync(path.join(dir, \"config\"))) {\n return dir;\n }\n }\n\n dir = path.dirname(dir);\n }\n\n return null;\n}\n\n/**\n * Locate the backend directory within the project root.\n */\nexport function findBackendDir(projectRoot: string): string | null {\n const backendDir = path.join(projectRoot, \"backend\");\n return fs.existsSync(backendDir) ? backendDir : null;\n}\n\n/**\n * Detect the active backend plugin (e.g. @rebasepro/server-postgres) from the backend's package.json.\n */\nexport function getActiveBackendPlugin(backendDir: string): string | null {\n const pkgPath = path.join(backendDir, \"package.json\");\n if (!fs.existsSync(pkgPath)) return null;\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const deps = { ...pkg.dependencies,\n...pkg.devDependencies };\n\n // Collect all @rebasepro/server-* driver plugins (exclude server itself)\n const candidates = Object.keys(deps).filter(\n dep => dep.startsWith(\"@rebasepro/server-\") && dep !== \"@rebasepro/server\"\n );\n\n if (candidates.length === 0) return null;\n\n // Prefer server-postgres — it's the primary supported driver\n if (candidates.includes(\"@rebasepro/server-postgres\")) {\n return \"@rebasepro/server-postgres\";\n }\n\n // Fallback: return the first candidate that actually has a CLI entry point\n for (const candidate of candidates) {\n if (resolvePluginCliScript(backendDir, candidate)) {\n return candidate;\n }\n }\n\n // Last resort: return whatever we found\n return candidates[0];\n } catch {\n // Ignore parse errors\n }\n return null;\n}\n\n/**\n * Resolve the active plugin's CLI script.\n */\nexport function resolvePluginCliScript(backendDir: string, pluginName: string): string | null {\n const candidates: string[] = [];\n\n // Walk up from the backend dir: pnpm links the plugin into\n // backend/node_modules, while npm workspaces hoist it to the project (or an\n // enclosing monorepo) root.\n let dir = path.resolve(backendDir);\n const fsRoot = path.parse(dir).root;\n while (dir !== fsRoot) {\n candidates.push(\n path.join(dir, \"node_modules\", pluginName, \"src\", \"cli.ts\"),\n path.join(dir, \"node_modules\", pluginName, \"dist\", \"cli.js\")\n );\n dir = path.dirname(dir);\n }\n\n candidates.push(\n // For monorepo dev mode:\n path.resolve(backendDir, \"..\", \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\")\n );\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Locate the frontend directory within the project root.\n */\nexport function findFrontendDir(projectRoot: string): string | null {\n const frontendDir = path.join(projectRoot, \"frontend\");\n return fs.existsSync(frontendDir) ? frontendDir : null;\n}\n\n/**\n * Find the .env file. Checks the project root first, then backend.\n */\nexport function findEnvFile(projectRoot: string): string | null {\n const candidates = [\n path.join(projectRoot, \".env\"),\n path.join(projectRoot, \"backend\", \".env\")\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n return null;\n}\n\n/**\n * Read the project's `.env` into a plain object.\n *\n * One reader, because there were four: `dotenv` in `start`, a hand-rolled\n * `indexOf(\"=\")` loop in `api-keys`, a single-key regex in `auth`, and its own\n * splitting in `cloud env`. `dotenv` is a declared dependency of this package,\n * so the other three existed for no reason and disagreed with the correct one\n * on the two things people actually write in a `.env`:\n *\n * - `export KEY=value`, which the hand-rolled parser keyed as\n * `export KEY` — so the command reported the key as unset while it was\n * right there in the file;\n * - `KEY=value # comment`, whose comment travelled into the value and then\n * into an `Authorization` header, coming back as a 401 with nothing\n * pointing at the cause.\n *\n * Returns `{}` when the project has no `.env`, so callers can treat \"absent\"\n * and \"empty\" alike.\n */\nexport function readEnvFile(projectRoot: string): Record<string, string> {\n const envFile = findEnvFile(projectRoot);\n if (!envFile || !fs.existsSync(envFile)) return {};\n try {\n return dotenv.parse(fs.readFileSync(envFile, \"utf-8\"));\n } catch {\n // An unreadable or malformed file is not worth failing a command over;\n // the caller reports the missing value it was looking for.\n return {};\n }\n}\n\n/**\n * Resolve a binary from the project's node_modules/.bin.\n * Checks backend, root, parent monorepo root, then falls back to PATH.\n */\nexport function resolveLocalBin(projectRoot: string, binName: string): string | null {\n const candidates = [\n path.join(projectRoot, \"backend\", \"node_modules\", \".bin\", binName),\n path.join(projectRoot, \"node_modules\", \".bin\", binName)\n ];\n\n // Also check parent directories (for monorepo setups where app/ is nested)\n let parent = path.dirname(projectRoot);\n const rootDir = path.parse(parent).root;\n while (parent !== rootDir) {\n candidates.push(path.join(parent, \"node_modules\", \".bin\", binName));\n parent = path.dirname(parent);\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n // Fall back to globally installed binary via which\n try {\n const globalPath = execSync(`which ${binName}`, { encoding: \"utf-8\" }).trim();\n if (globalPath && fs.existsSync(globalPath)) return globalPath;\n } catch {\n // not found globally\n }\n\n return null;\n}\n\n/**\n * Resolve the tsx binary. Checks backend node_modules first, then root.\n */\nexport function resolveTsx(projectRoot: string): string | null {\n return resolveLocalBin(projectRoot, \"tsx\");\n}\n\n/**\n * tsx's loader, as the URL `node --import` takes, or null when none resolves.\n *\n * For running a TypeScript entry in one Node process. The `tsx` binary is a\n * relay — pnpm's `.bin/tsx` shell shim, then tsx's CLI in one Node, which\n * spawns a second Node with this same loader to run the script — so spawning\n * through it costs a shell and a Node start (~50–100 ms) on every hop, and\n * `rebase dev` pays a hop on every start and every collection save.\n *\n * Resolved the way Node resolves the package, from the project first — the\n * backend, where a scaffold declares tsx, then the root and everything above it\n * — so the tsx used is the one {@link resolveTsx} would have found; then from\n * this package, as the repository's own tests resolve `tsx/cli`. A URL rather\n * than a path: a Windows path is not a valid `--import` specifier.\n */\nexport function resolveTsxLoader(projectRoot: string): string | null {\n const bases = [\n path.join(projectRoot, \"backend\", \"noop.js\"),\n path.join(projectRoot, \"noop.js\"),\n import.meta.url\n ];\n for (const base of bases) {\n try {\n return pathToFileURL(createRequire(base).resolve(\"tsx\")).href;\n } catch {\n // Not resolvable from here; try the next base.\n }\n }\n return null;\n}\n\n/**\n * Validate that a resolved tsx binary actually has an intact installation.\n *\n * `resolveLocalBin` only checks whether `node_modules/.bin/tsx` (a symlink)\n * exists. If the pnpm content-addressable store was cleaned or a previous\n * install was interrupted, the symlink can exist while critical files inside\n * the tsx package (e.g. `dist/preflight.cjs`) are missing — causing a\n * confusing MODULE_NOT_FOUND error at runtime.\n *\n * This function follows the symlink, walks up to find the tsx package root\n * (`package.json` with `name: \"tsx\"`), and verifies that `dist/preflight.cjs`\n * is present. Returns `null` when the installation looks healthy, or an\n * error description string when it appears corrupted.\n */\nexport function validateTsxInstallation(tsxBinPath: string): string | null {\n try {\n // Follow the symlink chain to the real tsx entry script\n const realPath = fs.realpathSync(tsxBinPath);\n\n // Walk up from the real binary to locate the tsx package root\n let dir = path.dirname(realPath);\n const fsRoot = path.parse(dir).root;\n for (let depth = 0; depth < 10 && dir !== fsRoot; depth++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg.name === \"tsx\") {\n // Found the tsx package root — verify critical preload file\n const preflightPath = path.join(dir, \"dist\", \"preflight.cjs\");\n if (!fs.existsSync(preflightPath)) {\n return `tsx package at ${dir} is missing dist/preflight.cjs`;\n }\n return null; // Installation looks healthy\n }\n } catch {\n // Malformed package.json — keep walking\n }\n }\n dir = path.dirname(dir);\n }\n\n // Could not determine tsx root — don't block, assume valid\n return null;\n } catch (err) {\n // realpathSync throws if the symlink target is completely gone\n return `tsx binary symlink is broken: ${err instanceof Error ? err.message : String(err)}`;\n }\n}\n\n/**\n * The one sentence a command says when the project's dependencies are missing.\n *\n * Six commands each had their own wording for the same state, and none of them\n * named the remedy:\n *\n * ✗ Could not find CLI entry point for @rebasepro/server-postgres.\n * ✗ Could not find tsx binary.\n * ✗ Could not find tsx binary for backend.\n *\n * All three mean \"you have not installed yet\" — `getActiveBackendPlugin` has\n * already read the driver out of `backend/package.json` by the time the first\n * one fires, so the package is declared and simply not on disk, and `tsx` is a\n * devDependency of every scaffold. But they read as *Rebase* being broken, and\n * they name an internal path or a binary the developer never asked for rather\n * than the command that fixes it. That is the whole of the failure someone sees\n * on a fresh clone, where `node_modules/` is the one thing a checkout does not\n * carry.\n *\n * So: one sentence, naming the package manager this project uses and the\n * directory to run it in — the working directory is usually neither.\n */\nexport function dependenciesNotInstalled(projectRoot: string): string {\n const install = getPMCommands(detectPackageManager(projectRoot)).install.join(\" \");\n return `Dependencies are not installed — run \\`${install}\\` in ${projectRoot}`;\n}\n\n/**\n * Print {@link dependenciesNotInstalled} and exit 1.\n *\n * For the five commands that report and stop. `db.ts` throws instead, because\n * its caller adds the `✗` and the exit itself.\n */\nexport function exitDependenciesNotInstalled(projectRoot: string): never {\n console.error(chalk.red(`✗ ${dependenciesNotInstalled(projectRoot)}`));\n process.exit(1);\n}\n\n/** One problem inside a refusal, when the command found several. */\nexport interface JsonFailureIssue {\n /** Where it is — a config path, a manifest key, a file. */\n path?: string;\n message: string;\n}\n\n/**\n * The refusal envelope, for a caller that asked for JSON.\n *\n * Same shape as the cloud family's `fail()` — `{ error: { message, code, hint } }`\n * — because there is one CLI and a caller should not have to know which half of\n * it answered. `code` is what a caller branches on and is never absent; the\n * cloud family's reasoning about that applies here unchanged. `issues` carries\n * the per-problem detail a human reader gets as a bullet list, because a\n * refusal that says \"2 problem(s)\" and does not say which two is not\n * machine-readable in any useful sense.\n *\n * On **stdout**, like every other `--json` result: the contract those commands\n * make is that stdout holds one JSON value, and a caller that pipes stdout to a\n * parser must get a parseable refusal rather than an empty stream and a\n * human sentence it never sees. That contract used to hold for exactly one\n * failure of each command — the one that goes through `requireProjectRoot` —\n * while every other exit of the *same* command wrote human text to stderr and\n * left stdout empty. So `rebase status --json` was parseable outside a project\n * and unparseable inside a broken one, which is the case a caller actually has\n * to handle.\n *\n * The flag is read off `process.argv` because the failure happens inside a\n * helper the command calls before it has parsed anything. Coarse — a literal\n * `--json` as some other flag's value would count — and worth it: the failure\n * mode of being coarse is a JSON error where a human one was wanted, and the\n * failure mode of not doing it is an unparseable stream.\n */\nexport function failAsJson(\n message: string,\n code: string,\n hint?: string,\n issues?: JsonFailureIssue[]\n): never {\n const error: Record<string, unknown> = { message, code };\n if (hint !== undefined) error.hint = hint;\n if (issues !== undefined) error.issues = issues;\n console.log(JSON.stringify({ error }, null, 2));\n process.exit(1);\n}\n\n/** Did the command line ask for machine-readable output? */\nexport function wantsJsonOutput(argv: readonly string[] = process.argv): boolean {\n return argv.includes(\"--json\");\n}\n\n/**\n * Require the project root or exit with a helpful error.\n */\nexport function requireProjectRoot(): string {\n const root = findProjectRoot();\n if (!root) {\n if (wantsJsonOutput()) {\n // `rebase status --json` outside a project wrote four grey lines to\n // stderr and nothing at all to stdout, so the agent or CI step that\n // asked for JSON got an empty parse and no reason.\n failAsJson(\n \"Could not find a Rebase project root.\",\n \"no_project_root\",\n `Looked in this directory and every parent for a ${MANIFEST_FILENAME}, `\n + \"a package.json with a \\\"backend\\\" workspace, or a backend/ next to a config/.\"\n );\n }\n // Name what is actually looked for, in the order `findProjectRoot`\n // looks for it. The old wording (\"backend/, frontend/, and config/\")\n // described neither the manifest — which is the primary marker and the\n // only one `rebase init` writes — nor a `--headless` project, which has\n // no frontend at all and would read this as \"you are in the wrong\n // place\" while standing in the right one.\n console.error(chalk.red(\"✗ Could not find a Rebase project root.\"));\n console.error(chalk.gray(` Looked in this directory and every parent for a ${MANIFEST_FILENAME},`));\n console.error(chalk.gray(\" a package.json with a \\\"backend\\\" workspace, or a backend/ next to a config/.\"));\n console.error(chalk.gray(\" Run this from inside a project, or create one with `rebase init`.\"));\n process.exit(1);\n }\n return root;\n}\n\n/**\n * Require the backend directory or exit with a helpful error.\n */\nexport function requireBackendDir(projectRoot: string): string {\n const backendDir = findBackendDir(projectRoot);\n if (!backendDir) {\n if (wantsJsonOutput()) {\n failAsJson(\n \"Could not find a backend/ directory.\",\n \"no_backend_dir\",\n `Expected at: ${path.join(projectRoot, \"backend\")}`\n );\n }\n console.error(chalk.red(\"✗ Could not find a backend/ directory.\"));\n console.error(chalk.gray(` Expected at: ${path.join(projectRoot, \"backend\")}`));\n process.exit(1);\n }\n return backendDir;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,oBAAoB;;;;;;;;;;;;;;AAejC,SAAgB,gBAAgB,WAAmB,QAAQ,IAAI,GAAkB;CAC7E,IAAI,MAAM,KAAK,QAAQ,QAAQ;CAC/B,MAAM,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC;CAE7B,OAAO,QAAQ,MAAM;EACjB,IAAI,GAAG,WAAW,KAAK,KAAK,KAAA,aAAsB,CAAC,GAC/C,OAAO;EAGX,MAAM,UAAU,KAAK,KAAK,KAAK,cA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I,yCAAyC,CAAC;EAClE,QAAQ,MAAM,MAAM,KAAK,qDAAqD,kBAAkB,EAAE,CAAC;EACnG,QAAQ,MAAM,MAAM,KAAK,iFAAiF,CAAC;EAC3G,QAAQ,MAAM,MAAM,KAAK,qEAAqE,CAAC;EAC/F,QAAQ,KAAK,CAAC;CAClB;CACA,OAAO;AACX;;;;AAKA,SAAgB,kBAAkB,aAA6B;CAC3D,MAAM,aAAa,eAAe,WAAW;CAC7C,IAAI,CAAC,YAAY;EACb,IAAI,gBAAgB,GAChB,WACI,wCACA,kBACA,gBAAgB,KAAK,KAAK,aAAa,SAAS,GACpD;EAEJ,QAAQ,MAAM,MAAM,IAAI,wCAAwC,CAAC;EACjE,QAAQ,MAAM,MAAM,KAAK,kBAAkB,KAAK,KAAK,aAAa,SAAS,GAAG,CAAC;EAC/E,QAAQ,KAAK,CAAC;CAClB;CACA,OAAO;AACX"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pull-C3PXduzl.js","names":[],"sources":["../src/dev-db/pull.ts"],"sourcesContent":["/**\n * `rebase db pull` — copy a database's contents into local development.\n *\n * The common case is production into local, and the reason it exists is that\n * the alternative is worse: without it people hand-roll a `pg_dump | psql` and\n * get the flags wrong in ways that either fail loudly at 2am or, more often,\n * quietly restore half a schema.\n *\n * Three things this command insists on, because copying a production database\n * onto a laptop is a data-protection event whether or not anyone calls it one:\n *\n * 1. **It says what it is about to do, in full, before doing it** — which\n * database it will read, which one it will overwrite, and where the data will\n * come to rest on disk. The target path matters: people forget that\n * `.rebase/pgdata` is a directory their backup software may be indexing.\n *\n * 2. **It refuses to run unattended without being told to.** The target is\n * destroyed, so a mistyped `--from` with no confirmation would take the\n * developer's working database with it.\n *\n * 3. **It will not write to a remote database.** The target is always the local\n * development database; there is no flag that makes this push. A tool that\n * can copy in both directions eventually copies in the wrong one.\n *\n * Anonymization is opt-in (`--anonymize`), which is a deliberate choice and not\n * an obviously safe one — the flag nobody types is the flag nobody gets. It is\n * a best-effort pass over columns whose *names* look like personal data, and\n * {@link ANONYMIZE_PATTERNS} says exactly which. It cannot find personal data in\n * a column called `notes`, and this file says so rather than implying a\n * guarantee it cannot keep.\n *\n * What it does guarantee is that it never half-happens: {@link anonymizeCopy}\n * runs the pass in one transaction, and when the pass fails it empties the\n * tables it would have rewritten rather than leave their real values behind.\n */\n\nimport { execa } from \"execa\";\nimport fs from \"fs\";\nimport type { Client } from \"pg\";\n\nimport { banner, connectionErrorText, hostOf } from \"./connection-banner\";\nimport { PGLITE_EXTENSIONS } from \"./constraints\";\n\n/**\n * How one kind of personal-looking column is overwritten.\n *\n * Two forms, because a constant is the most readable replacement and is wrong\n * for exactly one kind of column: a unique one. Every `token_hash` becoming\n * `'REDACTED'` is what `UNIQUE(token_hash)` refused on the second row of\n * `rebase.refresh_tokens` — so on any project where someone had signed in twice.\n */\nexport interface AnonymizeRule {\n pattern: RegExp;\n /**\n * Only on tables whose name matches, when set. For a column name that is\n * personal on one table and not on another: a user's `name` is a person's,\n * a tag's is not.\n */\n tables?: RegExp;\n /** The value for a column no unique index covers, or null to always use the unique form. */\n value: string | null;\n /** The unique form is `prefix` + random hex + `suffix`, cut to fit the column. */\n prefix: string;\n suffix: string;\n}\n\n/**\n * Tables whose rows are people, by name: `rebase.users` and the usual spellings\n * of a project's own. Singular or plural.\n */\nconst PERSON_TABLES = /^(users?|user_profiles?|profiles?|people|persons?|members?|customers?|contacts?|employees?)$/i;\n\n/**\n * Column-name patterns the anonymizer overwrites.\n *\n * Names, not contents: inspecting values would be slower, and would still miss\n * the same things. This is a reasonable-effort measure for making a local copy\n * less dangerous, and it is not a compliance control.\n */\nexport const ANONYMIZE_PATTERNS: readonly AnonymizeRule[] = [\n // Emails are unique in practice even where nothing enforces it, so they\n // always get a value of their own.\n { pattern: /^(.*_)?e?mail(_.*)?$/i, value: null, prefix: \"user-\", suffix: \"@example.invalid\" },\n { pattern: /^(.*_)?(phone|mobile|tel|telephone)(_.*)?$/i, value: \"+10000000000\", prefix: \"+1-\", suffix: \"\" },\n // `display_name` is how `rebase.users` holds every user's name.\n {\n pattern: /^(.*_)?(display_name|first_name|last_name|full_name|middle_name|family_name|surname|given_name)(_.*)?$/i,\n value: \"Redacted\",\n prefix: \"Redacted-\",\n suffix: \"\"\n },\n // A bare `name` is a person's only on a table of people.\n { pattern: /^name$/i, tables: PERSON_TABLES, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(address|street|postcode|zip|zipcode)(_.*)?$/i, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(ssn|tax_id|national_id|passport)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(password|password_hash|secret|token|api_key|access_token|refresh_token)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(ip|ip_address|user_agent)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" }\n];\n\n/** The rule that overwrites this column, if any. Without a table, a table-bound rule never applies. */\nfunction ruleFor(columnName: string, table?: string): AnonymizeRule | undefined {\n return ANONYMIZE_PATTERNS.find((rule) =>\n rule.pattern.test(columnName) && (!rule.tables || (table !== undefined && rule.tables.test(table))));\n}\n\nexport function shouldAnonymize(columnName: string, table?: string): boolean {\n return ruleFor(columnName, table) !== undefined;\n}\n\n/** A text-ish column the anonymizer can overwrite without a type error. */\nexport interface ColumnRef {\n schema: string;\n table: string;\n column: string;\n dataType: string;\n /** `character_maximum_length`: null or absent for an unbounded type. */\n maxLength?: number | null;\n /** Covered by a unique index — a primary key, a UNIQUE constraint, or a unique expression index. */\n unique?: boolean;\n}\n\n/** Random hex of this length, per row. `gen_random_uuid()` is core since PostgreSQL 13. */\nfunction randomHex(length: number): string {\n return `left(replace(gen_random_uuid()::text, '-', ''), ${length})`;\n}\n\nfunction sqlLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Fewest random hex digits a unique replacement keeps. Twelve is 16^12 values:\n * a collision needs millions of rows, where eight would need tens of thousands.\n */\nconst MIN_UNIQUE_HEX = 12;\n\n/**\n * The SQL expression that overwrites one column, or null when no rule names it.\n *\n * Unique per row when an index makes the column unique, and always cut to the\n * column's declared length — `zip char(5)` refused `'Redacted'` outright, and a\n * failed statement now empties the tables rather than skip one. To fit a short\n * unique column the prefix goes first, then the suffix, and the random part is\n * kept to at least {@link MIN_UNIQUE_HEX} digits while there is room for them.\n * A NULL stays NULL: an empty optional field is not personal data.\n */\nexport function replacementFor(column: ColumnRef): string | null {\n const rule = ruleFor(column.column, column.table);\n if (!rule) return null;\n const limit = typeof column.maxLength === \"number\" && column.maxLength > 0 ? column.maxLength : null;\n\n let value: string;\n if (rule.value !== null && !column.unique) {\n value = sqlLiteral(limit === null ? rule.value : rule.value.slice(0, limit));\n } else {\n const shapes = [[rule.prefix, rule.suffix], [\"\", rule.suffix], [\"\", \"\"]];\n const fitting = shapes.find(([prefix, suffix]) =>\n limit === null || limit - prefix.length - suffix.length >= MIN_UNIQUE_HEX);\n const [prefix, suffix] = fitting ?? [\"\", \"\"];\n const hex = Math.min(32, limit === null ? 32 : limit - prefix.length - suffix.length);\n value = `concat(${sqlLiteral(prefix)}, ${randomHex(Math.max(1, hex))}, ${sqlLiteral(suffix)})`;\n }\n\n const name = quoteIdentifier(column.column);\n return `CASE WHEN ${name} IS NULL THEN NULL ELSE ${value} END`;\n}\n\n/** A double-quoted identifier, with any `\"` in it doubled — a table called `order` or `a\"b` still works. */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Anonymizable columns: name looks personal, and the type can hold the\n * replacement.\n *\n * The type check is what stops this generating `UPDATE … SET user_id =\n * 'Redacted'` for an integer column called `user_id_email_seq` and failing the\n * whole pass on a technicality.\n */\nexport function anonymizableColumns(columns: readonly ColumnRef[]): ColumnRef[] {\n const textual = new Set([\"text\", \"character varying\", \"varchar\", \"character\", \"char\", \"citext\"]);\n\n return columns.filter((column) =>\n shouldAnonymize(column.column, column.table) && textual.has(column.dataType.toLowerCase()));\n}\n\n/** `\"schema\".\"table\"` for each table the pass rewrites, sorted. */\nexport function anonymizedTables(columns: readonly ColumnRef[]): string[] {\n return [...new Set(anonymizableColumns(columns).map((column) =>\n `${quoteIdentifier(column.schema)}.${quoteIdentifier(column.table)}`))].sort();\n}\n\n/** `UPDATE` statements for one anonymization pass, in a stable order. */\nexport function anonymizeStatements(columns: readonly ColumnRef[]): string[] {\n const byTable = new Map<string, ColumnRef[]>();\n for (const column of anonymizableColumns(columns)) {\n const key = `${quoteIdentifier(column.schema)}.${quoteIdentifier(column.table)}`;\n byTable.set(key, [...(byTable.get(key) ?? []), column]);\n }\n\n return [...byTable.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([table, cols]) => {\n const assignments = [...cols]\n .sort((a, b) => a.column.localeCompare(b.column))\n .map((column) => `${quoteIdentifier(column.column)} = ${replacementFor(column)}`)\n .join(\", \");\n\n return `UPDATE ${table} SET ${assignments};`;\n });\n}\n\n/**\n * Every column the pass could overwrite, with what decides how.\n *\n * Base tables only — a view has an `email` column too, and is not something to\n * UPDATE. Generated columns are skipped for the same reason: `email_domain\n * GENERATED ALWAYS AS (…)` matches by name and refuses any value but DEFAULT,\n * and it follows the column it is generated from anyway. An extension type such\n * as `citext` reports `USER-DEFINED`, so its own name is what is compared.\n *\n * `unique` comes from the indexes, through `pg_depend` as well as `indkey`: a\n * unique index on `lower(email)` names no column in `indkey`, and is exactly\n * what a constant replacement would violate.\n */\nexport const ANONYMIZE_COLUMNS_SQL = `\nWITH unique_columns AS (\n SELECT DISTINCT i.indrelid AS relid, a.attname AS column_name\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum > 0 AND NOT a.attisdropped\n WHERE i.indisunique\n AND (a.attnum = ANY (i.indkey)\n OR EXISTS (SELECT 1 FROM pg_depend d\n WHERE d.classid = 'pg_class'::regclass AND d.objid = i.indexrelid\n AND d.refclassid = 'pg_class'::regclass AND d.refobjid = i.indrelid\n AND d.refobjsubid = a.attnum))\n)\nSELECT c.table_schema AS \"schema\",\n c.table_name AS \"table\",\n c.column_name AS \"column\",\n CASE WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name ELSE c.data_type END AS \"dataType\",\n c.character_maximum_length AS \"maxLength\",\n (u.column_name IS NOT NULL) AS \"unique\"\n FROM information_schema.columns c\n JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name\n LEFT JOIN unique_columns u\n ON u.relid = format('%I.%I', c.table_schema, c.table_name)::regclass AND u.column_name = c.column_name\n WHERE t.table_type = 'BASE TABLE'\n AND c.is_generated = 'NEVER'\n AND c.table_schema NOT IN ('pg_catalog', 'information_schema')`;\n\n/** How {@link anonymizeCopy} ended. */\nexport type AnonymizeOutcome =\n | { ok: true; tables: string[] }\n | {\n ok: false;\n /** Why the pass failed. Nothing it wrote was kept. */\n error: string;\n /** The tables emptied instead, so none of their real values are left. */\n emptied: string[];\n /** Why they could not be emptied, when they could not: the copy then holds real data. */\n emptyError: string | null;\n };\n\nfunction errorText(error: unknown): string {\n return error instanceof Error && error.message ? error.message : String(error);\n}\n\n/**\n * Overwrite the personal-looking columns of a restored copy, all or nothing.\n *\n * One transaction, so a failure part-way leaves no table half done — the old\n * pass ran its UPDATEs one by one, so a failure on `rebase.refresh_tokens` left\n * `public.authors` anonymized and `rebase.users` holding every real email.\n *\n * A rollback alone would be worse than that, though: it puts back the real\n * value of every column, in a copy the developer asked to be anonymized. So on\n * failure the tables the pass would have rewritten are emptied (`TRUNCATE …\n * CASCADE`, which takes the rows that reference them too), and the outcome\n * says which — or, if even that failed, says the copy holds real data, so the\n * caller can say it louder.\n *\n * `row_security = off` makes a role that RLS would filter fail the pass instead\n * of rewriting only the rows its policies show it, which looked like success.\n */\nexport async function anonymizeCopy(client: Client): Promise<AnonymizeOutcome> {\n let listed = false;\n let tables: string[] = [];\n try {\n const { rows } = await client.query<ColumnRef>(ANONYMIZE_COLUMNS_SQL);\n tables = anonymizedTables(rows);\n listed = true;\n await client.query(\"BEGIN\");\n await client.query(\"SET LOCAL row_security = off\");\n for (const statement of anonymizeStatements(rows)) await client.query(statement);\n await client.query(\"COMMIT\");\n\n return { ok: true, tables };\n } catch (error) {\n const reason = errorText(error);\n await client.query(\"ROLLBACK\").catch(() => undefined);\n if (!listed) {\n return { ok: false, error: reason, emptied: [], emptyError: \"the tables to empty could not be listed\" };\n }\n if (tables.length === 0) return { ok: false, error: reason, emptied: [], emptyError: null };\n try {\n await client.query(`TRUNCATE TABLE ${tables.join(\", \")} CASCADE`);\n\n return { ok: false, error: reason, emptied: tables, emptyError: null };\n } catch (emptyError) {\n return { ok: false, error: reason, emptied: [], emptyError: errorText(emptyError) };\n }\n }\n}\n\n/**\n * Schemas the restored copy needs the app role provisioned on.\n *\n * `pg_dump --no-privileges` strips every GRANT, so a pulled database arrives\n * with its RLS policies and its `FORCE ROW LEVEL SECURITY` intact and no\n * privileges behind them. Measured on a 30-table project: 68 policies restored,\n * 14 tables with RLS on, and **0** grants to `rebase_user` — where the source\n * had 60. Reading one table as the role Rebase serves every request through:\n *\n * source: 6\n * copy: ERROR: permission denied for table leads\n *\n * The dump flags are right and stay: without `--no-owner`/`--no-privileges`\n * every `ALTER … OWNER TO` and `GRANT … TO <prod role>` in the dump fails\n * against roles that do not exist on a laptop, and buries the real output. The\n * repair belongs after the restore, and belongs to `ensureAppRole` — the same\n * routine boot and `rebase db push` call — rather than to a second list of\n * grants written here.\n *\n * Which schemas: every non-system schema the restored database actually has.\n * Boot knows its `managedSchemas` from the collections; a restore knows only\n * what arrived, and a source may carry schemas this project does not declare.\n * `pg_catalog`, `information_schema` and the `pg_*` internals are never ours to\n * grant on and PostgreSQL would refuse anyway.\n */\nexport function provisionableSchemas(rows: readonly { schema: string }[]): string[] {\n const skip = (name: string) => name === \"information_schema\" || name.startsWith(\"pg_\");\n\n return [...new Set(rows.map((row) => row.schema))].filter((name) => !skip(name)).sort();\n}\n\n/** Host and database of a connection string, with no credentials in it. */\nexport function describeTarget(connectionString: string): string {\n try {\n const url = new URL(connectionString);\n const database = url.pathname.replace(/^\\//, \"\") || \"(default)\";\n\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}/${database}`;\n } catch {\n // Never echo the raw string: it carries a password, and this line is\n // printed to a terminal people paste into issues.\n return \"(unparseable connection string)\";\n }\n}\n\n/**\n * What the local database runs on.\n *\n * `pglite` is the managed development database: one PGlite session behind a\n * socket server. Two things a restore relies on are not there. The server runs\n * each protocol message on its own, so the `CopyData` that follows a `COPY …\n * FROM stdin` never reaches the backend waiting for it: the COPY fails on\n * \"unexpected EOF\", and the session stops answering anyone until the daemon\n * is killed. And every connection shares that one session, so what pg_restore\n * `SET`s for itself stays set for everyone after it disconnects.\n */\nexport type PullTargetEngine = \"postgres\" | \"pglite\";\n\nexport interface PullPlan {\n /** Where the data comes from. */\n source: string;\n /** Where it lands. Always local. */\n target: string;\n anonymize: boolean;\n /** Schemas to copy. Empty means every non-system schema. */\n schemas: string[];\n /**\n * What the target runs on, which decides how the dump carries its rows.\n * Absent means `postgres`. {@link dumpSource} reads it off the target.\n */\n targetEngine?: PullTargetEngine;\n}\n\n/**\n * Rows per `INSERT` in a dump for the managed database.\n *\n * One per statement restored 100k rows in 8s; a hundred took 0.8s. A hundred\n * 512KB rows, a 100MB statement, still went in.\n */\nconst ROWS_PER_INSERT = 100;\n\n/**\n * `pg_dump` arguments for the source.\n *\n * `--no-owner` and `--no-acl` because the roles on a production server do not\n * exist locally, and without them every `ALTER … OWNER TO` in the dump fails and\n * buries the real output in noise. `--format=custom` so `pg_restore` can be told\n * to continue past errors selectively rather than all-or-nothing.\n *\n * For the managed database the rows travel as `INSERT`s, which PGlite takes\n * like any other statement, instead of `COPY` data, which it cannot take at\n * all — see {@link PullTargetEngine}. The copy is the same; only how the rows\n * are written in the dump differs.\n */\nexport function dumpArgs(plan: PullPlan): string[] {\n const args = [\"--format=custom\", \"--no-owner\", \"--no-acl\", \"--no-privileges\"];\n if (plan.targetEngine === \"pglite\") args.push(`--rows-per-insert=${ROWS_PER_INSERT}`);\n for (const schema of plan.schemas) args.push(\"--schema\", schema);\n args.push(\"--dbname\", splitPassword(plan.source).connectionString);\n\n return args;\n}\n\n/** The environment `pg_dump` runs with: the source's password, if it has one. */\nexport function dumpEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.source);\n}\n\n/** The environment `pg_restore` runs with: the target's password, if it has one. */\nexport function restoreEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.target);\n}\n\nfunction passwordEnv(connectionString: string): Record<string, string> {\n const { password } = splitPassword(connectionString);\n return password === null ? {} : { PGPASSWORD: password };\n}\n\n/**\n * A libpq connection string without its password, and the password.\n *\n * The password goes in `PGPASSWORD`, never on a command line, where every\n * process listing can read it and every failure prints it back (execa's error\n * repeats the command). The same rule `db backup` follows; this mirrors\n * `splitPassword` in `@rebasepro/server-postgres`'s connection-string utils,\n * which is not exported. Covers the user-info password and a `password=`\n * parameter; anything that does not parse as a postgres URL is left alone.\n */\nfunction splitPassword(connectionString: string): { connectionString: string; password: string | null } {\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n return { connectionString, password: null };\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return { connectionString, password: null };\n\n const fromUserInfo = url.password ? decodePercent(url.password) : null;\n const fromParameter = url.searchParams.get(\"password\");\n if (fromUserInfo === null && fromParameter === null) return { connectionString, password: null };\n\n url.password = \"\";\n if (fromParameter !== null) {\n url.searchParams.delete(\"password\");\n // By hand: URLSearchParams writes a space as `+`, which libpq reads literally.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n }\n return { connectionString: url.toString(), password: fromUserInfo ?? fromParameter };\n}\n\nfunction decodePercent(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * `pg_restore` arguments for the target.\n *\n * It restores into schemas {@link restoreCopy} has already emptied, so\n * `--clean --if-exists` drops nothing that is there; it stays for whatever a\n * dump holds outside them — an extension, say — which would otherwise fail as\n * already existing. `--no-owner` for the same reason as the dump.\n */\nexport function restoreArgs(plan: PullPlan, dumpFile: string): string[] {\n return [\"--clean\", \"--if-exists\", \"--no-owner\", \"--no-privileges\", \"--dbname\", splitPassword(plan.target).connectionString, dumpFile];\n}\n\n/**\n * Is this PostgreSQL client tool on PATH, and what version? Both are checked\n * before anything destructive: discovering `pg_restore` is missing after the\n * dump has been taken — or after `--clean` has emptied the target — is the\n * worst possible ordering.\n */\nexport async function findPgTool(tool: \"pg_dump\" | \"pg_restore\"): Promise<string | null> {\n try {\n const { stdout } = await execa(tool, [\"--version\"]);\n\n return stdout.trim();\n } catch {\n return null;\n }\n}\n\n/** PGlite names itself in `version()`: `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`. */\nfunction engineOf(version: string): PullTargetEngine {\n return /\\bPGlite\\b/i.test(version) ? \"pglite\" : \"postgres\";\n}\n\nconst NOTHING_CHANGED = \"Nothing was changed: the local database is as it was.\";\n\n/** What the target database runs on, or why it could not be asked. */\nasync function readTargetEngine(target: string): Promise<{ engine: PullTargetEngine } | { error: unknown }> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: target, connectionTimeoutMillis: 10_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n const { rows } = await client.query<{ version: string }>(\"SELECT version() AS version\");\n\n return { engine: engineOf(rows[0]?.version ?? \"\") };\n } catch (error) {\n return { error };\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/** How {@link dumpSource} ended. */\nexport type DumpOutcome =\n | {\n ok: true;\n /** The plan the dump was taken for, with its target's engine read: what {@link restoreCopy} takes. */\n plan: PullPlan;\n }\n | {\n ok: false;\n /** What failed and what to do, as plain lines for the caller to print. Nothing was changed. */\n lines: string[];\n };\n\n/**\n * `pg_dump` the source into `dumpFile`, in the form the target can restore.\n *\n * It asks the target what it runs on first — the managed database cannot take\n * `COPY` data, see {@link PullTargetEngine} — which also finds a local\n * database that is not there before anything is read from the source.\n *\n * pg_dump's stderr is kept rather than shown as it arrives, so a failure is\n * reported once, in the reader's terms: an unreachable source, or credentials\n * it refused, get the banner every database command prints for a connection\n * that failed, and anything else is pg_dump's own words with a line saying\n * nothing was changed. A dump that succeeds with warnings still shows them.\n * A dump that fails leaves no file behind.\n */\nexport async function dumpSource(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n try {\n const outcome = await dumpInto(plan, dumpFile);\n if (!outcome.ok) fs.rmSync(dumpFile, { force: true });\n\n return outcome;\n } catch (error) {\n fs.rmSync(dumpFile, { force: true });\n throw error;\n }\n}\n\nasync function dumpInto(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n let targetEngine = plan.targetEngine;\n if (!targetEngine) {\n const read = await readTargetEngine(plan.target);\n if (\"error\" in read) {\n return {\n ok: false,\n lines: banner(`Cannot connect to PostgreSQL at ${hostOf(plan.target)}`,\n `The driver said: ${connectionErrorText(read.error)}`, [\n \"That is the local database the pull would replace, and nothing\",\n \"was read from the source.\",\n \"Start it — `rebase dev` starts the managed one, `rebase dev --docker`\",\n \"Postgres in Docker — or check DATABASE_URL in .env, then pull again.\"\n ])\n };\n }\n targetEngine = read.engine;\n }\n\n const planned: PullPlan = { ...plan, targetEngine };\n const run = await execa(\"pg_dump\", [...dumpArgs(planned), \"--file\", dumpFile], {\n env: dumpEnv(planned),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"pipe\",\n reject: false\n });\n if (run.exitCode === 0) {\n if (run.stderr.trim()) process.stderr.write(`${run.stderr.trimEnd()}\\n`);\n\n return { ok: true, plan: planned };\n }\n\n return { ok: false, lines: describeDumpFailure(plan.source, run) };\n}\n\n/**\n * Why `pg_dump` could not read the source, as plain lines for the caller to\n * print. The dump is taken before anything local is touched, so every one of\n * them ends the same way: nothing was changed.\n */\nexport function describeDumpFailure(source: string, run: RestoreRun): string[] {\n if (run.signal) return [`✗ pg_dump was stopped by ${run.signal} before it finished.`, NOTHING_CHANGED];\n if (run.exitCode === undefined) {\n return [\n `✗ pg_dump could not be started (${run.code ?? \"unknown error\"}).`,\n NOTHING_CHANGED,\n \"Check that the PostgreSQL client tools are installed (`pg_dump --version`).\"\n ];\n }\n\n const stderr = (run.stderr ?? \"\").trim();\n const host = hostOf(source);\n const error = /pg_dump: error: (.+)/.exec(stderr)?.[1]?.trim() ?? null;\n const said = error ? `pg_dump said: ${error}` : null;\n\n if (/could not translate host name|could not connect to server|connection to server .* failed: (?:Connection refused|timeout expired|No route to host|Network is unreachable|Operation timed out|Host is down)/i.test(stderr)) {\n return banner(`Cannot connect to PostgreSQL at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the host and port in --from, and that this machine can reach\",\n \"that server: a VPN, an allow-list, or an SSH tunnel.\"\n ]);\n }\n if (/password authentication failed|no pg_hba\\.conf entry|role \"[^\"]+\" does not exist/i.test(stderr)) {\n let user = \"unknown\";\n try {\n user = decodePercent(new URL(source).username) || \"unknown\";\n } catch { /* named as unknown */ }\n return banner(`Authentication failed for user \"${user}\" at ${host}`, said, [\n \"PostgreSQL rejected the credentials --from carries.\",\n NOTHING_CHANGED,\n \"Check the user and password in --from.\"\n ]);\n }\n // The server answered and has no database of that name: a typo in\n // --from, usually, or a database not created yet.\n const missing = /database \"([^\"]+)\" does not exist/i.exec(stderr)?.[1];\n if (missing) {\n return banner(`Database \"${missing}\" does not exist at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the database name in --from.\"\n ]);\n }\n\n const versions = /server version mismatch/i.test(stderr)\n ? [\"pg_dump is older than the server: install client tools at least as new as it (`brew install libpq`).\"]\n : [];\n return [\n ...(stderr ? stderr.split(\"\\n\") : []),\n `✗ pg_dump could not dump ${describeTarget(source)} (exit code ${run.exitCode}).`,\n NOTHING_CHANGED,\n ...versions\n ];\n}\n\n/** The fields of a finished `pg_restore` (or `pg_dump`) run that decide {@link restoreOutcome}. */\nexport interface RestoreRun {\n exitCode?: number;\n signal?: string;\n /** A spawn failure's code — `ENOENT` when the binary vanished. */\n code?: string;\n stderr?: string;\n}\n\n/** What a `pg_restore` run says about the copy. */\nexport interface RestoreRunOutcome {\n /** Whether anything can have arrived — what decides whether an anonymization pass has data to redact. */\n started: boolean;\n /** Null when the copy is complete. */\n failure: string | null;\n /**\n * What to do about the failure. \"Pull again\" only where a second pull is\n * what finishes the job: everything else repeats until its cause is fixed.\n */\n advice: string | null;\n}\n\n/**\n * What a finished `pg_restore` says about the copy.\n *\n * The target was emptied before anything was written, so every way this can\n * end short of exit 0 leaves a partial or empty local database, and none of\n * them may be reported as a copy. A non-zero exit is pg_restore saying it\n * skipped statements — \"errors ignored on restore: N\" — and whatever those\n * statements created (a table, its rows, an RLS policy) is missing locally.\n *\n * Restoring into an emptied database, those errors come from what the source\n * holds that this Postgres cannot create — an extension it does not have, a\n * feature of a newer server — and a second pull meets them again. So the\n * advice names that, rather than \"pull again\", which sent people in a loop.\n * On the managed database an extension cannot be installed at all, so the\n * advice there is Postgres in Docker.\n */\nexport function restoreOutcome(run: RestoreRun, engine: PullTargetEngine = \"postgres\"): RestoreRunOutcome {\n if (run.signal) {\n return {\n started: true,\n failure: `pg_restore was stopped by ${run.signal} before it finished.`,\n advice: \"It was interrupted, not refused: pull again to finish the copy.\"\n };\n }\n if (run.exitCode === undefined) {\n return {\n started: false,\n failure: `pg_restore could not be started (${run.code ?? \"unknown error\"}).`,\n advice: \"Check that the PostgreSQL client tools are installed (`pg_restore --version`), then pull again.\"\n };\n }\n if (run.exitCode === 0) return { started: true, failure: null, advice: null };\n\n const ignored = /errors ignored on restore: (\\d+)/.exec(run.stderr ?? \"\");\n const repeats = engine === \"pglite\"\n ? \"Pulling again repeats these errors until what they name is fixed — most often an extension the \"\n + `source uses that the managed database does not have (it has ${PGLITE_EXTENSIONS.map(extension => extension.name).join(\", \")}). `\n + \"Pull into Postgres in Docker instead (`rebase db pull --docker`), or pull only the schemas that do \"\n + \"not need it (--schema).\"\n : \"Pulling again repeats these errors until what they name is fixed — most often an extension \"\n + \"the source uses that this Postgres does not have installed. Install it here, or pull only the schemas \"\n + \"that do not need it (--schema).\";\n\n return {\n started: true,\n failure: ignored\n ? `pg_restore could not restore ${ignored[1]} object(s) — the errors are above.`\n : `pg_restore exited with code ${run.exitCode} — the errors are above.`,\n advice: repeats\n };\n}\n\n/** How {@link restoreCopy} ended. */\nexport interface RestoreOutcome extends RestoreRunOutcome {\n /** Whether the local database was emptied first. False means it is exactly as it was. */\n cleared: boolean;\n}\n\n/**\n * The local schemas a pull empties before it restores: every one of the local\n * database's own for a whole-database pull, and those it copies for a\n * `--schema` pull. `pg_catalog`, `information_schema` and the `pg_*` internals\n * never — see {@link provisionableSchemas}.\n */\nexport function schemasToClear(present: readonly { schema: string }[], planned: readonly string[]): string[] {\n const local = provisionableSchemas(present);\n\n return planned.length === 0 ? local : local.filter((schema) => planned.includes(schema));\n}\n\n/**\n * The statements that empty those schemas, in one transaction.\n *\n * `CASCADE`, which `pg_restore --clean` never uses: a table the source lacks —\n * `rebase.atlas_schema_revisions` from `rebase db migrate`, a collection added\n * locally that references a pulled table — is exactly what blocked its plain\n * `DROP SCHEMA` and `DROP TABLE`. `public` is put back empty, with the access\n * every role has to it by default, because a dump does not create a default\n * `public` and every table in it would otherwise have nowhere to go.\n */\nexport function clearStatements(schemas: readonly string[]): string[] {\n const statements = schemas.map((schema) => `DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`);\n if (schemas.includes(\"public\")) statements.push(\"CREATE SCHEMA public\", \"GRANT USAGE ON SCHEMA public TO PUBLIC\");\n\n return statements;\n}\n\n/**\n * How long emptying the local database waits for a lock before giving up.\n *\n * A `rebase dev` serving from the database holds connections, and one inside\n * a transaction would otherwise make the pull hang without a word.\n */\nconst CLEAR_LOCK_TIMEOUT = \"15s\";\n\n/** Why emptying the local database failed, in the reader's terms, and what fixes it. */\nfunction clearFailure(error: unknown): RestoreOutcome {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"\";\n const reason = errorText(error);\n const advice = code === \"55P03\"\n ? \"Something holds a lock on it — usually `rebase dev` serving from it. Stop that, then pull again.\"\n : code === \"42501\"\n ? \"This connection may not drop those schemas. Connect as the role that owns them — the one \"\n + \"that created them — and pull with that.\"\n : \"Fix what the error names; pulling again before that repeats it.\";\n\n return {\n cleared: false,\n started: false,\n failure: `Could not empty the local database before restoring: ${reason}`,\n advice\n };\n}\n\n/**\n * Replace the local database's contents with a dump: empty the schemas it\n * holds, then `pg_restore` into them.\n *\n * Only ever `plan.target`, the local development database the command\n * resolved — the pull's one destination, which no flag can change. Emptying it\n * is one transaction: if any schema cannot be dropped, none is, nothing is\n * restored, and the database is as it was.\n *\n * On the managed database the dump must be one {@link dumpSource} took for it,\n * with its rows as INSERTs: a COPY would leave the daemon answering nobody, so\n * one is refused before anything is emptied. And afterwards its one session —\n * every connection's — is given back its own settings: pg_restore leaves\n * `search_path` empty and `row_security` off behind it, which a running\n * `rebase dev` would otherwise query under.\n */\nexport async function restoreCopy(plan: PullPlan, dumpFile: string): Promise<RestoreOutcome> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: plan.target });\n client.on(\"error\", () => undefined);\n let engine: PullTargetEngine;\n try {\n await client.connect();\n engine = engineOf((await client.query<{ version: string }>(\"SELECT version() AS version\")).rows[0]?.version ?? \"\");\n if (engine === \"pglite\" && plan.targetEngine !== \"pglite\") {\n return {\n cleared: false,\n started: false,\n failure: \"The managed development database cannot take this dump: its rows are COPY data, which PGlite's socket server cannot receive.\",\n advice: \"Pull into Postgres in Docker instead: `rebase db pull --docker`.\"\n };\n }\n const { rows } = await client.query<{ schema: string }>(\"SELECT nspname AS \\\"schema\\\" FROM pg_namespace\");\n await client.query(\"BEGIN\");\n await client.query(`SET LOCAL lock_timeout = '${CLEAR_LOCK_TIMEOUT}'`);\n for (const statement of clearStatements(schemasToClear(rows, plan.schemas))) await client.query(statement);\n await client.query(\"COMMIT\");\n } catch (error) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n return clearFailure(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n\n // stderr is shown as it arrives and kept, for the count in its summary\n // line. Not rejected: every way this ends is judged by `restoreOutcome`.\n const run = await execa(\"pg_restore\", restoreArgs(plan, dumpFile), {\n env: restoreEnv(plan),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: [\"pipe\", \"inherit\"],\n reject: false\n });\n\n if (engine === \"pglite\") await resetSharedSession(plan.target);\n\n return { cleared: true, ...restoreOutcome(run, engine) };\n}\n\n/**\n * Put the managed database's one session back to its own settings.\n *\n * `RESET ALL` and `DEALLOCATE ALL`, not `DISCARD ALL`: the session is every\n * connection's, and `DISCARD` would also drop the `LISTEN` a running\n * `rebase dev`'s realtime holds on it. The same pair the backup service runs\n * after its tools (`resetSharedSession` in server-postgres' backup-service). Best effort: a daemon that cannot take this cannot take the\n * re-grant that follows either, and that step reports it.\n */\nasync function resetSharedSession(target: string): Promise<void> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: target, connectionTimeoutMillis: 10_000, query_timeout: 15_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n await client.query(\"RESET ALL\");\n await client.query(\"DEALLOCATE ALL\");\n } catch {\n // Reported by the next step that connects; see above.\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * The lines that report a failed restore: what failed, what state the local\n * database is in now, and what to do. Plain text, for the caller to colour.\n */\nexport function describeRestoreFailure(outcome: RestoreOutcome, source: string): string[] {\n const state = outcome.started\n ? `The local database holds an incomplete copy of ${source}.`\n : outcome.cleared\n ? \"The local database was emptied, and nothing was restored into it.\"\n : \"Nothing was restored, and the local database is as it was.\";\n\n return [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"sources":["../src/commands/schema.ts"],"sourcesContent":["/**\n * CLI command: rebase schema <action>\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { ensureDockerDatabase, spawnDriverCli } from \"./db\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { recordEvent } from \"../telemetry\";\nimport { wantsHelp } from \"../utils/args\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport { absolutizeLocalPathArgs } from \"./db\";\nimport { COLLECTIONS_FLAG_HELP, refuseMissingCollectionsPath } from \"../utils/path-flags\";\n\n/**\n * The line handed to the driver, its paths resolved from where the command was\n * run (the driver runs in `backend/`). `--schema` is left alone: on\n * `introspect` it names a Postgres schema, not a file.\n */\nexport function schemaDriverArgs(rawArgs: string[], cwd: string): string[] {\n return absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"schema\"), cwd, [\"--collections\", \"-c\", \"--output\", \"-o\", \"--out\"]);\n}\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before `requireProjectRoot` and before the\n // driver is spawned — the same shape `db.ts` already uses, and for the same\n // reason.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase schema --help` was covered and `rebase schema generate\n // --help` was not: the flag travelled into `rawArgs.slice(2)` and reached\n // the driver, whose own `schemaCommand` has no `--help` case. It *ran the\n // generator* — overwriting `src/schema.generated.ts` — for a flag whose\n // entire job is to print text. Worse, the first thing it hit outside a\n // project was `requireProjectRoot`, so `rebase schema introspect --help` in\n // an empty directory exited 1 with \"Could not find a Rebase project root\":\n // help you cannot read until you already have a project is help for nobody.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printSchemaHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, in the same words every other family uses.\n //\n // It used to travel to the driver, which said the bare line `Unknown schema\n // command.` — no list, no pointer, no did-you-mean, for a family with three\n // subcommands. The set comes from the help table, so what a typo is measured\n // against and what `--help` prints cannot drift apart.\n if (!SCHEMA_ACTION_HELP[subcommand]) {\n unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), \"schema\");\n }\n\n const projectRoot = requireProjectRoot();\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.schema\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n // Which database this project is on, so the driver's closing line does not\n // recommend a command that database refuses. A pure decision — nothing is\n // started, which matters here above all: `schema generate` reads collection\n // files and writes one file, and booting a database to run it would be a\n // side effect nobody asked for.\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n refuseMissingCollectionsPath(rawArgs, process.cwd(), backendDir);\n\n // `introspect` is the one schema command that reads a database, and it\n // reads the project's — resolved the way every `db` command resolves it,\n // started if that is what it takes. It used to pass `.env` and nothing\n // else, so on the managed database or after `rebase dev --docker` (with\n // the scaffold's DATABASE_URL commented out, on purpose) it said\n // \"DATABASE_URL is not set\", and `--docker` and `--database-url` passed the\n // flag check only to be ignored.\n if (subcommand === \"introspect\") {\n const flags = arg(\n { \"--database-url\": String, \"--docker\": Boolean },\n { argv: rawArgs.slice(2), permissive: true }\n );\n await ensureDockerDatabase(projectRoot, rawArgs);\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n try {\n // The one spawn, shared with `db`. This file used to carry its own copy\n // of the tsx-or-node decision; three copies of that rule existed and two\n // were fixed while the third went on spawning plain node.\n await spawnDriverCli(\n { projectRoot, backendDir, pluginCli, env },\n schemaDriverArgs(rawArgs, process.cwd())\n );\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio; a child that never started (ENOENT on tsx,\n // EACCES on the script) printed nothing at all, and this used to exit 1\n // in silence.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/** One page per subcommand, so `rebase schema <action> --help` says something. */\nconst SCHEMA_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n generate: {\n usage: \"rebase schema generate [--collections <dir>] [--output <file>] [--watch]\",\n summary: \"Generate the Drizzle schema from the collection definitions.\",\n notes: [\"--watch regenerates on every change to a collection file.\"]\n },\n introspect: {\n usage: \"rebase schema introspect [--collections <dir>] [--output <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]\",\n summary: \"Read an existing database and write Rebase collection definitions from it.\",\n notes: [\n \"--force overwrites collection files that are already there.\",\n \"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; \"\n + \"--no-data-inference reads the structure only. Without either it asks, and without a terminal \"\n + \"it reads the structure only.\",\n \"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; \"\n + \"--docker uses the compose one, starting it if needed.\"\n ]\n },\n stale: {\n usage: \"rebase schema stale [--collections <dir>] [--output <file>] [--fix]\",\n summary: \"Report generated schema files that no longer match the collections.\",\n notes: [\"--fix regenerates them instead of only reporting.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);\n\nfunction printSchemaHelp(action?: string) {\n const entry = action ? SCHEMA_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase schema ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase schema --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n ${chalk.blue.bold(\"stale\")} Report generated schema files that no longer match the collections\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} ${COLLECTIONS_FLAG_HELP}\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n ${chalk.blue(\"--schema\")} Postgres schema to read (default: public)\n ${chalk.blue(\"--force, -f\")} Overwrite collection files that already exist\n ${chalk.blue(\"--database-url\")} Read this database instead of the project's own\n ${chalk.blue(\"--docker\")} Read the compose database, starting it if needed\n ${chalk.blue(\"--data-inference\")} Sample rows to detect formats and constraints ${chalk.gray(\"(asked when omitted)\")}\n ${chalk.blue(\"--no-data-inference\")} Read the structure only, without asking\n\n${chalk.green.bold(\"stale Options\")}\n ${chalk.blue(\"--fix\")} Regenerate the stale files instead of only reporting them\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,SAAgB,iBAAiB,SAAmB,KAAuB;CACvE,OAAO,wBAAwB,gBAAgB,SAAS,QAAQ,GAAG,KAAK;EAAC;EAAiB;EAAM;EAAY;EAAM;CAAO,CAAC;AAC9H;AAEA,eAAsB,cAAc,YAAgC,SAAkC;CAclG,IAAI,CAAC,cAAc,eAAe,YAAY,UAAU,OAAO,GAAG;EAC9D,gBAAgB,eAAe,WAAW,KAAA,IAAY,UAAU;EAChE;CACJ;CAQA,IAAI,CAAC,mBAAmB,aACpB,eAAe,YAAY,OAAO,KAAK,kBAAkB,GAAG,QAAQ;CAGxE,MAAM,cAAc,mBAAmB;CAKvC,YAAiB,cAAc,EAAE,YAAY,cAAc,OAAO,GAAG,EAAE,YAAY,CAAC;CACpF,MAAM,aAAa,kBAAkB,WAAW;CAEhD,MAAM,eAAe,uBAAuB,UAAU;CACtD,IAAI,CAAC,cAAc;EACf,QAAQ,MAAM,MAAM,IAAI,+CAA+C,CAAC;EACxE,QAAQ,MAAM,MAAM,KAAK,6FAA6F,CAAC;EACvH,QAAQ,KAAK,CAAC;CAClB;CAEA,MAAM,YAAY,uBAAuB,YAAY,YAAY;CACjE,IAAI,CAAC,WACD,6BAA6B,WAAW;CAI5C,MAAM,UAAU,YAAY,WAAW;CACvC,MAAM,MAA8B,EAAE,GAAG,QAAQ,IAA8B;CAC/E,IAAI,SACA,IAAI,qBAAqB;CAO7B,IAAI,yBAAyB,gBAAgB,WAAW,KAAK;CAE7D,6BAA6B,SAAS,QAAQ,IAAI,GAAG,UAAU;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