@rebasepro/cli 0.19.1-canary.gafb2f80 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -112,6 +112,36 @@ export declare function refuseAtlasOnManagedDatabase(rawArgs: string[], kind: st
112
112
  * cover. It does now.
113
113
  */
114
114
  export declare function refuseBranchOnManagedDatabase(rawArgs: string[], kind: string): void;
115
+ /**
116
+ * The one place this CLI spawns the driver's own CLI.
117
+ *
118
+ * There were three, each with its own copy of "tsx for a `.ts` entry, `node`
119
+ * otherwise". That rule was right only while the driver shipped `src/`; once it
120
+ * shipped `dist/cli.js` all three quietly switched to plain `node`, and the
121
+ * driver loads the PROJECT's TypeScript in process:
122
+ *
123
+ * - `schema stale` reads the collections, could not resolve `./authors` onto
124
+ * `authors.ts`, and answered "⏭ Not checked" while exiting 0;
125
+ * - `db push` does the same in `ensureAuthTables`, so `rebase.users` was never
126
+ * created and the push died at "Applying RLS policies" with
127
+ * `relation "rebase.users" does not exist` — on a virgin database, which is
128
+ * the documented bring-your-own-Postgres first run.
129
+ *
130
+ * Two were fixed and the third was missed, because three copies of a decision
131
+ * are three chances to miss one. There is one now, and a gate holds it at one.
132
+ *
133
+ * tsx whenever it is installed — a devDependency of every scaffold, for exactly
134
+ * this reason. Without it a `.ts` entry cannot run at all; a built entry still
135
+ * runs, and the subcommands that never touch the project's TypeScript still work.
136
+ */
137
+ export declare function spawnDriverCli(resolved: {
138
+ projectRoot: string;
139
+ backendDir: string;
140
+ pluginCli: string;
141
+ env: Record<string, string>;
142
+ }, childArgs: string[], options?: {
143
+ quiet?: boolean;
144
+ }): Promise<void>;
115
145
  /**
116
146
  * Run a `schema` subcommand through the active driver's CLI.
117
147
  *
@@ -28,6 +28,7 @@ var daemon_exports = /* @__PURE__ */ __exportAll({
28
28
  findRunningDaemon: () => findRunningDaemon,
29
29
  isDaemonAlive: () => isDaemonAlive,
30
30
  managedUrl: () => managedUrl,
31
+ pgliteLogTail: () => pgliteLogTail,
31
32
  resetManagedDatabase: () => resetManagedDatabase,
32
33
  resolveSpawn: () => resolveSpawn,
33
34
  stopManagedDatabase: () => stopManagedDatabase
@@ -60,6 +61,29 @@ var MANAGED_DATABASE = "postgres";
60
61
  * Putting it in the URL fixes every consumer at once — Atlas, `pg`, and anything
61
62
  * a driver shells out to later — rather than teaching each one about PGlite.
62
63
  */
64
+ /**
65
+ * The end of `pglite.log`, for an error message that has to carry its own reason.
66
+ *
67
+ * The daemon writes its output to a file because it is detached — it has to
68
+ * outlive the command that started it. That is right, and it means every
69
+ * startup failure used to be reported as a path: "see pglite.log for the
70
+ * reason". On a laptop that is a fair trade. In CI it is not a trade at all,
71
+ * because the runner discards the workspace: the log named in the message no
72
+ * longer exists by the time anybody reads the message, so a failed run says
73
+ * only that something failed.
74
+ *
75
+ * So the tail comes with the error. Bounded, because a log that has been
76
+ * appended to across many runs is not something to paste in full.
77
+ */
78
+ function pgliteLogTail(projectRoot, lines = 12) {
79
+ try {
80
+ const contents = fs.readFileSync(path.join(devDbDir(projectRoot), "pglite.log"), "utf8").trimEnd();
81
+ if (!contents) return " (pglite.log is empty — the daemon wrote nothing before exiting)";
82
+ return contents.split("\n").slice(-lines).map((line) => ` ${line}`).join("\n");
83
+ } catch {
84
+ return " (pglite.log could not be read)";
85
+ }
86
+ }
63
87
  function managedUrl(port) {
64
88
  return `postgresql://${MANAGED_USER}@127.0.0.1:${port}/${MANAGED_DATABASE}?sslmode=disable`;
65
89
  }
@@ -243,10 +267,10 @@ async function ensureManagedDatabase(projectRoot, options = {}) {
243
267
  announced = true;
244
268
  options.onProgress?.("Starting the development database…");
245
269
  }
246
- if (child.exitCode !== null && child.exitCode !== 0) throw new Error(`The development database failed to start (exit ${child.exitCode}).\n See ${path.join(devDbDir(projectRoot), "pglite.log")} for the reason.`);
270
+ if (child.exitCode !== null && child.exitCode !== 0) throw new Error(`The development database failed to start (exit ${child.exitCode}).\n ${path.join(devDbDir(projectRoot), "pglite.log")} ends:\n` + pgliteLogTail(projectRoot));
247
271
  await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
248
272
  }
249
- throw new Error(`The development database did not start within ${Math.round(START_TIMEOUT_MS / 1e3)}s.\n See ${path.join(devDbDir(projectRoot), "pglite.log")} for the reason.\n To use your own Postgres instead, set DATABASE_URL or pass --database-url.`);
273
+ throw new Error(`The development database did not start within ${Math.round(START_TIMEOUT_MS / 1e3)}s.\n ${path.join(devDbDir(projectRoot), "pglite.log")} ends:\n` + pgliteLogTail(projectRoot) + "\n To use your own Postgres instead, set DATABASE_URL or pass --database-url.");
250
274
  } finally {
251
275
  releaseStartLock(projectRoot);
252
276
  }
@@ -328,4 +352,4 @@ function ensureGitignore(projectRoot) {
328
352
  //#endregion
329
353
  export { managedUrl as i, ensureManagedDatabase as n, findRunningDaemon as r, daemon_exports as t };
330
354
 
331
- //# sourceMappingURL=daemon-YDZK9NZ1.js.map
355
+ //# sourceMappingURL=daemon-DR9Tk0La.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daemon-DR9Tk0La.js","names":[],"sources":["../src/dev-db/daemon.ts"],"sourcesContent":["/**\n * Starting, finding and stopping the managed database, from the caller's side.\n *\n * Every command that needs Postgres calls {@link ensureManagedDatabase} and\n * gets a connection string back. Whether that started a process or found one\n * already running is not the caller's business, which is the point: `rebase\n * db push`, `rebase dev` and `rebase studio` in three terminals must all reach\n * the same database without coordinating, because two processes opening one\n * PGlite data directory would corrupt it.\n *\n * The hard part is not starting the daemon; it is deciding whether the one the\n * state file describes is still there. A pid can be recycled after a reboot and\n * a port can be taken by a stranger, so believing either on its own would let\n * Rebase send a migration somewhere unintended. {@link isDaemonAlive} asks the\n * daemon to identify itself instead.\n */\n\nimport { randomBytes } from \"crypto\";\nimport { type ChildProcess, spawn } from \"child_process\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport {\n acquireStartLock,\n clearState,\n type DaemonState,\n dataDir,\n devDbDir,\n findFreePort,\n pidRunning,\n readState,\n releaseStartLock,\n stateFile\n} from \"./state\";\n\n/** How long to wait for a first boot. PGlite runs initdb on an empty data dir. */\nconst START_TIMEOUT_MS = 60_000;\n/** Poll interval while waiting for the daemon to publish its state file. */\nconst POLL_INTERVAL_MS = 150;\n/** How long the identity handshake may take before we call it dead. */\nconst IDENTITY_TIMEOUT_MS = 1_500;\n\nexport interface ManagedDatabase {\n /** Connection string for this project's managed database. */\n url: string;\n /** Where the data lives, for diagnostics and `--reset`. */\n dataDir: string;\n port: number;\n pid: number;\n /** True when this call started the daemon rather than finding it. */\n started: boolean;\n /**\n * Connection strings for the additional databases the caller asked for,\n * by declared key — `database(\"analytics\")` → `analytics`. Each is its\n * own PGlite instance behind the same daemon.\n */\n additional: Record<string, string>;\n}\n\n/**\n * PGlite's built-in superuser and database.\n *\n * Fixed by PGlite rather than chosen here, and asserted by the socket spike:\n * `session_user` comes back as `postgres`.\n */\nconst MANAGED_USER = \"postgres\";\nconst MANAGED_DATABASE = \"postgres\";\n\n/**\n * The DSN for the managed development database.\n *\n * **`sslmode=disable` is not decoration.** PGlite's socket server speaks no TLS,\n * and libpq-family clients try SSL first — so Atlas, which `rebase db push`\n * shells out to, failed the whole push with\n * `pq: SSL is not enabled on the server`. Its remedy box then told the reader to\n * append `sslmode=disable` to `DATABASE_URL`, which on this path is not set at\n * all: `rebase init` leaves it commented out precisely so the managed database\n * is used. The advice was correct and unfollowable.\n *\n * Putting it in the URL fixes every consumer at once — Atlas, `pg`, and anything\n * a driver shells out to later — rather than teaching each one about PGlite.\n */\n\n/**\n * The end of `pglite.log`, for an error message that has to carry its own reason.\n *\n * The daemon writes its output to a file because it is detached — it has to\n * outlive the command that started it. That is right, and it means every\n * startup failure used to be reported as a path: \"see pglite.log for the\n * reason\". On a laptop that is a fair trade. In CI it is not a trade at all,\n * because the runner discards the workspace: the log named in the message no\n * longer exists by the time anybody reads the message, so a failed run says\n * only that something failed.\n *\n * So the tail comes with the error. Bounded, because a log that has been\n * appended to across many runs is not something to paste in full.\n */\nexport function pgliteLogTail(projectRoot: string, lines = 12): string {\n try {\n const contents = fs.readFileSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"utf8\").trimEnd();\n if (!contents) return \" (pglite.log is empty — the daemon wrote nothing before exiting)\";\n return contents.split(\"\\n\").slice(-lines).map(line => ` ${line}`).join(\"\\n\");\n } catch {\n return \" (pglite.log could not be read)\";\n }\n}\n\nexport function managedUrl(port: number): string {\n return `postgresql://${MANAGED_USER}@127.0.0.1:${port}/${MANAGED_DATABASE}?sslmode=disable`;\n}\n\n/**\n * Ask the process behind a state record to prove it is the one we wrote down.\n *\n * A pid check alone answers \"is *a* process running\", and a port check alone\n * answers \"is *something* listening\" — after a reboot both say yes about\n * strangers. The daemon answers with the token from its own state file, so a\n * match is the only evidence accepted.\n */\nexport function isDaemonAlive(state: DaemonState): Promise<boolean> {\n if (!pidRunning(state.pid)) return Promise.resolve(false);\n\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let answer = \"\";\n const settle = (alive: boolean) => {\n socket.removeAllListeners();\n socket.destroy();\n resolve(alive);\n };\n socket.setTimeout(IDENTITY_TIMEOUT_MS);\n socket.once(\"timeout\", () => settle(false));\n socket.once(\"error\", () => settle(false));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n if (answer.includes(\"\\n\")) settle(answer.trim() === `rebase-dev-db ${state.token}`);\n });\n socket.once(\"close\", () => settle(answer.trim() === `rebase-dev-db ${state.token}`));\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/** The running daemon for this project, or `null`. Never starts anything. */\nexport async function findRunningDaemon(projectRoot: string): Promise<DaemonState | null> {\n const state = readState(projectRoot);\n if (!state) return null;\n if (await isDaemonAlive(state)) return state;\n\n // The record describes something that is not there. Clearing it is the\n // whole recovery: the next ensure call starts a fresh daemon, and leaving\n // it would make every subsequent check pay the identity timeout.\n clearState(projectRoot);\n\n return null;\n}\n\n/**\n * Resolve the CLI entry point, so the daemon can be spawned as ourselves.\n *\n * A hidden subcommand rather than a second build entry: under `tsx` this file\n * is `src/dev-db/daemon.ts` and in a published CLI it is bundled into\n * `dist/index.js`, and in both cases the executable to re-invoke is the one\n * already running.\n */\nfunction resolveCliEntry(): string {\n // `process.argv[1]` is `bin/rebase.js` for a real invocation, which is\n // exactly what should be re-run. Under a test runner it is the runner, so\n // fall back to this module's own directory.\n const argvEntry = process.argv[1];\n if (argvEntry && fs.existsSync(argvEntry)) return argvEntry;\n\n return fileURLToPath(new URL(\"../index.js\", import.meta.url));\n}\n\n/**\n * How to re-invoke ourselves, which differs between a published CLI and this\n * repository.\n *\n * A published `rebase` is `node bin/rebase.js`, and re-running that is trivial.\n * Inside the monorepo the entry is TypeScript, which plain `node` cannot load —\n * so the daemon has to be started through the same loader that is running now.\n * Getting this wrong fails as a spawn that exits instantly with a syntax error,\n * which is why the caller reads `pglite.log` on failure.\n */\nexport function resolveSpawn(entry: string): { execPath: string; prefixArgs: string[] } {\n if (!/\\.[cm]?ts$/.test(entry)) return { execPath: process.execPath, prefixArgs: [] };\n\n // Node can load TypeScript when tsx is registered as an import hook. tsx is\n // already a dependency of this package, because `rebase dev` runs the\n // backend through it.\n return { execPath: process.execPath, prefixArgs: [\"--import\", \"tsx\"] };\n}\n\nexport interface EnsureOptions {\n /** Silence the \"starting…\" progress line. */\n quiet?: boolean;\n /** Milliseconds of inactivity before the daemon exits. 0 disables. */\n idleTimeoutMs?: number;\n /** Where progress goes. Injected for tests. */\n onProgress?: (message: string) => void;\n /** Override how the daemon process is launched. For tests. */\n spawn?: { execPath: string; prefixArgs: string[] };\n /**\n * Override the CLI entry to re-invoke. For tests.\n *\n * Necessary because under a test runner `process.argv[1]` is the runner\n * itself, which exists and is therefore accepted by {@link resolveCliEntry}\n * — spawning vitest with `__dev-db-daemon` rather than the CLI.\n */\n entry?: string;\n /**\n * Keys of the additional databases the project declares, beyond the\n * default. Each is served by the daemon on request, so a project that\n * adds `database(\"analytics\")` while the daemon is running gets it\n * without a restart.\n */\n additionalKeys?: readonly string[];\n}\n\n/**\n * Ask the running daemon for one additional database, and get its port.\n *\n * The identity socket doubles as the command channel: the daemon answers\n * with its token first, which is how the caller knows it is talking to the\n * daemon the state file describes and not to a stranger on a recycled port.\n */\nfunction ensureAdditionalDatabase(state: DaemonState, key: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n let answer = \"\";\n let identified = false;\n const fail = (message: string) => {\n socket.removeAllListeners();\n socket.destroy();\n reject(new Error(message));\n };\n socket.setTimeout(START_TIMEOUT_MS);\n socket.once(\"timeout\", () => fail(`The development database did not answer for \"${key}\" within ${Math.round(START_TIMEOUT_MS / 1000)}s.`));\n socket.once(\"error\", (err) => fail(`Could not reach the development database for \"${key}\": ${err.message}`));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n let newline = answer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = answer.slice(0, newline).trim();\n answer = answer.slice(newline + 1);\n if (!identified) {\n if (line !== `rebase-dev-db ${state.token}`) return fail(\"The process on the development database's port is not the daemon.\");\n identified = true;\n socket.write(`ensure ${key}\\n`);\n } else if (line.startsWith(\"ok \")) {\n const port = Number(line.slice(3));\n socket.removeAllListeners();\n socket.destroy();\n if (!Number.isInteger(port) || port <= 0) return reject(new Error(`The development database answered with an invalid port for \"${key}\": ${line}`));\n return resolve(port);\n } else {\n return fail(`The development database could not serve \"${key}\": ${line.replace(/^error\\s*/, \"\")}`);\n }\n newline = answer.indexOf(\"\\n\");\n }\n });\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/** Every additional database the caller asked for, as connection strings. */\nasync function adoptWithAdditional(state: DaemonState, started: boolean, keys: readonly string[]): Promise<ManagedDatabase> {\n const additional: Record<string, string> = {};\n for (const key of keys) {\n const known = state.databases?.[key];\n const port = known ? known.port : await ensureAdditionalDatabase(state, key);\n additional[key] = managedUrl(port);\n }\n return { ...adopt(state, started), additional };\n}\n\n/**\n * The project's managed database, started if it is not already running.\n *\n * Safe to call concurrently from several commands: the loser of the race finds\n * the winner's state file during its poll and adopts it rather than starting a\n * second daemon.\n */\nexport async function ensureManagedDatabase(\n projectRoot: string,\n options: EnsureOptions = {}\n): Promise<ManagedDatabase> {\n const keys = options.additionalKeys ?? [];\n const existing = await findRunningDaemon(projectRoot);\n if (existing) return adoptWithAdditional(existing, false, keys);\n\n fs.mkdirSync(devDbDir(projectRoot), { recursive: true });\n ensureGitignore(projectRoot);\n\n // Exactly one process may spawn a daemon. Without this, `rebase dev` and\n // `rebase db push` started in the same second both see no state file, both\n // spawn, and two processes open one PGlite data directory — the corruption\n // the single-daemon design exists to prevent.\n if (!acquireStartLock(projectRoot, START_TIMEOUT_MS)) {\n const adopted = await waitForDaemon(projectRoot, START_TIMEOUT_MS);\n if (adopted) return adoptWithAdditional(adopted, false, keys);\n\n // The holder gave up or died without publishing. Falling through to\n // start one ourselves is better than failing: the lock is stale by now,\n // so the next acquire will break it.\n if (!acquireStartLock(projectRoot, 0)) {\n throw new Error(\n \"Another process is starting the development database and did not finish.\\n\" +\n ` Remove ${path.join(devDbDir(projectRoot), \"starting.lock\")} if nothing is running.`\n );\n }\n }\n\n const port = await findFreePort();\n const token = randomBytes(16).toString(\"hex\");\n const entry = options.entry ?? resolveCliEntry();\n\n const spawnPlan = options.spawn ?? resolveSpawn(entry);\n const args = [\n ...spawnPlan.prefixArgs,\n entry,\n \"__dev-db-daemon\",\n \"--project\", projectRoot,\n \"--port\", String(port),\n \"--token\", token\n ];\n if (options.idleTimeoutMs !== undefined) {\n args.push(\"--idle-timeout\", String(options.idleTimeoutMs));\n }\n\n const log = fs.openSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"a\");\n const child: ChildProcess = spawn(spawnPlan.execPath, args, {\n // Detached with no stdin and its output on a file: the daemon must\n // survive the command that started it, and must not hold the terminal\n // open when that command exits.\n detached: true,\n stdio: [\"ignore\", log, log]\n });\n child.unref();\n\n try {\n const deadline = Date.now() + START_TIMEOUT_MS;\n let announced = false;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return adoptWithAdditional(state, true, keys);\n\n if (!announced && !options.quiet) {\n announced = true;\n options.onProgress?.(\"Starting the development database…\");\n }\n\n // A daemon that died on startup will never publish a state file, and\n // waiting the full minute for that is a bad way to learn it. The log\n // is the only place the reason exists.\n if (child.exitCode !== null && child.exitCode !== 0) {\n throw new Error(\n `The development database failed to start (exit ${child.exitCode}).\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot)\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n throw new Error(\n `The development database did not start within ${Math.round(START_TIMEOUT_MS / 1000)}s.\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot) + \"\\n\" +\n \" To use your own Postgres instead, set DATABASE_URL or pass --database-url.\"\n );\n } finally {\n // Released whether we succeeded, timed out or threw. A lock left behind\n // by a crash is broken by age, but only after a full timeout — which a\n // developer should never have to wait out.\n releaseStartLock(projectRoot);\n }\n}\n\n/** Shape a live state record as the caller's result. */\nfunction adopt(state: DaemonState, started: boolean): ManagedDatabase {\n return {\n url: managedUrl(state.port),\n dataDir: state.dataDir,\n port: state.port,\n pid: state.pid,\n started,\n additional: {}\n };\n}\n\n/** Poll until another process publishes a live daemon, or give up. */\nasync function waitForDaemon(projectRoot: string, timeoutMs: number): Promise<DaemonState | null> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return state;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n return null;\n}\n\n/** Stop the daemon. Returns false when there was nothing running. */\nexport async function stopManagedDatabase(projectRoot: string): Promise<boolean> {\n const state = await findRunningDaemon(projectRoot);\n if (!state) return false;\n\n try {\n process.kill(state.pid, \"SIGTERM\");\n } catch {\n clearState(projectRoot);\n\n return false;\n }\n\n // Wait for it to clear its own state file, which is how it says it closed\n // the data directory cleanly. A hard kill here would risk the WAL.\n const deadline = Date.now() + 10_000;\n while (Date.now() < deadline) {\n if (!fs.existsSync(stateFile(projectRoot))) return true;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n clearState(projectRoot);\n\n return true;\n}\n\n/**\n * Stop the daemon and delete the data directory.\n *\n * Destructive and deliberately not clever: it removes the whole directory\n * rather than dropping schemas, because \"give me an empty database\" is the only\n * thing anyone means by it.\n */\nexport async function resetManagedDatabase(projectRoot: string): Promise<void> {\n await stopManagedDatabase(projectRoot);\n fs.rmSync(dataDir(projectRoot), { recursive: true, force: true });\n // Every additional database too: `pgdata__<key>` beside `pgdata`. \"Give\n // me an empty database\" means all of them — a reset that emptied the\n // default and kept the analytics rows would be a surprise on first read.\n const dir = devDbDir(projectRoot);\n if (fs.existsSync(dir)) {\n for (const entry of fs.readdirSync(dir)) {\n if (entry.startsWith(\"pgdata__\")) fs.rmSync(path.join(dir, entry), { recursive: true, force: true });\n }\n }\n clearState(projectRoot);\n}\n\n/**\n * Keep the generated directory out of git.\n *\n * `.rebase/` holds a Postgres data directory and a log. A project that commits\n * it will push hundreds of megabytes and a database that only makes sense on\n * one machine, so the ignore file is written next to the data rather than\n * relying on the project's root `.gitignore` having been updated.\n */\nfunction ensureGitignore(projectRoot: string): void {\n const target = path.join(devDbDir(projectRoot), \".gitignore\");\n if (fs.existsSync(target)) return;\n fs.writeFileSync(\n target,\n \"# Generated by `rebase dev` — a local Postgres data directory and its log.\\n\" +\n \"# Machine-specific and large; never commit it.\\n*\\n\",\n \"utf8\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAM,mBAAmB;;AAEzB,IAAM,mBAAmB;;AAEzB,IAAM,sBAAsB;;;;;;;AAyB5B,IAAM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C,IAAI,MAAM,WAAW,UAAU,GAAG,GAAG,OAAO,KAAK,KAAK,KAAK,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CAAA;CAG3G,WAAW,WAAW;AAC1B;;;;;;;;;AAUA,SAAS,gBAAgB,aAA2B;CAChD,MAAM,SAAS,KAAK,KAAK,SAAS,WAAW,GAAG,YAAY;CAC5D,IAAI,GAAG,WAAW,MAAM,GAAG;CAC3B,GAAG,cACC,QACA,mIAEA,MACJ;AACJ"}
@@ -45,6 +45,21 @@ export interface ManagedDatabase {
45
45
  * Putting it in the URL fixes every consumer at once — Atlas, `pg`, and anything
46
46
  * a driver shells out to later — rather than teaching each one about PGlite.
47
47
  */
48
+ /**
49
+ * The end of `pglite.log`, for an error message that has to carry its own reason.
50
+ *
51
+ * The daemon writes its output to a file because it is detached — it has to
52
+ * outlive the command that started it. That is right, and it means every
53
+ * startup failure used to be reported as a path: "see pglite.log for the
54
+ * reason". On a laptop that is a fair trade. In CI it is not a trade at all,
55
+ * because the runner discards the workspace: the log named in the message no
56
+ * longer exists by the time anybody reads the message, so a failed run says
57
+ * only that something failed.
58
+ *
59
+ * So the tail comes with the error. Bounded, because a log that has been
60
+ * appended to across many runs is not something to paste in full.
61
+ */
62
+ export declare function pgliteLogTail(projectRoot: string, lines?: number): string;
48
63
  export declare function managedUrl(port: number): string;
49
64
  /**
50
65
  * Ask the process behind a state record to prove it is the one we wrote down.
package/dist/index.es.js CHANGED
@@ -3,7 +3,7 @@ import { _ as validateTsxInstallation, a as findBackendDir, c as findProjectRoot
3
3
  import { i as probeTcp, r as ensureDevDatabase, t as composeDatabaseUrl } from "./dev-preflight-CNLl4rdo.js";
4
4
  import { r as readActiveBranch, t as branchUrl } from "./branch-pointer-dBiClJ0p.js";
5
5
  import { t as MANAGED_LIMITATIONS } from "./constraints-DKGbNfUW.js";
6
- import { i as managedUrl, n as ensureManagedDatabase, r as findRunningDaemon } from "./daemon-YDZK9NZ1.js";
6
+ import { i as managedUrl, n as ensureManagedDatabase, r as findRunningDaemon } from "./daemon-DR9Tk0La.js";
7
7
  import { n as resolveDevDatabase, t as describeDevDatabase } from "./resolve-Y56osuQH.js";
8
8
  import chalk from "chalk";
9
9
  import arg from "arg";
@@ -2452,6 +2452,19 @@ async function configureEnvFile(targetDirectory, databaseUrl) {
2452
2452
  `# DATABASE_URL=postgresql://rebase_app:${dbPassword}@127.0.0.1:${dbPort}/rebase?options=-c%20search_path%3Dpublic&sslmode=disable`,
2453
2453
  `DATABASE_PASSWORD=${dbPassword}`
2454
2454
  ].join("\n"));
2455
+ const envExampleReference = path.join(targetDirectory, ".env.example");
2456
+ if (fs.existsSync(envExampleReference)) {
2457
+ let exampleContent = fs.readFileSync(envExampleReference, "utf-8");
2458
+ exampleContent = exampleContent.replace(/^DATABASE_URL=postgresql:\/\/[^\n]*$/m, [
2459
+ "# Commented out on purpose — that is what selects the managed database.",
2460
+ "# To use the docker-compose Postgres this project ships instead:",
2461
+ "# docker compose up -d db, then uncomment the line below in .env",
2462
+ "# (with DATABASE_PASSWORD from that file, not the placeholder here).",
2463
+ `# DATABASE_URL=postgresql://rebase_app:changeme@127.0.0.1:${dbPort}/rebase?options=-c%20search_path%3Dpublic&sslmode=disable`
2464
+ ].join("\n"));
2465
+ exampleContent = exampleContent.replaceAll("@localhost:5432/rebase", `@127.0.0.1:${dbPort}/rebase`);
2466
+ fs.writeFileSync(envExampleReference, exampleContent, "utf-8");
2467
+ }
2455
2468
  const dockerComposePath = path.join(targetDirectory, "docker-compose.yml");
2456
2469
  if (fs.existsSync(dockerComposePath)) {
2457
2470
  let dockerComposeContent = fs.readFileSync(dockerComposePath, "utf-8");
@@ -2844,62 +2857,6 @@ function reportSpawnFailure(error) {
2844
2857
  if (message) console.error(chalk.red(`✗ ${message}`));
2845
2858
  }
2846
2859
  //#endregion
2847
- //#region src/utils/command-words.ts
2848
- /**
2849
- * The words that name a command, with the flags taken back out.
2850
- *
2851
- * `rawArgs` is the whole of `process.argv`, and reading the command's words at
2852
- * fixed indices off it assumes nothing precedes them. Something routinely does:
2853
- * `--debug` is what `bin/rebase.js` prints after every failure as the thing to
2854
- * re-run with, so it is the single most likely token to appear before a command
2855
- * word, and it shifted every index by one.
2856
- *
2857
- * What that cost is not a bad error message. `rebase db branch switch feature`
2858
- * writes a per-checkout pointer that the CLI owns; the driver, running as a
2859
- * child process, cannot persist it and does not try. The dispatch found
2860
- * `switch` by position, so `rebase --debug db branch switch feature` missed the
2861
- * CLI's branch and handed the line to the driver — which reported success and
2862
- * left the checkout on the main database. Every subsequent `dev`, `push` and
2863
- * `backup` then ran against the wrong database, believing it was the branch,
2864
- * which is the exact failure branching exists to prevent.
2865
- *
2866
- * The words are anchored on the command name rather than taken from position
2867
- * zero, because a flag written in the space form (`--database-url <url>`) leaves
2868
- * its value behind as a bare token and no parser at this level knows which
2869
- * flags take values. Anchoring survives that: the value would have to be the
2870
- * literal command name to fool it.
2871
- *
2872
- * Returns `[]` when the command name is not on the line at all.
2873
- */
2874
- function commandWords(rawArgs, command) {
2875
- const words = rawArgs.slice(2).filter((token) => !token.startsWith("-"));
2876
- const start = words.indexOf(command);
2877
- return start === -1 ? [] : words.slice(start);
2878
- }
2879
- /**
2880
- * The line to hand a spawned driver, starting at the command word.
2881
- *
2882
- * The same defect one layer down, and it does not degrade gracefully: the
2883
- * driver reads its domain from `args[0]`, so `rebase --debug db push` spawned
2884
- * it with `["--debug", "db", "push"]` and it answered "Unknown domain command:
2885
- * --debug" — for a flag the CLI itself tells you to add after any failure.
2886
- *
2887
- * Tokens written *before* the command word are moved after it rather than
2888
- * dropped. Dropping them would be the same class of bug in the other direction:
2889
- * `rebase --database-url postgres://… db push` would silently lose the flag that
2890
- * says which database to touch. Appending keeps each flag next to its value, and
2891
- * `arg` reads flags wherever they appear.
2892
- *
2893
- * Falls back to `rawArgs.slice(2)` when the command word is not on the line,
2894
- * which is what an internally synthesised argv looks like.
2895
- */
2896
- function argsFromCommand(rawArgs, command) {
2897
- const tail = rawArgs.slice(2);
2898
- const start = tail.findIndex((token) => token === command);
2899
- if (start <= 0) return [...tail];
2900
- return [...tail.slice(start), ...tail.slice(0, start)];
2901
- }
2902
- //#endregion
2903
2860
  //#region src/utils/unknown-command.ts
2904
2861
  /**
2905
2862
  * What every command family says when it does not recognise a subcommand.
@@ -2994,6 +2951,62 @@ function unknownCommand(typed, known, family = "") {
2994
2951
  process.exit(1);
2995
2952
  }
2996
2953
  //#endregion
2954
+ //#region src/utils/command-words.ts
2955
+ /**
2956
+ * The words that name a command, with the flags taken back out.
2957
+ *
2958
+ * `rawArgs` is the whole of `process.argv`, and reading the command's words at
2959
+ * fixed indices off it assumes nothing precedes them. Something routinely does:
2960
+ * `--debug` is what `bin/rebase.js` prints after every failure as the thing to
2961
+ * re-run with, so it is the single most likely token to appear before a command
2962
+ * word, and it shifted every index by one.
2963
+ *
2964
+ * What that cost is not a bad error message. `rebase db branch switch feature`
2965
+ * writes a per-checkout pointer that the CLI owns; the driver, running as a
2966
+ * child process, cannot persist it and does not try. The dispatch found
2967
+ * `switch` by position, so `rebase --debug db branch switch feature` missed the
2968
+ * CLI's branch and handed the line to the driver — which reported success and
2969
+ * left the checkout on the main database. Every subsequent `dev`, `push` and
2970
+ * `backup` then ran against the wrong database, believing it was the branch,
2971
+ * which is the exact failure branching exists to prevent.
2972
+ *
2973
+ * The words are anchored on the command name rather than taken from position
2974
+ * zero, because a flag written in the space form (`--database-url <url>`) leaves
2975
+ * its value behind as a bare token and no parser at this level knows which
2976
+ * flags take values. Anchoring survives that: the value would have to be the
2977
+ * literal command name to fool it.
2978
+ *
2979
+ * Returns `[]` when the command name is not on the line at all.
2980
+ */
2981
+ function commandWords(rawArgs, command) {
2982
+ const words = rawArgs.slice(2).filter((token) => !token.startsWith("-"));
2983
+ const start = words.indexOf(command);
2984
+ return start === -1 ? [] : words.slice(start);
2985
+ }
2986
+ /**
2987
+ * The line to hand a spawned driver, starting at the command word.
2988
+ *
2989
+ * The same defect one layer down, and it does not degrade gracefully: the
2990
+ * driver reads its domain from `args[0]`, so `rebase --debug db push` spawned
2991
+ * it with `["--debug", "db", "push"]` and it answered "Unknown domain command:
2992
+ * --debug" — for a flag the CLI itself tells you to add after any failure.
2993
+ *
2994
+ * Tokens written *before* the command word are moved after it rather than
2995
+ * dropped. Dropping them would be the same class of bug in the other direction:
2996
+ * `rebase --database-url postgres://… db push` would silently lose the flag that
2997
+ * says which database to touch. Appending keeps each flag next to its value, and
2998
+ * `arg` reads flags wherever they appear.
2999
+ *
3000
+ * Falls back to `rawArgs.slice(2)` when the command word is not on the line,
3001
+ * which is what an internally synthesised argv looks like.
3002
+ */
3003
+ function argsFromCommand(rawArgs, command) {
3004
+ const tail = rawArgs.slice(2);
3005
+ const start = tail.findIndex((token) => token === command);
3006
+ if (start <= 0) return [...tail];
3007
+ return [...tail.slice(start), ...tail.slice(0, start)];
3008
+ }
3009
+ //#endregion
2997
3010
  //#region src/dev-db/prepare.ts
2998
3011
  /**
2999
3012
  * The one place a command asks "which database, and how do I reach it?".
@@ -3179,122 +3192,6 @@ function managedNotices(prepared) {
3179
3192
  return lines;
3180
3193
  }
3181
3194
  //#endregion
3182
- //#region src/commands/schema.ts
3183
- /**
3184
- * CLI command: rebase schema <action>
3185
- */
3186
- async function schemaCommand(subcommand, rawArgs) {
3187
- if (!subcommand || subcommand === "--help" || wantsHelp(rawArgs)) {
3188
- printSchemaHelp(subcommand === "--help" ? void 0 : subcommand);
3189
- return;
3190
- }
3191
- if (!SCHEMA_ACTION_HELP[subcommand]) unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), "schema");
3192
- const projectRoot = requireProjectRoot();
3193
- recordEvent("cli.schema", { subcommand: subcommand ?? "none" }, { projectRoot });
3194
- const backendDir = requireBackendDir(projectRoot);
3195
- const activePlugin = getActiveBackendPlugin(backendDir);
3196
- if (!activePlugin) {
3197
- console.error(chalk.red("✗ Could not detect an active database plugin."));
3198
- console.error(chalk.gray(" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json."));
3199
- process.exit(1);
3200
- }
3201
- const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
3202
- if (!pluginCli) exitDependenciesNotInstalled(projectRoot);
3203
- const envFile = findEnvFile(projectRoot);
3204
- const env = { ...process.env };
3205
- if (envFile) env.DOTENV_CONFIG_PATH = envFile;
3206
- env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? "";
3207
- try {
3208
- /**
3209
- * tsx, whether the driver CLI is source or built.
3210
- *
3211
- * This chose the interpreter from the file extension — tsx for a `.ts`
3212
- * entry, `node` for a built one — which was right only for as long as
3213
- * the driver shipped `src/`. Once it shipped `dist/cli.js`, the built
3214
- * CLI ran under plain `node`, and some of its subcommands load the
3215
- * PROJECT's collections in process. `schema stale` does: on the stock
3216
- * scaffold, whose collections import each other, Node could not resolve
3217
- * `./authors` onto `authors.ts` and the command reported "⏭ Not
3218
- * checked" — answering "is the generated schema stale?" with nothing,
3219
- * and exiting 0.
3220
- *
3221
- * The same rule lives in `execDriverCli` (commands/db.ts). Two copies of
3222
- * one decision is how they came to disagree; this one is kept because
3223
- * `schema` deliberately does NOT resolve a database, and `execDriverCli`
3224
- * is reached through a path that does.
3225
- */
3226
- const tsxBin = resolveTsx(projectRoot);
3227
- if (!tsxBin && pluginCli.endsWith(".ts")) exitDependenciesNotInstalled(projectRoot);
3228
- await execa(tsxBin ?? "node", [pluginCli, ...argsFromCommand(rawArgs, "schema")], {
3229
- cwd: backendDir,
3230
- stdio: "inherit",
3231
- env
3232
- });
3233
- } catch (error) {
3234
- reportSpawnFailure(error);
3235
- process.exit(1);
3236
- }
3237
- }
3238
- /** One page per subcommand, so `rebase schema <action> --help` says something. */
3239
- var SCHEMA_ACTION_HELP = {
3240
- generate: {
3241
- usage: "rebase schema generate [--collections <dir>] [--output <file>] [--watch]",
3242
- summary: "Generate the Drizzle schema from the collection definitions.",
3243
- notes: ["--watch regenerates on every change to a collection file."]
3244
- },
3245
- introspect: {
3246
- usage: "rebase schema introspect [--collections <dir>] [--output <dir>] [--schema <name>] [--force]",
3247
- summary: "Read an existing database and write Rebase collection definitions from it.",
3248
- notes: ["--force overwrites collection files that are already there."]
3249
- },
3250
- stale: {
3251
- usage: "rebase schema stale [--collections <dir>] [--output <file>] [--fix]",
3252
- summary: "Report generated schema files that no longer match the collections.",
3253
- notes: ["--fix regenerates them instead of only reporting."]
3254
- }
3255
- };
3256
- function printSchemaHelp(action) {
3257
- const entry = action ? SCHEMA_ACTION_HELP[action] : void 0;
3258
- if (entry) {
3259
- console.log(`
3260
- ${chalk.bold(`rebase schema ${action}`)}
3261
-
3262
- ${entry.summary}
3263
-
3264
- ${chalk.green.bold("Usage")}
3265
- ${chalk.blue(entry.usage)}
3266
- ${entry.notes?.length ? `\n${chalk.green.bold("Notes")}\n${entry.notes.map((n) => ` ${chalk.gray(`• ${n}`)}`).join("\n")}\n` : ""}
3267
- ${chalk.gray("Run `rebase schema --help` for every subcommand.")}
3268
- `);
3269
- return;
3270
- }
3271
- console.log(`
3272
- ${chalk.bold("rebase schema")} — Schema management commands
3273
-
3274
- ${chalk.green.bold("Usage")}
3275
- rebase schema ${chalk.blue("<command>")} [options]
3276
-
3277
- ${chalk.green.bold("Commands")}
3278
- ${chalk.gray("(Commands are provided by your active database driver plugin)")}
3279
- ${chalk.blue.bold("generate")} Generate Schema from collection definitions
3280
- ${chalk.blue.bold("introspect")} Introspect an existing database to generate collection definitions
3281
- ${chalk.blue.bold("stale")} Report generated schema files that no longer match the collections
3282
-
3283
- ${chalk.green.bold("generate Options")}
3284
- ${chalk.blue("--collections, -c")} Path to collections directory
3285
- ${chalk.blue("--output, -o")} Output path for generated schema
3286
- ${chalk.blue("--watch, -w")} Watch for changes and regenerate automatically
3287
-
3288
- ${chalk.green.bold("introspect Options")}
3289
- ${chalk.blue("--output, -o")} Output directory for generated collection files
3290
- ${chalk.blue("--schema")} Postgres schema to read (default: public)
3291
- ${chalk.blue("--force, -f")} Overwrite collection files that already exist
3292
-
3293
- ${chalk.green.bold("stale Options")}
3294
- ${chalk.blue("--fix")} Regenerate the stale files instead of only reporting them
3295
- `);
3296
- }
3297
- //#endregion
3298
3195
  //#region src/commands/db.ts
3299
3196
  /**
3300
3197
  * CLI command: rebase db <action>
@@ -3588,42 +3485,41 @@ async function resolveDriverCli() {
3588
3485
  env
3589
3486
  };
3590
3487
  }
3591
- /** Run the resolved driver CLI with the given child arguments. */
3592
- async function execDriverCli(resolved, childArgs, options = {}) {
3488
+ /**
3489
+ * The one place this CLI spawns the driver's own CLI.
3490
+ *
3491
+ * There were three, each with its own copy of "tsx for a `.ts` entry, `node`
3492
+ * otherwise". That rule was right only while the driver shipped `src/`; once it
3493
+ * shipped `dist/cli.js` all three quietly switched to plain `node`, and the
3494
+ * driver loads the PROJECT's TypeScript in process:
3495
+ *
3496
+ * - `schema stale` reads the collections, could not resolve `./authors` onto
3497
+ * `authors.ts`, and answered "⏭ Not checked" while exiting 0;
3498
+ * - `db push` does the same in `ensureAuthTables`, so `rebase.users` was never
3499
+ * created and the push died at "Applying RLS policies" with
3500
+ * `relation "rebase.users" does not exist` — on a virgin database, which is
3501
+ * the documented bring-your-own-Postgres first run.
3502
+ *
3503
+ * Two were fixed and the third was missed, because three copies of a decision
3504
+ * are three chances to miss one. There is one now, and a gate holds it at one.
3505
+ *
3506
+ * tsx whenever it is installed — a devDependency of every scaffold, for exactly
3507
+ * this reason. Without it a `.ts` entry cannot run at all; a built entry still
3508
+ * runs, and the subcommands that never touch the project's TypeScript still work.
3509
+ */
3510
+ async function spawnDriverCli(resolved, childArgs, options = {}) {
3593
3511
  const { projectRoot, backendDir, pluginCli, env } = resolved;
3594
3512
  const stdio = options.quiet ? "pipe" : "inherit";
3595
- /**
3596
- * tsx, whether the driver CLI is source or built.
3597
- *
3598
- * It used to be tsx only for a `.ts` entry, which happened to be right for
3599
- * as long as the driver shipped `src/`. Once it shipped `dist/cli.js`
3600
- * instead, this ran the built CLI under plain `node` — and some of its
3601
- * subcommands load the PROJECT's collections in process. `schema stale`
3602
- * does, so on every scaffold whose collections import each other (the stock
3603
- * one does) it failed to resolve them and reported "⏭ Not checked": a
3604
- * command that answers "is the generated schema stale?" with nothing at all,
3605
- * exiting 0, on the default project.
3606
- *
3607
- * Node cannot load a `.ts` file, and cannot resolve `./authors` or
3608
- * `./authors.js` onto `authors.ts`. tsx does both. It is a devDependency of
3609
- * every scaffold for exactly this reason.
3610
- */
3611
3513
  const tsxBin = resolveTsx(projectRoot);
3612
- if (tsxBin) {
3613
- await execa(tsxBin, [pluginCli, ...childArgs], {
3614
- cwd: backendDir,
3615
- stdio,
3616
- env
3617
- });
3618
- return;
3619
- }
3620
- if (pluginCli.endsWith(".ts")) throw new Error(dependenciesNotInstalled(projectRoot));
3621
- await execa("node", [pluginCli, ...childArgs], {
3514
+ if (!tsxBin && pluginCli.endsWith(".ts")) throw new Error(dependenciesNotInstalled(projectRoot));
3515
+ await execa(tsxBin ?? "node", [pluginCli, ...childArgs], {
3622
3516
  cwd: backendDir,
3623
3517
  stdio,
3624
3518
  env
3625
3519
  });
3626
3520
  }
3521
+ /** @deprecated Use {@link spawnDriverCli}. Kept as the internal name callers use. */
3522
+ var execDriverCli = spawnDriverCli;
3627
3523
  /**
3628
3524
  * Run a `schema` subcommand through the active driver's CLI.
3629
3525
  *
@@ -3666,21 +3562,12 @@ async function runDriverDbCommand(rawArgs, options = {}) {
3666
3562
  if (!options.quiet) for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));
3667
3563
  refuseAtlasOnManagedDatabase(rawArgs, prepared.database.kind);
3668
3564
  const childArgs = absolutizeLocalPathArgs(argsFromCommand(rawArgs, "db"), process.cwd());
3669
- if (pluginCli.endsWith(".ts")) {
3670
- const tsxBin = resolveTsx(projectRoot);
3671
- if (!tsxBin) throw new Error(dependenciesNotInstalled(projectRoot));
3672
- await execa(tsxBin, [pluginCli, ...childArgs], {
3673
- cwd: backendDir,
3674
- stdio: "inherit",
3675
- env
3676
- });
3677
- return;
3678
- }
3679
- await execa("node", [pluginCli, ...childArgs], {
3680
- cwd: backendDir,
3681
- stdio: "inherit",
3565
+ await spawnDriverCli({
3566
+ projectRoot,
3567
+ backendDir,
3568
+ pluginCli,
3682
3569
  env
3683
- });
3570
+ }, childArgs, options);
3684
3571
  }
3685
3572
  async function dbCommand$1(subcommand, rawArgs) {
3686
3573
  if (!subcommand || subcommand === "--help" || rawArgs.includes("--help") || rawArgs.includes("-h")) {
@@ -3777,7 +3664,7 @@ async function printDatabaseUrl(projectRoot, rawArgs) {
3777
3664
  * removing the directory cannot leave a half-dropped schema behind.
3778
3665
  */
3779
3666
  async function manageLocalDatabase(subcommand, projectRoot, rawArgs) {
3780
- const { resetManagedDatabase, stopManagedDatabase, findRunningDaemon } = await import("./daemon-YDZK9NZ1.js").then((n) => n.t);
3667
+ const { resetManagedDatabase, stopManagedDatabase, findRunningDaemon } = await import("./daemon-DR9Tk0La.js").then((n) => n.t);
3781
3668
  const { dataDir } = await import("./state-C59Elrnt.js").then((n) => n.d);
3782
3669
  const nothingHere = () => {
3783
3670
  const kind = devDatabaseKind(projectRoot);
@@ -4348,6 +4235,103 @@ function dbExamples(kind) {
4348
4235
  `;
4349
4236
  }
4350
4237
  //#endregion
4238
+ //#region src/commands/schema.ts
4239
+ /**
4240
+ * CLI command: rebase schema <action>
4241
+ */
4242
+ async function schemaCommand(subcommand, rawArgs) {
4243
+ if (!subcommand || subcommand === "--help" || wantsHelp(rawArgs)) {
4244
+ printSchemaHelp(subcommand === "--help" ? void 0 : subcommand);
4245
+ return;
4246
+ }
4247
+ if (!SCHEMA_ACTION_HELP[subcommand]) unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), "schema");
4248
+ const projectRoot = requireProjectRoot();
4249
+ recordEvent("cli.schema", { subcommand: subcommand ?? "none" }, { projectRoot });
4250
+ const backendDir = requireBackendDir(projectRoot);
4251
+ const activePlugin = getActiveBackendPlugin(backendDir);
4252
+ if (!activePlugin) {
4253
+ console.error(chalk.red("✗ Could not detect an active database plugin."));
4254
+ console.error(chalk.gray(" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json."));
4255
+ process.exit(1);
4256
+ }
4257
+ const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
4258
+ if (!pluginCli) exitDependenciesNotInstalled(projectRoot);
4259
+ const envFile = findEnvFile(projectRoot);
4260
+ const env = { ...process.env };
4261
+ if (envFile) env.DOTENV_CONFIG_PATH = envFile;
4262
+ env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? "";
4263
+ try {
4264
+ await spawnDriverCli({
4265
+ projectRoot,
4266
+ backendDir,
4267
+ pluginCli,
4268
+ env
4269
+ }, argsFromCommand(rawArgs, "schema"));
4270
+ } catch (error) {
4271
+ reportSpawnFailure(error);
4272
+ process.exit(1);
4273
+ }
4274
+ }
4275
+ /** One page per subcommand, so `rebase schema <action> --help` says something. */
4276
+ var SCHEMA_ACTION_HELP = {
4277
+ generate: {
4278
+ usage: "rebase schema generate [--collections <dir>] [--output <file>] [--watch]",
4279
+ summary: "Generate the Drizzle schema from the collection definitions.",
4280
+ notes: ["--watch regenerates on every change to a collection file."]
4281
+ },
4282
+ introspect: {
4283
+ usage: "rebase schema introspect [--collections <dir>] [--output <dir>] [--schema <name>] [--force]",
4284
+ summary: "Read an existing database and write Rebase collection definitions from it.",
4285
+ notes: ["--force overwrites collection files that are already there."]
4286
+ },
4287
+ stale: {
4288
+ usage: "rebase schema stale [--collections <dir>] [--output <file>] [--fix]",
4289
+ summary: "Report generated schema files that no longer match the collections.",
4290
+ notes: ["--fix regenerates them instead of only reporting."]
4291
+ }
4292
+ };
4293
+ function printSchemaHelp(action) {
4294
+ const entry = action ? SCHEMA_ACTION_HELP[action] : void 0;
4295
+ if (entry) {
4296
+ console.log(`
4297
+ ${chalk.bold(`rebase schema ${action}`)}
4298
+
4299
+ ${entry.summary}
4300
+
4301
+ ${chalk.green.bold("Usage")}
4302
+ ${chalk.blue(entry.usage)}
4303
+ ${entry.notes?.length ? `\n${chalk.green.bold("Notes")}\n${entry.notes.map((n) => ` ${chalk.gray(`• ${n}`)}`).join("\n")}\n` : ""}
4304
+ ${chalk.gray("Run `rebase schema --help` for every subcommand.")}
4305
+ `);
4306
+ return;
4307
+ }
4308
+ console.log(`
4309
+ ${chalk.bold("rebase schema")} — Schema management commands
4310
+
4311
+ ${chalk.green.bold("Usage")}
4312
+ rebase schema ${chalk.blue("<command>")} [options]
4313
+
4314
+ ${chalk.green.bold("Commands")}
4315
+ ${chalk.gray("(Commands are provided by your active database driver plugin)")}
4316
+ ${chalk.blue.bold("generate")} Generate Schema from collection definitions
4317
+ ${chalk.blue.bold("introspect")} Introspect an existing database to generate collection definitions
4318
+ ${chalk.blue.bold("stale")} Report generated schema files that no longer match the collections
4319
+
4320
+ ${chalk.green.bold("generate Options")}
4321
+ ${chalk.blue("--collections, -c")} Path to collections directory
4322
+ ${chalk.blue("--output, -o")} Output path for generated schema
4323
+ ${chalk.blue("--watch, -w")} Watch for changes and regenerate automatically
4324
+
4325
+ ${chalk.green.bold("introspect Options")}
4326
+ ${chalk.blue("--output, -o")} Output directory for generated collection files
4327
+ ${chalk.blue("--schema")} Postgres schema to read (default: public)
4328
+ ${chalk.blue("--force, -f")} Overwrite collection files that already exist
4329
+
4330
+ ${chalk.green.bold("stale Options")}
4331
+ ${chalk.blue("--fix")} Regenerate the stale files instead of only reporting them
4332
+ `);
4333
+ }
4334
+ //#endregion
4351
4335
  //#region src/manifest.ts
4352
4336
  /**
4353
4337
  * Loading, validating and synthesizing `rebase.json`.