@rebasepro/cli 0.25.0-canary.ge06257e → 0.25.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.
Files changed (96) hide show
  1. package/bin/rebase.js +9 -5
  2. package/dist/{agent-setup-C83DXnlx.js → agent-setup-B5AKHOgt.js} +2 -2
  3. package/dist/{agent-setup-C83DXnlx.js.map → agent-setup-B5AKHOgt.js.map} +1 -1
  4. package/dist/{api-keys-Bc4FJKYp.js → api-keys-Tm7zvAPe.js} +27 -20
  5. package/dist/api-keys-Tm7zvAPe.js.map +1 -0
  6. package/dist/{apps-wG-ZTryA.js → apps-BsU_ILbP.js} +4 -4
  7. package/dist/{apps-wG-ZTryA.js.map → apps-BsU_ILbP.js.map} +1 -1
  8. package/dist/{args-CcBphFdj.js → args-BX0YD14a.js} +45 -16
  9. package/dist/args-BX0YD14a.js.map +1 -0
  10. package/dist/{atlas-dev-database-DeK3Sa4h.js → atlas-dev-database-OWtqnG7W.js} +2 -2
  11. package/dist/{atlas-dev-database-DeK3Sa4h.js.map → atlas-dev-database-OWtqnG7W.js.map} +1 -1
  12. package/dist/{auth-BL7bNQVu.js → auth-Vl2hFKXP.js} +77 -10
  13. package/dist/auth-Vl2hFKXP.js.map +1 -0
  14. package/dist/{branch-pointer-DTQNLFtb.js → branch-pointer-9DnwkFJJ.js} +1 -1
  15. package/dist/{build-h_7Re-67.js → build-BBgT8EJZ.js} +5 -5
  16. package/dist/{build-h_7Re-67.js.map → build-BBgT8EJZ.js.map} +1 -1
  17. package/dist/{bundle-CqURVN-K.js → bundle-DtCCCr4w.js} +4 -19
  18. package/dist/bundle-DtCCCr4w.js.map +1 -0
  19. package/dist/{cloud-DVV_5GPG.js → cloud-BpH0_bmV.js} +7 -7
  20. package/dist/{cloud-DVV_5GPG.js.map → cloud-BpH0_bmV.js.map} +1 -1
  21. package/dist/commands/api-keys.d.ts +4 -1
  22. package/dist/commands/auth.d.ts +3 -2
  23. package/dist/connection-banner-DbLJzWf4.js +128 -0
  24. package/dist/connection-banner-DbLJzWf4.js.map +1 -0
  25. package/dist/{console-Dw3HLdUs.js → console-CEGm0XNc.js} +4 -4
  26. package/dist/{console-Dw3HLdUs.js.map → console-CEGm0XNc.js.map} +1 -1
  27. package/dist/{context-BM-oOMNX.js → context-CyflUrKg.js} +2 -2
  28. package/dist/{context-BM-oOMNX.js.map → context-CyflUrKg.js.map} +1 -1
  29. package/dist/{daemon-entry-C6pxdily.js → daemon-entry-CbLRrgzy.js} +199 -3
  30. package/dist/daemon-entry-CbLRrgzy.js.map +1 -0
  31. package/dist/{db-Dkn9XhT-.js → db-CRNpA5mH.js} +171 -60
  32. package/dist/db-CRNpA5mH.js.map +1 -0
  33. package/dist/{derive-Dl0z2OWi.js → derive-CsoFGAnK.js} +28 -13
  34. package/dist/{derive-Dl0z2OWi.js.map → derive-CsoFGAnK.js.map} +1 -1
  35. package/dist/{dev-DAcZR4Pp.js → dev-C0pbMmhS.js} +6 -6
  36. package/dist/{dev-DAcZR4Pp.js.map → dev-C0pbMmhS.js.map} +1 -1
  37. package/dist/dev-db/connection-banner.d.ts +47 -0
  38. package/dist/dev-db/notification-proxy.d.ts +82 -1
  39. package/dist/{dev-preflight-CorMg7Ub.js → dev-preflight-unHpiYO1.js} +26 -3
  40. package/dist/dev-preflight-unHpiYO1.js.map +1 -0
  41. package/dist/{doctor-Ds_lzc9p.js → doctor-CATRdWm6.js} +4 -4
  42. package/dist/{doctor-Ds_lzc9p.js.map → doctor-CATRdWm6.js.map} +1 -1
  43. package/dist/{eject-CJHkfnat.js → eject-DuasTr-F.js} +2 -2
  44. package/dist/{eject-CJHkfnat.js.map → eject-DuasTr-F.js.map} +1 -1
  45. package/dist/{fold-static-BC9CYicw.js → fold-static-hDHtDfTq.js} +2 -2
  46. package/dist/{fold-static-BC9CYicw.js.map → fold-static-hDHtDfTq.js.map} +1 -1
  47. package/dist/{generate_sdk-kfkZmG-d.js → generate_sdk-Cvg5jjJF.js} +3 -3
  48. package/dist/{generate_sdk-kfkZmG-d.js.map → generate_sdk-Cvg5jjJF.js.map} +1 -1
  49. package/dist/index.es.js +34 -34
  50. package/dist/{init-CjoJoThg.js → init-BWAwHPtz.js} +8 -7
  51. package/dist/init-BWAwHPtz.js.map +1 -0
  52. package/dist/last-dev-database-c_dKz1S3.js +2 -0
  53. package/dist/{normalize-imports-BHxL2d05.js → normalize-imports-BoBVh5tU.js} +3 -3
  54. package/dist/{normalize-imports-BHxL2d05.js.map → normalize-imports-BoBVh5tU.js.map} +1 -1
  55. package/dist/precompress.d.ts +0 -7
  56. package/dist/{prepare-C1iaiTC4.js → prepare-DdnU70z8.js} +4 -4
  57. package/dist/prepare-DdnU70z8.js.map +1 -0
  58. package/dist/{pull-COpNJFzY.js → pull-C3PXduzl.js} +13 -40
  59. package/dist/pull-C3PXduzl.js.map +1 -0
  60. package/dist/resolve-CNQjsatH.js +2 -0
  61. package/dist/resources/derive.d.ts +9 -0
  62. package/dist/{resources-CLm6g0br.js → resources-BdNRDEAy.js} +3 -3
  63. package/dist/{resources-CLm6g0br.js.map → resources-BdNRDEAy.js.map} +1 -1
  64. package/dist/{schema-BKdh6UoE.js → schema-B0-p6T1O.js} +4 -4
  65. package/dist/{schema-BKdh6UoE.js.map → schema-B0-p6T1O.js.map} +1 -1
  66. package/dist/{skills-DEhYiPeO.js → skills-DfnTeyRz.js} +3 -3
  67. package/dist/{skills-DEhYiPeO.js.map → skills-DfnTeyRz.js.map} +1 -1
  68. package/dist/{start-BsPJedPQ.js → start-BmEZkS0n.js} +4 -4
  69. package/dist/{start-BsPJedPQ.js.map → start-BmEZkS0n.js.map} +1 -1
  70. package/dist/{status-D_B3tlDy.js → status-BJ26yZOo.js} +9 -9
  71. package/dist/{status-D_B3tlDy.js.map → status-BJ26yZOo.js.map} +1 -1
  72. package/dist/{storage-CtB8polS.js → storage-DKPUBTWG.js} +3 -3
  73. package/dist/{storage-CtB8polS.js.map → storage-DKPUBTWG.js.map} +1 -1
  74. package/dist/{telemetry-BYmPU-Ji.js → telemetry-m9czTNGR.js} +2 -2
  75. package/dist/{telemetry-BYmPU-Ji.js.map → telemetry-m9czTNGR.js.map} +1 -1
  76. package/dist/{upgrade-DbuKX9lv.js → upgrade-DjihWuZL.js} +5 -4
  77. package/dist/{upgrade-DbuKX9lv.js.map → upgrade-DjihWuZL.js.map} +1 -1
  78. package/dist/utils/args.d.ts +13 -0
  79. package/dist/utils/redact.d.ts +10 -0
  80. package/dist/utils/refusal.d.ts +18 -0
  81. package/package.json +7 -7
  82. package/templates/overlays/baas/README.md +2 -1
  83. package/templates/template/.env.example +6 -0
  84. package/templates/template/frontend/vite.config.ts +7 -73
  85. package/dist/api-keys-Bc4FJKYp.js.map +0 -1
  86. package/dist/args-CcBphFdj.js.map +0 -1
  87. package/dist/auth-BL7bNQVu.js.map +0 -1
  88. package/dist/bundle-CqURVN-K.js.map +0 -1
  89. package/dist/daemon-entry-C6pxdily.js.map +0 -1
  90. package/dist/db-Dkn9XhT-.js.map +0 -1
  91. package/dist/dev-preflight-CorMg7Ub.js.map +0 -1
  92. package/dist/init-CjoJoThg.js.map +0 -1
  93. package/dist/last-dev-database-BEBPfAMY.js +0 -2
  94. package/dist/prepare-C1iaiTC4.js.map +0 -1
  95. package/dist/pull-COpNJFzY.js.map +0 -1
  96. package/dist/resolve-b_p9bmdH.js +0 -2
@@ -1,4 +1,5 @@
1
1
  import { r as PGLITE_EXTENSIONS } from "./constraints-CtiylsGf.js";
2
+ import { i as hostOf, n as connectionErrorText, t as banner } from "./connection-banner-DbLJzWf4.js";
2
3
  import fs from "fs";
3
4
  import { execa } from "execa";
4
5
  /**
@@ -416,42 +417,6 @@ async function findPgTool(tool) {
416
417
  function engineOf(version) {
417
418
  return /\bPGlite\b/i.test(version) ? "pglite" : "postgres";
418
419
  }
419
- /** `host:port` of a connection string, for a message: never the string, which carries the password. */
420
- function hostOf(connectionString) {
421
- try {
422
- const url = new URL(connectionString);
423
- return `${url.hostname || "localhost"}:${url.port || "5432"}`;
424
- } catch {
425
- return "(unparseable connection string)";
426
- }
427
- }
428
- /**
429
- * A connection error's own sentence. A refused connection on a dual-stack
430
- * host is an `AggregateError` with an empty message, and its sentence —
431
- * `connect ECONNREFUSED 127.0.0.1:5432` — is in the attempts it holds.
432
- */
433
- function connectionErrorText(error) {
434
- if (error instanceof AggregateError && error.errors.length > 0 && !error.message) return connectionErrorText(error.errors[0]);
435
- return errorText(error);
436
- }
437
- var RULE = "━".repeat(60);
438
- /**
439
- * The boxed banner the database commands print when a connection fails —
440
- * `Cannot connect to PostgreSQL at …` — as plain lines for the caller to print.
441
- */
442
- function banner(title, said, body) {
443
- return [
444
- "",
445
- RULE,
446
- ` ❌ ${title}`,
447
- RULE,
448
- "",
449
- ...said ? [` ${said}`, ""] : [],
450
- ...body.map((line) => ` ${line}`),
451
- "",
452
- RULE
453
- ];
454
- }
455
420
  var NOTHING_CHANGED = "Nothing was changed: the local database is as it was.";
456
421
  /** What the target database runs on, or why it could not be asked. */
457
422
  async function readTargetEngine(target) {
@@ -570,6 +535,12 @@ function describeDumpFailure(source, run) {
570
535
  "Check the user and password in --from."
571
536
  ]);
572
537
  }
538
+ const missing = /database "([^"]+)" does not exist/i.exec(stderr)?.[1];
539
+ if (missing) return banner(`Database "${missing}" does not exist at ${host}`, said, [
540
+ "That is the database --from names, which the pull reads.",
541
+ NOTHING_CHANGED,
542
+ "Check the database name in --from."
543
+ ]);
573
544
  const versions = /server version mismatch/i.test(stderr) ? ["pg_dump is older than the server: install client tools at least as new as it (`brew install libpq`)."] : [];
574
545
  return [
575
546
  ...stderr ? stderr.split("\n") : [],
@@ -719,9 +690,10 @@ async function restoreCopy(plan, dumpFile) {
719
690
  /**
720
691
  * Put the managed database's one session back to its own settings.
721
692
  *
722
- * `RESET ALL`, not `DISCARD ALL`: the session is every connection's, and
723
- * `DISCARD` would also drop the `LISTEN` a running `rebase dev`'s realtime
724
- * holds on it. Best effort: a daemon that cannot take this cannot take the
693
+ * `RESET ALL` and `DEALLOCATE ALL`, not `DISCARD ALL`: the session is every
694
+ * connection's, and `DISCARD` would also drop the `LISTEN` a running
695
+ * `rebase dev`'s realtime holds on it. The same pair the backup service runs
696
+ * after its tools (`resetSharedSession` in server-postgres' backup-service). Best effort: a daemon that cannot take this cannot take the
725
697
  * re-grant that follows either, and that step reports it.
726
698
  */
727
699
  async function resetSharedSession(target) {
@@ -735,6 +707,7 @@ async function resetSharedSession(target) {
735
707
  try {
736
708
  await client.connect();
737
709
  await client.query("RESET ALL");
710
+ await client.query("DEALLOCATE ALL");
738
711
  } catch {} finally {
739
712
  await client.end().catch(() => void 0);
740
713
  }
@@ -754,4 +727,4 @@ function describeRestoreFailure(outcome, source) {
754
727
  //#endregion
755
728
  export { anonymizeCopy, describeRestoreFailure, describeTarget, dumpSource, findPgTool, provisionableSchemas, restoreCopy };
756
729
 
757
- //# sourceMappingURL=pull-COpNJFzY.js.map
730
+ //# sourceMappingURL=pull-C3PXduzl.js.map
@@ -0,0 +1 @@
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 [outcome.failure ?? \"The restore did not complete.\", state, ...(outcome.advice ? [outcome.advice] : [])];\n}\n"],"mappings":";;;;;;;;;;;AA+EA,IAAa,qBAA+C;CAGxD;EAAE,SAAS;EAAyB,OAAO;EAAM,QAAQ;EAAS,QAAQ;CAAmB;CAC7F;EAAE,SAAS;EAA+C,OAAO;EAAgB,QAAQ;EAAO,QAAQ;CAAG;CAE3G;EACI,SAAS;EACT,OAAO;EACP,QAAQ;EACR,QAAQ;CACZ;CAEA;EAAE,SAAS;EAAW,QAAQ;EAAe,OAAO;EAAY,QAAQ;EAAa,QAAQ;CAAG;CAChG;EAAE,SAAS;EAAwD,OAAO;EAAY,QAAQ;EAAa,QAAQ;CAAG;CACtH;EAAE,SAAS;EAAoD,OAAO;EAAY,QAAQ;EAAa,QAAQ;CAAG;CAClH;EAAE,SAAS;EAA2F,OAAO;EAAY,QAAQ;EAAa,QAAQ;CAAG;CACzJ;EAAE,SAAS;EAA6C,OAAO;EAAY,QAAQ;EAAa,QAAQ;CAAG;AAC/G;;AAGA,SAAS,QAAQ,YAAoB,OAA2C;CAC5E,OAAO,mBAAmB,MAAM,SAC5B,KAAK,QAAQ,KAAK,UAAU,MAAM,CAAC,KAAK,UAAW,UAAU,KAAA,KAAa,KAAK,OAAO,KAAK,KAAK,EAAG;AAC3G;AAEA,SAAgB,gBAAgB,YAAoB,OAAyB;CACzE,OAAO,QAAQ,YAAY,KAAK,MAAM,KAAA;AAC1C;;AAeA,SAAS,UAAU,QAAwB;CACvC,OAAO,mDAAmD,OAAO;AACrE;AAEA,SAAS,WAAW,OAAuB;CACvC,OAAO,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;AACzC;;;;;AAMA,IAAM,iBAAiB;;;;;;;;;;;AAYvB,SAAgB,eAAe,QAAkC;CAC7D,MAAM,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK;CAChD,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,QA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
+ export { resolveDevDatabase };
@@ -84,6 +84,15 @@ export declare function parseResourceGraph(contents: string): ResourceGraph;
84
84
  * in the graph, so a status view built only from declarations would show an
85
85
  * empty screen to the majority of projects — the ones that most need to be told
86
86
  * which variable their one database reads.
87
+ *
88
+ * Declaring a *named* one leaves the default where it is, as the server does
89
+ * (`resolveDataSources` and `resolveStorageSources` in `@rebasepro/server`):
90
+ * `bucket("media")` adds a source and never moves the files the default holds,
91
+ * so both are listed. The default is displaced only by declaring it — or, for a
92
+ * bucket, by marking exactly one server-side bucket `default: true`, which then
93
+ * serves the uploads that name no `storageSource`. This used to drop the
94
+ * default once a bucket was declared, and `rebase status` and `rebase
95
+ * resources` stopped listing a source the server was still serving.
87
96
  */
88
97
  export declare function withImplicitDefaults(graph: ResourceGraph): {
89
98
  declaration: ResourceDeclaration;
@@ -1,7 +1,7 @@
1
1
  import { i as failAsJson, p as requireProjectRoot } from "./project-Wp2zoyeN.js";
2
- import { n as parseCommandArgs, r as wantsHelp } from "./args-CcBphFdj.js";
2
+ import { n as parseCommandArgs, r as wantsHelp } from "./args-BX0YD14a.js";
3
3
  import { d as findBackendApp, o as ManifestError, p as loadManifest } from "./manifest-DRp0UVTj.js";
4
- import { a as projectResourceGraph, l as writeResourceGraphFile, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-Dl0z2OWi.js";
4
+ import { a as projectResourceGraph, l as writeResourceGraphFile, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-CsoFGAnK.js";
5
5
  import chalk from "chalk";
6
6
  import path from "path";
7
7
  import { declaredSubscriptions } from "@rebasepro/types";
@@ -180,4 +180,4 @@ async function resourcesCommand(rawArgs) {
180
180
  //#endregion
181
181
  export { resourcesCommand };
182
182
 
183
- //# sourceMappingURL=resources-CLm6g0br.js.map
183
+ //# sourceMappingURL=resources-BdNRDEAy.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resources-CLm6g0br.js","names":[],"sources":["../src/commands/resources.ts"],"sourcesContent":["/**\n * CLI command: rebase resources\n *\n * Shows what a project declares, and keeps the committed graph honest.\n *\n * The graph is generated, so it can drift the moment somebody adds a bucket and\n * does not regenerate. Drift here is not cosmetic: the committed file is what a\n * host reads to decide what to provision, so a stale one means the console\n * offers a project one set of resources while the runtime asks for another.\n * `--check` is the gate that makes that impossible to land.\n */\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport { failAsJson, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError } from \"../manifest\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport {\n RESOURCE_GRAPH_FILENAME,\n deriveOptionsFor, deriveResourceGraph,\n projectResourceGraph,\n readResourceGraphFile,\n serializeResourceGraph,\n writeResourceGraphFile,\n type ProjectedResource\n} from \"../resources/derive\";\nimport { declaredSubscriptions, type RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase resources\")} — what this project needs\n\n ${chalk.blue(\"rebase resources\")} List them, declared and implicit\n ${chalk.blue(\"rebase resources --write\")} Regenerate ${RESOURCE_GRAPH_FILENAME}\n ${chalk.blue(\"rebase resources --check\")} Fail if the committed graph is stale\n ${chalk.blue(\"rebase resources --json\")} The same set, machine-readable; with --check or --write,\n their result too (a failed check is an error envelope, exit 1)\n\nA resource is declared in config code — ${chalk.gray('database(\"analytics\"), bucket(\"media\"), topic(\"signups\")')} —\nand never in ${RESOURCE_GRAPH_FILENAME}, which is generated from those declarations so a host\ncan read what a project needs without building it. A backend also has a default\ndatabase and a default storage source nobody declared; both are listed here,\nmarked ${chalk.gray(\"implicit\")}, and neither is written to that file — the host supplies them.\n`);\n}\n\n/**\n * Render the projection the way somebody reads it: grouped by kind, key first.\n *\n * The projection, not the raw graph. `rebase status` has always included the\n * implicit default database and bucket and this listing did not, so the two\n * commands answered \"what does this project need\" differently on the same stock\n * scaffold. There is no \"no resources declared\" case any more: a backend has a\n * database and a storage source whether or not anyone wrote them down.\n */\nfunction print(resources: ProjectedResource[]): void {\n // Infrastructure first, then code: what needs binding is what a reader\n // is here to check.\n const order = [\"database\", \"bucket\", \"topic\", \"queue\", \"cron\", \"function\"];\n const kinds = [...new Set(resources.map(r => r.kind))]\n .sort((a, b) => (order.indexOf(a) === -1 ? 99 : order.indexOf(a)) - (order.indexOf(b) === -1 ? 99 : order.indexOf(b)));\n for (const kind of kinds) {\n console.log(`\\n ${chalk.bold(kind)}`);\n for (const r of resources.filter(x => x.kind === kind)) {\n const bits: string[] = [];\n if (kind === \"cron\") {\n bits.push(chalk.cyan(String(r.options.schedule)));\n bits.push(chalk.gray(r.options.timezone ? String(r.options.timezone) : \"local time\"));\n } else if (kind === \"function\") {\n bits.push(chalk.gray(String(r.options.file ?? \"\")));\n if (r.options.portable === false) bits.push(chalk.yellow(\"node-only\"));\n } else {\n bits.push(chalk.gray(r.engine));\n if (r.transport !== \"server\") bits.push(chalk.yellow(r.transport));\n for (const [k, v] of Object.entries(r.options)) bits.push(chalk.gray(`${k}=${String(v)}`));\n }\n // Marked, not hidden: a declared resource is recorded in\n // `rebase.resources.json` for a host to provision, and an implicit\n // one is a default the runtime supplies regardless.\n if (r.implicit) bits.push(chalk.gray(\"implicit\"));\n console.log(` ${r.key.padEnd(24)} ${bits.join(\" · \")}`);\n if (kind === \"topic\") {\n for (const sub of declaredSubscriptions(r.key)) {\n console.log(` ${chalk.gray(\"→\")} ${sub.name}`);\n }\n }\n if (r.usedBy && r.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(r.usedBy.join(\", \"))}`);\n }\n }\n }\n console.log(\"\");\n}\n\nexport async function resourcesCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: {\n \"--write\": Boolean,\n \"--check\": Boolean,\n \"--json\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"resources\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, for the reason in `failAsJson`:\n // `--json` is a promise about stdout, and a promise kept on one exit of a\n // command and broken on the next is not one.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backendApp: RebaseBackendAppConfig;\n try {\n const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (!backend) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backendApp = backend.app;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The projection, so this and `rebase status --json` describe the same\n // set. `version` is kept so a reader of either can tell them apart from a\n // future shape. `--check` and `--write` add what they did to it: `--json`\n // changes how the answer is printed, never which question is answered — it\n // used to return here, so `--check --json` exited 0 on any drift and\n // `--write --json` wrote nothing.\n const projection = () => ({ version: graph.version, resources: projectResourceGraph(graph) });\n\n if (flags[\"--check\"]) {\n const committed = readResourceGraphFile(projectRoot);\n const expected = serializeResourceGraph(graph);\n // Declaring nothing and having no file is a consistent state, not a\n // stale one. The file records declarations; a project with none has\n // nothing to record, and its default database and bucket are implicit\n // by design — that is the overwhelmingly common project and it must not\n // be required to commit an empty file saying so.\n //\n // This mattered the moment the check was put in a gate: it would have\n // failed this repository's own reference app, which declares nothing,\n // and every scaffolded project until someone declared a second bucket.\n const status = committed === expected\n ? \"current\"\n : committed === null && graph.resources.length === 0 ? \"nothing-declared\" : null;\n\n if (status !== null) {\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), check: { file: RESOURCE_GRAPH_FILENAME, status } }, null, 2));\n return;\n }\n console.log(status === \"current\"\n ? chalk.green(`✓ ${RESOURCE_GRAPH_FILENAME} matches the declarations.`)\n : chalk.gray(\"✓ Nothing declared, so there is nothing to record.\"));\n return;\n }\n\n const state = committed === null ? \"missing\" : \"stale\";\n if (asJson) {\n failAsJson(\n `${RESOURCE_GRAPH_FILENAME} is ${state}.`,\n `resource_graph_${state}`,\n \"Regenerate it with `rebase resources --write`, and commit it.\"\n );\n }\n console.error(chalk.red(`\\n✗ ${RESOURCE_GRAPH_FILENAME} is ${state}.\\n`));\n console.error(\n \" A host reads this file to decide what to provision, so a stale one means the\\n\" +\n \" console offers one set of resources while the runtime asks for another.\\n\"\n );\n console.error(` Regenerate it: ${chalk.blue(\"rebase resources --write\")}\\n`);\n process.exitCode = 1;\n return;\n }\n\n if (flags[\"--write\"]) {\n const { changed, file } = writeResourceGraphFile(projectRoot, graph);\n const relative = path.relative(projectRoot, file);\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), written: { file: relative, changed } }, null, 2));\n return;\n }\n console.log(changed\n ? chalk.green(`✓ Wrote ${relative}`)\n : chalk.gray(`${relative} already matched the declarations.`));\n return;\n }\n\n if (asJson) {\n console.log(JSON.stringify(projection(), null, 2));\n return;\n }\n\n print(proj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M,CAAC,CAAC;IAC1G;GACJ;GACA,QAAQ,IAAI,WAAW,YACjB,MAAM,MAAM,KAAK,wBAAwB,2BAA2B,IACpE,MAAM,KAAK,oDAAoD,CAAC;GACtE;EACJ;EAEA,MAAM,QAAQ,cAAc,OAAO,YAAY;EAC/C,IAAI,QACA,WACI,GAAG,wBAAwB,MAAM,MAAM,IACvC,kBAAkB,SAClB,+DACJ;EAEJ,QAAQ,MAAM,MAAM,IAAI,OAAO,wBAAwB,MAAM,MAAM,IAAI,CAAC;EACxE,QAAQ,MACJ,6JAEJ;EACA,QAAQ,MAAM,qBAAqB,MAAM,KAAK,0BAA0B,EAAE,GAAG;EAC7E,QAAQ,WAAW;EACnB;CACJ;CAEA,IAAI,MAAM,YAAY;EAClB,MAAM,EAAE,SAAS,SAAS,uBAAuB,aAAa,KAAK;EACnE,MAAM,WAAW,KAAK,SAAS,aAAa,IAAI;EAChD,IAAI,QAAQ;GACR,QAAQ,IAAI,KAAK,UAAU;IAAE,GAAG,WAAW;IAAG,SAAS;KAAE,MAAM;KAAU;IAAQ;GAAE,GAAG,MAAM,CAAC,CAAC;GAC9F;EACJ;EACA,QAAQ,IAAI,UACN,MAAM,MAAM,WAAW,UAAU,IACjC,MAAM,KAAK,GAAG,SAAS,mCAAmC,CAAC;EACjE;CACJ;CAEA,IAAI,QAAQ;EACR,QAAQ,IAAI,KAAK,UAAU,WAAW,GAAG,MAAM,CAAC,CAAC;EACjD;CACJ;CAEA,MAAM,qBAAqB,KAAK,CAAC;AACrC"}
1
+ {"version":3,"file":"resources-BdNRDEAy.js","names":[],"sources":["../src/commands/resources.ts"],"sourcesContent":["/**\n * CLI command: rebase resources\n *\n * Shows what a project declares, and keeps the committed graph honest.\n *\n * The graph is generated, so it can drift the moment somebody adds a bucket and\n * does not regenerate. Drift here is not cosmetic: the committed file is what a\n * host reads to decide what to provision, so a stale one means the console\n * offers a project one set of resources while the runtime asks for another.\n * `--check` is the gate that makes that impossible to land.\n */\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport { failAsJson, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError } from \"../manifest\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport {\n RESOURCE_GRAPH_FILENAME,\n deriveOptionsFor, deriveResourceGraph,\n projectResourceGraph,\n readResourceGraphFile,\n serializeResourceGraph,\n writeResourceGraphFile,\n type ProjectedResource\n} from \"../resources/derive\";\nimport { declaredSubscriptions, type RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase resources\")} — what this project needs\n\n ${chalk.blue(\"rebase resources\")} List them, declared and implicit\n ${chalk.blue(\"rebase resources --write\")} Regenerate ${RESOURCE_GRAPH_FILENAME}\n ${chalk.blue(\"rebase resources --check\")} Fail if the committed graph is stale\n ${chalk.blue(\"rebase resources --json\")} The same set, machine-readable; with --check or --write,\n their result too (a failed check is an error envelope, exit 1)\n\nA resource is declared in config code — ${chalk.gray('database(\"analytics\"), bucket(\"media\"), topic(\"signups\")')} —\nand never in ${RESOURCE_GRAPH_FILENAME}, which is generated from those declarations so a host\ncan read what a project needs without building it. A backend also has a default\ndatabase and a default storage source nobody declared; both are listed here,\nmarked ${chalk.gray(\"implicit\")}, and neither is written to that file — the host supplies them.\n`);\n}\n\n/**\n * Render the projection the way somebody reads it: grouped by kind, key first.\n *\n * The projection, not the raw graph. `rebase status` has always included the\n * implicit default database and bucket and this listing did not, so the two\n * commands answered \"what does this project need\" differently on the same stock\n * scaffold. There is no \"no resources declared\" case any more: a backend has a\n * database and a storage source whether or not anyone wrote them down.\n */\nfunction print(resources: ProjectedResource[]): void {\n // Infrastructure first, then code: what needs binding is what a reader\n // is here to check.\n const order = [\"database\", \"bucket\", \"topic\", \"queue\", \"cron\", \"function\"];\n const kinds = [...new Set(resources.map(r => r.kind))]\n .sort((a, b) => (order.indexOf(a) === -1 ? 99 : order.indexOf(a)) - (order.indexOf(b) === -1 ? 99 : order.indexOf(b)));\n for (const kind of kinds) {\n console.log(`\\n ${chalk.bold(kind)}`);\n for (const r of resources.filter(x => x.kind === kind)) {\n const bits: string[] = [];\n if (kind === \"cron\") {\n bits.push(chalk.cyan(String(r.options.schedule)));\n bits.push(chalk.gray(r.options.timezone ? String(r.options.timezone) : \"local time\"));\n } else if (kind === \"function\") {\n bits.push(chalk.gray(String(r.options.file ?? \"\")));\n if (r.options.portable === false) bits.push(chalk.yellow(\"node-only\"));\n } else {\n bits.push(chalk.gray(r.engine));\n if (r.transport !== \"server\") bits.push(chalk.yellow(r.transport));\n for (const [k, v] of Object.entries(r.options)) bits.push(chalk.gray(`${k}=${String(v)}`));\n }\n // Marked, not hidden: a declared resource is recorded in\n // `rebase.resources.json` for a host to provision, and an implicit\n // one is a default the runtime supplies regardless.\n if (r.implicit) bits.push(chalk.gray(\"implicit\"));\n console.log(` ${r.key.padEnd(24)} ${bits.join(\" · \")}`);\n if (kind === \"topic\") {\n for (const sub of declaredSubscriptions(r.key)) {\n console.log(` ${chalk.gray(\"→\")} ${sub.name}`);\n }\n }\n if (r.usedBy && r.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(r.usedBy.join(\", \"))}`);\n }\n }\n }\n console.log(\"\");\n}\n\nexport async function resourcesCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: {\n \"--write\": Boolean,\n \"--check\": Boolean,\n \"--json\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"resources\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, for the reason in `failAsJson`:\n // `--json` is a promise about stdout, and a promise kept on one exit of a\n // command and broken on the next is not one.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backendApp: RebaseBackendAppConfig;\n try {\n const loaded = loadManifest(projectRoot);\n const backend = findBackendApp(loaded.manifest);\n if (!backend) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backendApp = backend.app;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The projection, so this and `rebase status --json` describe the same\n // set. `version` is kept so a reader of either can tell them apart from a\n // future shape. `--check` and `--write` add what they did to it: `--json`\n // changes how the answer is printed, never which question is answered — it\n // used to return here, so `--check --json` exited 0 on any drift and\n // `--write --json` wrote nothing.\n const projection = () => ({ version: graph.version, resources: projectResourceGraph(graph) });\n\n if (flags[\"--check\"]) {\n const committed = readResourceGraphFile(projectRoot);\n const expected = serializeResourceGraph(graph);\n // Declaring nothing and having no file is a consistent state, not a\n // stale one. The file records declarations; a project with none has\n // nothing to record, and its default database and bucket are implicit\n // by design — that is the overwhelmingly common project and it must not\n // be required to commit an empty file saying so.\n //\n // This mattered the moment the check was put in a gate: it would have\n // failed this repository's own reference app, which declares nothing,\n // and every scaffolded project until someone declared a second bucket.\n const status = committed === expected\n ? \"current\"\n : committed === null && graph.resources.length === 0 ? \"nothing-declared\" : null;\n\n if (status !== null) {\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), check: { file: RESOURCE_GRAPH_FILENAME, status } }, null, 2));\n return;\n }\n console.log(status === \"current\"\n ? chalk.green(`✓ ${RESOURCE_GRAPH_FILENAME} matches the declarations.`)\n : chalk.gray(\"✓ Nothing declared, so there is nothing to record.\"));\n return;\n }\n\n const state = committed === null ? \"missing\" : \"stale\";\n if (asJson) {\n failAsJson(\n `${RESOURCE_GRAPH_FILENAME} is ${state}.`,\n `resource_graph_${state}`,\n \"Regenerate it with `rebase resources --write`, and commit it.\"\n );\n }\n console.error(chalk.red(`\\n✗ ${RESOURCE_GRAPH_FILENAME} is ${state}.\\n`));\n console.error(\n \" A host reads this file to decide what to provision, so a stale one means the\\n\" +\n \" console offers one set of resources while the runtime asks for another.\\n\"\n );\n console.error(` Regenerate it: ${chalk.blue(\"rebase resources --write\")}\\n`);\n process.exitCode = 1;\n return;\n }\n\n if (flags[\"--write\"]) {\n const { changed, file } = writeResourceGraphFile(projectRoot, graph);\n const relative = path.relative(projectRoot, file);\n if (asJson) {\n console.log(JSON.stringify({ ...projection(), written: { file: relative, changed } }, null, 2));\n return;\n }\n console.log(changed\n ? chalk.green(`✓ Wrote ${relative}`)\n : chalk.gray(`${relative} already matched the declarations.`));\n return;\n }\n\n if (asJson) {\n console.log(JSON.stringify(projection(), null, 2));\n return;\n }\n\n print(projectResourceGraph(graph));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,SAAS,QAAc;CACnB,QAAQ,IAAI;EACd,MAAM,KAAK,kBAAkB,EAAE;;IAE7B,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,0BAA0B,EAAE,iBAAiB,wBAAwB;IAChF,MAAM,KAAK,0BAA0B,EAAE;IACvC,MAAM,KAAK,yBAAyB,EAAE;;;0CAGA,MAAM,KAAK,gEAA0D,EAAE;eAClG,wBAAwB;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;EACxE,QAAQ,MACJ,6JAEJ;EACA,QAAQ,MAAM,qBAAqB,MAAM,KAAK,0BAA0B,EAAE,GAAG;EAC7E,QAAQ,WAAW;EACnB;CACJ;CAEA,IAAI,MAAM,YAAY;EAClB,MAAM,EAAE,SAAS,SAAS,uBAAuB,aAAa,KAAK;EACnE,MAAM,WAAW,KAAK,SAAS,aAAa,IAAI;EAChD,IAAI,QAAQ;GACR,QAAQ,IAAI,KAAK,UAAU;IAAE,GAAG,WAAW;IAAG,SAAS;KAAE,MAAM;KAAU;IAAQ;GAAE,GAAG,MAAM,CAAC,CAAC;GAC9F;EACJ;EACA,QAAQ,IAAI,UACN,MAAM,MAAM,WAAW,UAAU,IACjC,MAAM,KAAK,GAAG,SAAS,mCAAmC,CAAC;EACjE;CACJ;CAEA,IAAI,QAAQ;EACR,QAAQ,IAAI,KAAK,UAAU,WAAW,GAAG,MAAM,CAAC,CAAC;EACjD;CACJ;CAEA,MAAM,qBAAqB,KAAK,CAAC;AACrC"}
@@ -1,9 +1,9 @@
1
1
  import { i as recordEvent } from "./telemetry-EMFRVRQi.js";
2
2
  import { f as requireBackendDir, h as resolvePluginCliScript, l as getActiveBackendPlugin, o as findEnvFile, p as requireProjectRoot, r as exitDependenciesNotInstalled } from "./project-Wp2zoyeN.js";
3
- import { a as unknownCommand, r as wantsHelp } from "./args-CcBphFdj.js";
3
+ import { a as unknownCommand, r as wantsHelp } from "./args-BX0YD14a.js";
4
4
  import { r as refuseMissingCollectionsPath, t as COLLECTIONS_FLAG_HELP } from "./path-flags-BFgG9V6y.js";
5
- import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-C1iaiTC4.js";
6
- import { absolutizeLocalPathArgs, ensureDockerDatabase, n as argsFromCommand, spawnDriverCli, t as reportSpawnFailure } from "./db-Dkn9XhT-.js";
5
+ import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-DdnU70z8.js";
6
+ import { absolutizeLocalPathArgs, ensureDockerDatabase, n as argsFromCommand, spawnDriverCli, t as reportSpawnFailure } from "./db-CRNpA5mH.js";
7
7
  import chalk from "chalk";
8
8
  import arg from "arg";
9
9
  //#region src/commands/schema.ts
@@ -148,4 +148,4 @@ ${chalk.green.bold("stale Options")}
148
148
  //#endregion
149
149
  export { SCHEMA_SUBCOMMANDS, schemaCommand };
150
150
 
151
- //# sourceMappingURL=schema-BKdh6UoE.js.map
151
+ //# sourceMappingURL=schema-B0-p6T1O.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-BKdh6UoE.js","names":[],"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,MAA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B,MAAM,KAAK,kBAAkB,EAAE,mDAAmD,MAAM,KAAK,sBAAsB,EAAE;IACrH,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
1
+ {"version":3,"file":"schema-B0-p6T1O.js","names":[],"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,W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;CACvB;AACD"}
@@ -1,5 +1,5 @@
1
1
  import { c as findProjectRoot } from "./project-Wp2zoyeN.js";
2
- import { a as unknownCommand, n as parseCommandArgs, r as wantsHelp, t as UsageError } from "./args-CcBphFdj.js";
2
+ import { a as unknownCommand, n as parseCommandArgs, r as wantsHelp, t as UsageError } from "./args-BX0YD14a.js";
3
3
  import chalk from "chalk";
4
4
  import fs from "fs";
5
5
  import os from "os";
@@ -571,7 +571,7 @@ async function skillsInstall(rawArgs = []) {
571
571
  console.log(chalk.yellow(" Edited files were left as they are. To replace them with the bundle's copy:"));
572
572
  console.log(` ${chalk.cyan("rebase skills install --force")}`);
573
573
  }
574
- const { MCP_SERVER_NAME, ensureMcpDependency, mcpDependencyNote, mcpServerRegistered, writeMcpConfig } = await import("./agent-setup-C83DXnlx.js");
574
+ const { MCP_SERVER_NAME, ensureMcpDependency, mcpDependencyNote, mcpServerRegistered, writeMcpConfig } = await import("./agent-setup-B5AKHOgt.js");
575
575
  const { detectPackageManager } = await import("./package-manager-DSEOwTqM.js").then((n) => n.r);
576
576
  const shownFile = (file) => path.relative(process.cwd(), path.join(projectDir, file)) || file;
577
577
  if (withMcp) {
@@ -638,4 +638,4 @@ ${chalk.green.bold("Examples")}
638
638
  //#endregion
639
639
  export { AGENTS, AGENT_KEYS, SKILLS_SUBCOMMANDS, detectInstalledAgents, installSkills, loadBundledSkills, resolveAgentNames, skillsCommand };
640
640
 
641
- //# sourceMappingURL=skills-DEhYiPeO.js.map
641
+ //# sourceMappingURL=skills-DfnTeyRz.js.map