@rebasepro/cli 0.30.0 → 0.31.0-canary.g902a0ce

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 (285) hide show
  1. package/README.md +8 -7
  2. package/dist/{agent-setup-0uyfC7VX.js → agent-setup-DqAcoDcn.js} +10 -5
  3. package/dist/{agent-setup-0uyfC7VX.js.map → agent-setup-DqAcoDcn.js.map} +1 -1
  4. package/dist/{api-keys-Dfw5-9s1.js → api-keys-eIUjMqWn.js} +8 -7
  5. package/dist/api-keys-eIUjMqWn.js.map +1 -0
  6. package/dist/{apps-MKQbgDtN.js → apps-DExO4PEl.js} +8 -7
  7. package/dist/apps-DExO4PEl.js.map +1 -0
  8. package/dist/{project-CasK56vN.js → args-CaCcrYE1.js} +2 -351
  9. package/dist/args-CaCcrYE1.js.map +1 -0
  10. package/dist/{atlas-dev-database-BODqdCWt.js → atlas-dev-database-DOCKk6ht.js} +2 -2
  11. package/dist/{atlas-dev-database-BODqdCWt.js.map → atlas-dev-database-DOCKk6ht.js.map} +1 -1
  12. package/dist/{auth-Bv0rTbQX.js → auth-CyADghFQ.js} +7 -6
  13. package/dist/{auth-Bv0rTbQX.js.map → auth-CyADghFQ.js.map} +1 -1
  14. package/dist/backend-guard-C0mVkXBw.js +162 -0
  15. package/dist/backend-guard-C0mVkXBw.js.map +1 -0
  16. package/dist/{branch-pointer-BQUF6lYa.js → branch-pointer-DMPyvZoK.js} +1 -1
  17. package/dist/{build-BuKTnec8.js → build-CA5R07tw.js} +29 -9
  18. package/dist/build-CA5R07tw.js.map +1 -0
  19. package/dist/{bundle-BAH4FCju.js → bundle-DgILeA5b.js} +112 -138
  20. package/dist/bundle-DgILeA5b.js.map +1 -0
  21. package/dist/bundle.d.ts +35 -12
  22. package/dist/cli.d.ts +2 -2
  23. package/dist/{cloud-Cj5ey3l_.js → cloud-CYMk92iG.js} +217 -104
  24. package/dist/cloud-CYMk92iG.js.map +1 -0
  25. package/dist/cms-directories-BK3vcswg.js +33 -0
  26. package/dist/cms-directories-BK3vcswg.js.map +1 -0
  27. package/dist/codemod/collections-to-tables/ast.d.ts +135 -0
  28. package/dist/codemod/collections-to-tables/backend.d.ts +38 -0
  29. package/dist/codemod/collections-to-tables/command.d.ts +35 -0
  30. package/dist/codemod/collections-to-tables/comments.d.ts +45 -0
  31. package/dist/codemod/collections-to-tables/customization.d.ts +47 -0
  32. package/dist/codemod/collections-to-tables/dynamic-props.d.ts +34 -0
  33. package/dist/codemod/collections-to-tables/export-changes.d.ts +83 -0
  34. package/dist/codemod/collections-to-tables/firestore.d.ts +11 -0
  35. package/dist/codemod/collections-to-tables/helper-hooks.d.ts +41 -0
  36. package/dist/codemod/collections-to-tables/hooks.d.ts +44 -0
  37. package/dist/codemod/collections-to-tables/journal.d.ts +10 -0
  38. package/dist/codemod/collections-to-tables/legacy-shims.d.ts +52 -0
  39. package/dist/codemod/collections-to-tables/load-legacy.d.ts +81 -0
  40. package/dist/codemod/collections-to-tables/migrate.d.ts +20 -0
  41. package/dist/codemod/collections-to-tables/modules.d.ts +127 -0
  42. package/dist/codemod/collections-to-tables/moved-imports.d.ts +70 -0
  43. package/dist/codemod/collections-to-tables/moved-symbols.generated.d.ts +12 -0
  44. package/dist/codemod/collections-to-tables/own.d.ts +10 -0
  45. package/dist/codemod/collections-to-tables/path-aliases.d.ts +26 -0
  46. package/dist/codemod/collections-to-tables/plan-context.d.ts +49 -0
  47. package/dist/codemod/collections-to-tables/print-js.d.ts +44 -0
  48. package/dist/codemod/collections-to-tables/project-files.d.ts +144 -0
  49. package/dist/codemod/collections-to-tables/repoint.d.ts +50 -0
  50. package/dist/codemod/collections-to-tables/row-hands.d.ts +7 -0
  51. package/dist/codemod/collections-to-tables/sdk-calls.d.ts +88 -0
  52. package/dist/codemod/collections-to-tables/skills-step.d.ts +13 -0
  53. package/dist/codemod/collections-to-tables/split-constants.d.ts +42 -0
  54. package/dist/codemod/collections-to-tables/storage-paths.d.ts +28 -0
  55. package/dist/codemod/collections-to-tables/types.d.ts +164 -0
  56. package/dist/codemod/collections-to-tables/verify.d.ts +27 -0
  57. package/dist/codemod/collections-to-tables/vocabulary.d.ts +40 -0
  58. package/dist/command-D5lhW_-B.js +9984 -0
  59. package/dist/command-D5lhW_-B.js.map +1 -0
  60. package/dist/commands/agent-setup.d.ts +6 -2
  61. package/dist/commands/cloud/auth.d.ts +2 -0
  62. package/dist/commands/cloud/context.d.ts +1 -1
  63. package/dist/commands/cloud/init.d.ts +2 -2
  64. package/dist/commands/cloud/login-flow.d.ts +30 -1
  65. package/dist/commands/console.d.ts +1 -2
  66. package/dist/commands/db.d.ts +5 -6
  67. package/dist/commands/dev.d.ts +18 -17
  68. package/dist/commands/doctor.d.ts +4 -5
  69. package/dist/commands/eject.d.ts +17 -13
  70. package/dist/commands/generate-view.d.ts +20 -9
  71. package/dist/commands/generate_sdk.d.ts +27 -27
  72. package/dist/commands/init.d.ts +21 -8
  73. package/dist/commands/migrate.d.ts +24 -0
  74. package/dist/commands/schema-reconcile.d.ts +1 -1
  75. package/dist/commands/skills.d.ts +8 -0
  76. package/dist/commands/verify-cms.d.ts +28 -0
  77. package/dist/commands/verify.d.ts +14 -9
  78. package/dist/{consent-BD7F29T3.js → consent-BXLIrMl8.js} +2 -2
  79. package/dist/{consent-BD7F29T3.js.map → consent-BXLIrMl8.js.map} +1 -1
  80. package/dist/{console-CdwIYOMV.js → console-CMjhgMUE.js} +14 -14
  81. package/dist/console-CMjhgMUE.js.map +1 -0
  82. package/dist/{context-AXdAh-q8.js → context--JwaHaZp.js} +6 -5
  83. package/dist/context--JwaHaZp.js.map +1 -0
  84. package/dist/{daemon-Cp7oNXth.js → daemon-w30PsdwV.js} +2 -2
  85. package/dist/{daemon-Cp7oNXth.js.map → daemon-w30PsdwV.js.map} +1 -1
  86. package/dist/{db-DBbKpjYX.js → db-A7XDCIIO.js} +51 -51
  87. package/dist/db-A7XDCIIO.js.map +1 -0
  88. package/dist/{derive-ae9UOoOB.js → derive-C3ezmY-p.js} +105 -133
  89. package/dist/derive-C3ezmY-p.js.map +1 -0
  90. package/dist/dev-db/attver.d.ts +11 -0
  91. package/dist/{dev-preflight-Cxv3TiD1.js → dev-preflight-DjvcV6SK.js} +5 -5
  92. package/dist/dev-preflight-DjvcV6SK.js.map +1 -0
  93. package/dist/{dev-server-OJsUGZEB.js → dev-server-BLxCbQEP.js} +2 -2
  94. package/dist/{dev-server-OJsUGZEB.js.map → dev-server-BLxCbQEP.js.map} +1 -1
  95. package/dist/{dev-C93d4QIv.js → dev-tWwPyWkQ.js} +142 -84
  96. package/dist/dev-tWwPyWkQ.js.map +1 -0
  97. package/dist/{doctor-BBPQUO2g.js → doctor-BBM0dWvZ.js} +39 -62
  98. package/dist/doctor-BBM0dWvZ.js.map +1 -0
  99. package/dist/doctor-environment.d.ts +6 -6
  100. package/dist/{eject-DABcDnPN.js → eject-Bhzd6hgb.js} +25 -16
  101. package/dist/eject-Bhzd6hgb.js.map +1 -0
  102. package/dist/{fold-static-BWzxNn06.js → fold-static-CKewnAPX.js} +5 -3
  103. package/dist/fold-static-CKewnAPX.js.map +1 -0
  104. package/dist/{generate-view-IFwCADvb.js → generate-view-CTOluXvH.js} +160 -89
  105. package/dist/generate-view-CTOluXvH.js.map +1 -0
  106. package/dist/{generate_sdk-DNmNuFuW.js → generate_sdk-De-aLC1L.js} +120 -137
  107. package/dist/generate_sdk-De-aLC1L.js.map +1 -0
  108. package/dist/import-schema-module-Df67TIWj.js +51 -0
  109. package/dist/import-schema-module-Df67TIWj.js.map +1 -0
  110. package/dist/index.es.js +64 -51
  111. package/dist/index.es.js.map +1 -1
  112. package/dist/{init-vL1DWOeC.js → init-Dtl-IcXf.js} +83 -80
  113. package/dist/init-Dtl-IcXf.js.map +1 -0
  114. package/dist/last-dev-database-Dc8cP01o.js +2 -0
  115. package/dist/{manifest-BtzDy7KQ.js → manifest-C3uLDrrJ.js} +115 -40
  116. package/dist/manifest-C3uLDrrJ.js.map +1 -0
  117. package/dist/manifest.d.ts +79 -24
  118. package/dist/migrate-VrKoi3nB.js +138 -0
  119. package/dist/migrate-VrKoi3nB.js.map +1 -0
  120. package/dist/{normalize-imports-Bd5Y4yLp.js → normalize-imports-DwxqEMYq.js} +3 -3
  121. package/dist/{normalize-imports-Bd5Y4yLp.js.map → normalize-imports-DwxqEMYq.js.map} +1 -1
  122. package/dist/path-flags-7O5uPBcQ.js +139 -0
  123. package/dist/path-flags-7O5uPBcQ.js.map +1 -0
  124. package/dist/{prepare-CTw9NEkh.js → prepare-Ccxspoj-.js} +4 -4
  125. package/dist/{prepare-CTw9NEkh.js.map → prepare-Ccxspoj-.js.map} +1 -1
  126. package/dist/project-CLcF5i8c.js +360 -0
  127. package/dist/project-CLcF5i8c.js.map +1 -0
  128. package/dist/project-schema-CsSOG2gE.js +30 -0
  129. package/dist/project-schema-CsSOG2gE.js.map +1 -0
  130. package/dist/{pull-DDMpsZ5r.js → pull-D9WvpDYY.js} +189 -1
  131. package/dist/pull-D9WvpDYY.js.map +1 -0
  132. package/dist/resolve-BY7bSFRT.js +2 -0
  133. package/dist/resources/derive.d.ts +19 -13
  134. package/dist/{resources-CPSC5Kcu.js → resources-Dpfs2y8P.js} +5 -4
  135. package/dist/{resources-CPSC5Kcu.js.map → resources-Dpfs2y8P.js.map} +1 -1
  136. package/dist/{schema-DtLPsXbT.js → schema-DwFDI1iU.js} +41 -39
  137. package/dist/schema-DwFDI1iU.js.map +1 -0
  138. package/dist/schema-dir-Cd1kvYbf.js +98 -0
  139. package/dist/schema-dir-Cd1kvYbf.js.map +1 -0
  140. package/dist/schema-reconcile-Tto54Qbv.js +2 -0
  141. package/dist/schema-text-CpNrsuMe.js +73 -0
  142. package/dist/schema-text-CpNrsuMe.js.map +1 -0
  143. package/dist/{skills-CbwV6vw_.js → skills-CXjA9TWw.js} +54 -10
  144. package/dist/skills-CXjA9TWw.js.map +1 -0
  145. package/dist/{start-YOr3X5Zm.js → start-Bwbtt2W5.js} +7 -10
  146. package/dist/{start-YOr3X5Zm.js.map → start-Bwbtt2W5.js.map} +1 -1
  147. package/dist/{status-BREvtzJm.js → status-DQ_PPz4C.js} +12 -12
  148. package/dist/status-DQ_PPz4C.js.map +1 -0
  149. package/dist/{storage-CO9ouK76.js → storage-iTqj5-Av.js} +12 -11
  150. package/dist/storage-iTqj5-Av.js.map +1 -0
  151. package/dist/{telemetry-DwK5RQJl.js → telemetry-BP_1Cl9r.js} +4 -4
  152. package/dist/{telemetry-DwK5RQJl.js.map → telemetry-BP_1Cl9r.js.map} +1 -1
  153. package/dist/{telemetry-CgwJPVMO.js → telemetry-M3HjlyhZ.js} +2 -2
  154. package/dist/{telemetry-CgwJPVMO.js.map → telemetry-M3HjlyhZ.js.map} +1 -1
  155. package/dist/{upgrade-B7sVwL8S.js → upgrade-oZzJ13jM.js} +5 -4
  156. package/dist/{upgrade-B7sVwL8S.js.map → upgrade-oZzJ13jM.js.map} +1 -1
  157. package/dist/utils/backend-guard.d.ts +47 -0
  158. package/dist/utils/cms-directories.d.ts +6 -0
  159. package/dist/utils/dev-preflight.d.ts +2 -2
  160. package/dist/utils/import-schema-module.d.ts +16 -0
  161. package/dist/utils/path-flags.d.ts +35 -16
  162. package/dist/utils/project-schema.d.ts +40 -0
  163. package/dist/utils/project.d.ts +8 -2
  164. package/dist/utils/schema-dir.d.ts +32 -0
  165. package/dist/utils/schema-drift.d.ts +6 -0
  166. package/dist/utils/schema-text.d.ts +24 -0
  167. package/dist/verify-DkJqhYPI.js +1160 -0
  168. package/dist/verify-DkJqhYPI.js.map +1 -0
  169. package/package.json +11 -8
  170. package/runtime/dev-server.mjs +5 -1
  171. package/templates/eject/Dockerfile +1 -4
  172. package/templates/eject/backend/src/env.ts +1 -1
  173. package/templates/eject/backend/src/index.ts +53 -40
  174. package/templates/eject/docker-compose.custom.yml +1 -1
  175. package/templates/overlays/baas/README.md +39 -12
  176. package/templates/overlays/baas/ai-instructions.md +8 -8
  177. package/templates/overlays/baas/{config → backend}/storage.ts +3 -4
  178. package/templates/overlays/baas/backend/tsconfig.json +10 -12
  179. package/templates/overlays/baas/package.json +1 -2
  180. package/templates/overlays/baas/pnpm-workspace.yaml +0 -1
  181. package/templates/presets/blank/backend/schema/index.ts +19 -0
  182. package/templates/presets/blank/frontend/src/App.tsx +56 -0
  183. package/templates/presets/ecommerce/backend/schema/categories.ts +12 -0
  184. package/templates/presets/ecommerce/backend/schema/index.ts +23 -0
  185. package/templates/presets/ecommerce/backend/schema/orders.ts +13 -0
  186. package/templates/presets/ecommerce/backend/schema/products.ts +18 -0
  187. package/templates/presets/ecommerce/frontend/src/App.tsx +59 -0
  188. package/templates/presets/ecommerce/frontend/src/cms/categories.tsx +12 -0
  189. package/templates/presets/ecommerce/frontend/src/cms/orders.tsx +38 -0
  190. package/templates/presets/ecommerce/frontend/src/cms/products.tsx +27 -0
  191. package/templates/resource-graphs/blank.json +2 -2
  192. package/templates/resource-graphs/blog.json +5 -5
  193. package/templates/resource-graphs/ecommerce.json +5 -5
  194. package/templates/resource-graphs/headless.json +1 -1
  195. package/templates/template/.claude/hooks/post-edit-collection.sh +27 -23
  196. package/templates/template/.cursorrules +2 -2
  197. package/templates/template/.env.example +6 -17
  198. package/templates/template/.github/copilot-instructions.md +2 -2
  199. package/templates/template/.windsurfrules +2 -2
  200. package/templates/template/AGENTS.md +2 -2
  201. package/templates/template/CLAUDE.md +2 -2
  202. package/templates/template/README.md +47 -13
  203. package/templates/template/ai-instructions.md +15 -14
  204. package/templates/template/backend/functions/hello.ts +1 -1
  205. package/templates/template/backend/package.json +0 -2
  206. package/templates/template/{config → backend}/resources.ts +3 -3
  207. package/templates/template/backend/schema/authors.ts +11 -0
  208. package/templates/template/backend/schema/index.ts +29 -0
  209. package/templates/template/backend/schema/posts.ts +29 -0
  210. package/templates/template/backend/schema/tags.ts +9 -0
  211. package/templates/template/backend/schema/users.ts +32 -0
  212. package/templates/template/{config → backend}/storage.ts +4 -4
  213. package/templates/template/backend/tsconfig.json +15 -20
  214. package/templates/template/docker-compose.yml +3 -3
  215. package/templates/template/frontend/package.json +0 -2
  216. package/templates/template/frontend/src/App.tsx +10 -4
  217. package/templates/template/frontend/src/cms/authors.tsx +7 -0
  218. package/templates/template/frontend/src/cms/posts.tsx +27 -0
  219. package/templates/template/frontend/src/cms/tags.tsx +11 -0
  220. package/templates/template/frontend/src/cms/ui-config.json +3 -0
  221. package/templates/template/frontend/src/cms/users.tsx +54 -0
  222. package/templates/template/frontend/src/{virtual.d.ts → vite-env.d.ts} +0 -4
  223. package/templates/template/frontend/vite.config.ts +6 -2
  224. package/templates/template/gitignore +1 -1
  225. package/templates/template/package.json +1 -2
  226. package/templates/template/pnpm-workspace.yaml +0 -1
  227. package/templates/template/scripts/example.ts +3 -3
  228. package/templates/template/tsconfig.json +1 -1
  229. package/templates/views/AppView.tsx.tmpl +4 -4
  230. package/templates/views/EntityView.tsx.tmpl +3 -4
  231. package/dist/api-keys-Dfw5-9s1.js.map +0 -1
  232. package/dist/apps-MKQbgDtN.js.map +0 -1
  233. package/dist/build-BuKTnec8.js.map +0 -1
  234. package/dist/bundle-BAH4FCju.js.map +0 -1
  235. package/dist/cloud-Cj5ey3l_.js.map +0 -1
  236. package/dist/collection-drift-BKj_BoMq.js +0 -106
  237. package/dist/collection-drift-BKj_BoMq.js.map +0 -1
  238. package/dist/collections-dir-DlvDhime.js +0 -69
  239. package/dist/collections-dir-DlvDhime.js.map +0 -1
  240. package/dist/console-CdwIYOMV.js.map +0 -1
  241. package/dist/context-AXdAh-q8.js.map +0 -1
  242. package/dist/db-DBbKpjYX.js.map +0 -1
  243. package/dist/derive-ae9UOoOB.js.map +0 -1
  244. package/dist/dev-C93d4QIv.js.map +0 -1
  245. package/dist/dev-preflight-Cxv3TiD1.js.map +0 -1
  246. package/dist/doctor-BBPQUO2g.js.map +0 -1
  247. package/dist/eject-DABcDnPN.js.map +0 -1
  248. package/dist/fold-static-BWzxNn06.js.map +0 -1
  249. package/dist/generate-view-IFwCADvb.js.map +0 -1
  250. package/dist/generate_sdk-DNmNuFuW.js.map +0 -1
  251. package/dist/init-vL1DWOeC.js.map +0 -1
  252. package/dist/last-dev-database-DpW5dfoX.js +0 -2
  253. package/dist/manifest-BtzDy7KQ.js.map +0 -1
  254. package/dist/path-flags-DNvtEi2-.js +0 -92
  255. package/dist/path-flags-DNvtEi2-.js.map +0 -1
  256. package/dist/project-CasK56vN.js.map +0 -1
  257. package/dist/pull-DDMpsZ5r.js.map +0 -1
  258. package/dist/resolve-D647F1LA.js +0 -2
  259. package/dist/schema-DtLPsXbT.js.map +0 -1
  260. package/dist/schema-reconcile-DkArN9jF.js +0 -2
  261. package/dist/skills-CbwV6vw_.js.map +0 -1
  262. package/dist/status-BREvtzJm.js.map +0 -1
  263. package/dist/storage-CO9ouK76.js.map +0 -1
  264. package/dist/utils/collection-drift.d.ts +0 -27
  265. package/dist/utils/collections-dir.d.ts +0 -14
  266. package/dist/verify-Y3rWSgfA.js +0 -730
  267. package/dist/verify-Y3rWSgfA.js.map +0 -1
  268. package/templates/overlays/baas/config/index.ts +0 -24
  269. package/templates/overlays/baas/config/package.json +0 -30
  270. package/templates/template/config/cms.d.ts +0 -15
  271. package/templates/template/config/collections/authors.ts +0 -47
  272. package/templates/template/config/collections/index.ts +0 -44
  273. package/templates/template/config/collections/posts.ts +0 -94
  274. package/templates/template/config/collections/presets/blank/index.ts +0 -5
  275. package/templates/template/config/collections/presets/ecommerce/categories.ts +0 -42
  276. package/templates/template/config/collections/presets/ecommerce/index.ts +0 -31
  277. package/templates/template/config/collections/presets/ecommerce/orders.ts +0 -78
  278. package/templates/template/config/collections/presets/ecommerce/products.ts +0 -73
  279. package/templates/template/config/collections/tags.ts +0 -27
  280. package/templates/template/config/collections/users.ts +0 -149
  281. package/templates/template/config/frontend-assets.d.ts +0 -17
  282. package/templates/template/config/index.ts +0 -12
  283. package/templates/template/config/package.json +0 -30
  284. package/templates/template/config/tsconfig.json +0 -35
  285. /package/templates/eject/{config → backend}/resources.ts +0 -0
@@ -0,0 +1,139 @@
1
+ import { t as UsageError } from "./args-CaCcrYE1.js";
2
+ import { t as SCHEMA_DIR_FLAG } from "./schema-dir-Cd1kvYbf.js";
3
+ import chalk from "chalk";
4
+ import fs from "fs";
5
+ import path from "path";
6
+ import { LEGACY_LAYOUT_REMEDY } from "@rebasepro/types";
7
+ //#region src/utils/path-flags.ts
8
+ /**
9
+ * Where a path typed on a `rebase` command line resolves: one rule, one sentence.
10
+ *
11
+ * The driver CLI runs with `cwd: backend/` — that is where it and its
12
+ * dependencies resolve from — while people type commands from the project root
13
+ * (or anywhere else in it). So every relative path on the line is resolved by
14
+ * the CLI, from the directory the command was run in, before the driver is
15
+ * handed a different one (`absolutizeLocalPathArgs` in `commands/db.ts`).
16
+ * `generate-sdk` and `db backup --out` already worked that way, and so does
17
+ * `--schema-dir`.
18
+ *
19
+ * The sentence below is printed by every help page that takes `--schema-dir`,
20
+ * and by the refusal when the path is not there, so the rule is stated in one
21
+ * set of words wherever a reader meets it.
22
+ */
23
+ /** The rule, as every help page and error states it. */
24
+ var PATH_RESOLUTION_RULE = "relative paths are resolved from where you run the command";
25
+ /** The `--schema-dir` line of a help page. */
26
+ var SCHEMA_DIR_FLAG_HELP = `Schema directory — the one whose index.ts exports the tables (default: backend/schema, or the backend's "tables" in rebase.json); ${PATH_RESOLUTION_RULE}`;
27
+ /** The `--schema-dir` value on a line, as typed, or `null` when there is none. */
28
+ function typedSchemaDir(args) {
29
+ for (let i = 0; i < args.length; i++) {
30
+ const token = args[i];
31
+ const eq = token.indexOf("=");
32
+ if (eq > 0 && token.slice(0, eq) === "--schema-dir") return token.slice(eq + 1) || null;
33
+ if (token === "--schema-dir") {
34
+ const value = args[i + 1];
35
+ return value && !value.startsWith("-") ? value : null;
36
+ }
37
+ }
38
+ return null;
39
+ }
40
+ /**
41
+ * What a refusal over a missing `--schema-dir` path spared, by what the command
42
+ * would have done with it. Only a schema writer drops tables; a console or a
43
+ * doctor run over nothing does something else wrong, and says so.
44
+ */
45
+ var MISSING_SCHEMA_DIR_CONSEQUENCE = {
46
+ schema: [
47
+ "Nothing was generated and nothing was applied — a schema generated from a",
48
+ "directory that is not there is an empty one, and applying it would drop",
49
+ "every table it does not describe."
50
+ ],
51
+ console: ["Nothing was started — a console over a directory that is not there would", "load none of this project's tables."],
52
+ doctor: ["Nothing was checked — a directory that is not there declares no tables, so", "every table check would pass over it."],
53
+ verify: ["Nothing was verified — a directory that is not there declares no tables, so", "every step would pass over it and report 0 errors."]
54
+ };
55
+ /**
56
+ * The refusal for a `--schema-dir` path that does not exist, or `null`.
57
+ *
58
+ * Checked by the CLI, in the reader's terms, before the driver is spawned: the
59
+ * driver's own check runs in `backend/` and can only describe the path it was
60
+ * handed. A generator pointed at a directory that is not there writes an empty
61
+ * schema, and a push of an empty schema drops every table — so nothing runs.
62
+ *
63
+ * A path written from `backend/` (`--schema-dir schema`, run from the root)
64
+ * lands here, and the message says exactly what to change.
65
+ */
66
+ function missingSchemaDir(args, cwd, backendDir, use = "schema") {
67
+ const typed = typedSchemaDir(args);
68
+ if (typed === null) return null;
69
+ const resolved = path.resolve(cwd, typed);
70
+ if (fs.existsSync(resolved)) return null;
71
+ const lines = [
72
+ chalk.red(`✗ Schema directory not found: "${typed}"`),
73
+ chalk.gray(` Resolved to: ${resolved}`),
74
+ chalk.gray(` (${PATH_RESOLUTION_RULE}: ${cwd})`)
75
+ ];
76
+ const fromBackend = path.resolve(backendDir, typed);
77
+ if (!path.isAbsolute(typed) && fs.existsSync(fromBackend)) lines.push("", chalk.yellow(` From backend/ it would be ${fromBackend} — the driver runs from there, but the CLI resolves from here.`), chalk.yellow(` Leave the flag out (backend/schema is the default), or write it from here: ${path.relative(cwd, fromBackend) || "."}`));
78
+ lines.push("", ...MISSING_SCHEMA_DIR_CONSEQUENCE[use].map((line) => chalk.gray(` ${line}`)));
79
+ return lines;
80
+ }
81
+ /**
82
+ * The commands that took the removed `--collections` flag, keyed as the
83
+ * command is named in messages (`rebase <command>`). Their `-c` was the
84
+ * flag's short form; elsewhere `-c` never existed, so only these name it as
85
+ * removed.
86
+ */
87
+ var COMMANDS_THAT_TOOK_COLLECTIONS = /* @__PURE__ */ new Set([
88
+ "verify",
89
+ "doctor",
90
+ "console",
91
+ "generate-sdk",
92
+ "db push",
93
+ "db generate",
94
+ "schema generate",
95
+ "schema introspect",
96
+ "schema stale"
97
+ ]);
98
+ /**
99
+ * The sentence a typed `--collections` (or, on a command that had it, `-c`)
100
+ * is refused with, or `null` when the line has neither.
101
+ *
102
+ * The flag named a `config/collections` directory of `defineCollection` files,
103
+ * which nothing reads any more. Refused rather than ignored: reading the
104
+ * default directory instead of the one typed would check, generate or push a
105
+ * different schema than the one asked about. There is no short form of the
106
+ * replacement — `--schema-dir` is spelled out.
107
+ *
108
+ * Only the words before a `--` separator count: after it, the line belongs to
109
+ * whatever the command relays it to.
110
+ */
111
+ function removedCollectionsFlag(args, command) {
112
+ const end = args.indexOf("--");
113
+ const words = end === -1 ? args : args.slice(0, end);
114
+ const shortForm = COMMANDS_THAT_TOOK_COLLECTIONS.has(command);
115
+ const used = words.find((word) => word === "--collections" || word.startsWith("--collections=") || shortForm && word === "-c");
116
+ if (used === void 0) return null;
117
+ return `\`rebase ${command}\`: ${used === "-c" ? "-c" : "--collections"} was removed. Tables are read from backend/schema (or the backend's "tables" in rebase.json) by default, and \`${SCHEMA_DIR_FLAG} <dir>\` names another directory. Nothing was run. A project still on config/collections: ${LEGACY_LAYOUT_REMEDY}.`;
118
+ }
119
+ /**
120
+ * Throw {@link removedCollectionsFlag}'s sentence as a {@link UsageError}, or
121
+ * return. Called before anything starts — no database, no driver.
122
+ */
123
+ function refuseRemovedCollectionsFlag(args, command) {
124
+ const sentence = removedCollectionsFlag(args, command);
125
+ if (sentence !== null) throw new UsageError(sentence);
126
+ }
127
+ /** Print {@link missingSchemaDir}'s refusal and exit 1, or return. */
128
+ function refuseMissingSchemaDir(args, cwd, backendDir, use = "schema") {
129
+ const lines = missingSchemaDir(args, cwd, backendDir, use);
130
+ if (!lines) return;
131
+ console.error("");
132
+ for (const line of lines) console.error(line);
133
+ console.error("");
134
+ process.exit(1);
135
+ }
136
+ //#endregion
137
+ export { refuseRemovedCollectionsFlag as a, refuseMissingSchemaDir as i, SCHEMA_DIR_FLAG_HELP as n, missingSchemaDir as r, PATH_RESOLUTION_RULE as t };
138
+
139
+ //# sourceMappingURL=path-flags-7O5uPBcQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path-flags-7O5uPBcQ.js","names":[],"sources":["../src/utils/path-flags.ts"],"sourcesContent":["/**\n * Where a path typed on a `rebase` command line resolves: one rule, one sentence.\n *\n * The driver CLI runs with `cwd: backend/` — that is where it and its\n * dependencies resolve from — while people type commands from the project root\n * (or anywhere else in it). So every relative path on the line is resolved by\n * the CLI, from the directory the command was run in, before the driver is\n * handed a different one (`absolutizeLocalPathArgs` in `commands/db.ts`).\n * `generate-sdk` and `db backup --out` already worked that way, and so does\n * `--schema-dir`.\n *\n * The sentence below is printed by every help page that takes `--schema-dir`,\n * and by the refusal when the path is not there, so the rule is stated in one\n * set of words wherever a reader meets it.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { LEGACY_LAYOUT_REMEDY } from \"@rebasepro/types\";\nimport { UsageError } from \"./args\";\nimport { SCHEMA_DIR_FLAG } from \"./schema-dir\";\n\n/** The rule, as every help page and error states it. */\nexport const PATH_RESOLUTION_RULE = \"relative paths are resolved from where you run the command\";\n\n/** The `--schema-dir` line of a help page. */\nexport const SCHEMA_DIR_FLAG_HELP = \"Schema directory — the one whose index.ts exports the tables \" +\n `(default: backend/schema, or the backend's \"tables\" in rebase.json); ${PATH_RESOLUTION_RULE}`;\n\n/** The `--schema-dir` value on a line, as typed, or `null` when there is none. */\nfunction typedSchemaDir(args: readonly string[]): string | null {\n for (let i = 0; i < args.length; i++) {\n const token = args[i];\n const eq = token.indexOf(\"=\");\n if (eq > 0 && token.slice(0, eq) === SCHEMA_DIR_FLAG) return token.slice(eq + 1) || null;\n if (token === SCHEMA_DIR_FLAG) {\n const value = args[i + 1];\n return value && !value.startsWith(\"-\") ? value : null;\n }\n }\n return null;\n}\n\n/**\n * What a refusal over a missing `--schema-dir` path spared, by what the command\n * would have done with it. Only a schema writer drops tables; a console or a\n * doctor run over nothing does something else wrong, and says so.\n */\nconst MISSING_SCHEMA_DIR_CONSEQUENCE = {\n schema: [\n \"Nothing was generated and nothing was applied — a schema generated from a\",\n \"directory that is not there is an empty one, and applying it would drop\",\n \"every table it does not describe.\"\n ],\n console: [\n \"Nothing was started — a console over a directory that is not there would\",\n \"load none of this project's tables.\"\n ],\n doctor: [\n \"Nothing was checked — a directory that is not there declares no tables, so\",\n \"every table check would pass over it.\"\n ],\n verify: [\n \"Nothing was verified — a directory that is not there declares no tables, so\",\n \"every step would pass over it and report 0 errors.\"\n ]\n} as const;\n\n/** What a command does with its `--schema-dir` path. */\nexport type SchemaDirUse = keyof typeof MISSING_SCHEMA_DIR_CONSEQUENCE;\n\n/**\n * The refusal for a `--schema-dir` path that does not exist, or `null`.\n *\n * Checked by the CLI, in the reader's terms, before the driver is spawned: the\n * driver's own check runs in `backend/` and can only describe the path it was\n * handed. A generator pointed at a directory that is not there writes an empty\n * schema, and a push of an empty schema drops every table — so nothing runs.\n *\n * A path written from `backend/` (`--schema-dir schema`, run from the root)\n * lands here, and the message says exactly what to change.\n */\nexport function missingSchemaDir(\n args: readonly string[],\n cwd: string,\n backendDir: string,\n use: SchemaDirUse = \"schema\"\n): string[] | null {\n const typed = typedSchemaDir(args);\n if (typed === null) return null;\n const resolved = path.resolve(cwd, typed);\n if (fs.existsSync(resolved)) return null;\n\n const lines = [\n chalk.red(`✗ Schema directory not found: \"${typed}\"`),\n chalk.gray(` Resolved to: ${resolved}`),\n chalk.gray(` (${PATH_RESOLUTION_RULE}: ${cwd})`)\n ];\n const fromBackend = path.resolve(backendDir, typed);\n if (!path.isAbsolute(typed) && fs.existsSync(fromBackend)) {\n lines.push(\n \"\",\n chalk.yellow(` From backend/ it would be ${fromBackend} — the driver runs from there, but the CLI resolves from here.`),\n chalk.yellow(` Leave the flag out (backend/schema is the default), or write it from here: ${path.relative(cwd, fromBackend) || \".\"}`)\n );\n }\n lines.push(\"\", ...MISSING_SCHEMA_DIR_CONSEQUENCE[use].map(line => chalk.gray(` ${line}`)));\n return lines;\n}\n\n/**\n * The commands that took the removed `--collections` flag, keyed as the\n * command is named in messages (`rebase <command>`). Their `-c` was the\n * flag's short form; elsewhere `-c` never existed, so only these name it as\n * removed.\n */\nconst COMMANDS_THAT_TOOK_COLLECTIONS = new Set([\n \"verify\",\n \"doctor\",\n \"console\",\n \"generate-sdk\",\n \"db push\",\n \"db generate\",\n \"schema generate\",\n \"schema introspect\",\n \"schema stale\"\n]);\n\n/**\n * The sentence a typed `--collections` (or, on a command that had it, `-c`)\n * is refused with, or `null` when the line has neither.\n *\n * The flag named a `config/collections` directory of `defineCollection` files,\n * which nothing reads any more. Refused rather than ignored: reading the\n * default directory instead of the one typed would check, generate or push a\n * different schema than the one asked about. There is no short form of the\n * replacement — `--schema-dir` is spelled out.\n *\n * Only the words before a `--` separator count: after it, the line belongs to\n * whatever the command relays it to.\n */\nexport function removedCollectionsFlag(args: readonly string[], command: string): string | null {\n const end = args.indexOf(\"--\");\n const words = end === -1 ? args : args.slice(0, end);\n const shortForm = COMMANDS_THAT_TOOK_COLLECTIONS.has(command);\n const used = words.find(word =>\n word === \"--collections\" || word.startsWith(\"--collections=\") || (shortForm && word === \"-c\"));\n if (used === undefined) return null;\n const flag = used === \"-c\" ? \"-c\" : \"--collections\";\n return `\\`rebase ${command}\\`: ${flag} was removed. Tables are read from backend/schema (or the backend's ` +\n `\"tables\" in rebase.json) by default, and \\`${SCHEMA_DIR_FLAG} <dir>\\` names another directory. ` +\n `Nothing was run. A project still on config/collections: ${LEGACY_LAYOUT_REMEDY}.`;\n}\n\n/**\n * Throw {@link removedCollectionsFlag}'s sentence as a {@link UsageError}, or\n * return. Called before anything starts — no database, no driver.\n */\nexport function refuseRemovedCollectionsFlag(args: readonly string[], command: string): void {\n const sentence = removedCollectionsFlag(args, command);\n if (sentence !== null) throw new UsageError(sentence);\n}\n\n/** Print {@link missingSchemaDir}'s refusal and exit 1, or return. */\nexport function refuseMissingSchemaDir(\n args: readonly string[],\n cwd: string,\n backendDir: string,\n use: SchemaDirUse = \"schema\"\n): void {\n const lines = missingSchemaDir(args, cwd, backendDir, use);\n if (!lines) return;\n console.error(\"\");\n for (const line of lines) console.error(line);\n console.error(\"\");\n process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,uBAAuB;;AAGpC,IAAa,uBAAuB,qIACwC;;AAG5E,SAAS,eAAe,MAAwC;CAC5D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EAClC,MAAM,QAAQ,KAAK;EACnB,MAAM,KAAK,MAAM,QAAQ,GAAG;EAC5B,IAAI,KAAK,KAAK,MAAM,MAAM,GAAG,EAAE,MAAA,gBAAuB,OAAO,MAAM,MAAM,KAAK,CAAC,KAAK;EACpF,IAAI,UAAA,gBAA2B;GAC3B,MAAM,QAAQ,KAAK,IAAI;GACvB,OAAO,SAAS,CAAC,MAAM,WAAW,GAAG,IAAI,QAAQ;EACrD;CACJ;CACA,OAAO;AACX;;;;;;AAOA,IAAM,iCAAiC;CACnC,QAAQ;EACJ;EACA;EACA;CACJ;CACA,SAAS,CACL,4EACA,qCACJ;CACA,QAAQ,CACJ,8EACA,uCACJ;CACA,QAAQ,CACJ,+EACA,oDACJ;AACJ;;;;;;;;;;;;AAgBA,SAAgB,iBACZ,MACA,KACA,YACA,MAAoB,UACL;CACf,MAAM,QAAQ,eAAe,IAAI;CACjC,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,WAAW,KAAK,QAAQ,KAAK,KAAK;CACxC,IAAI,GAAG,WAAW,QAAQ,GAAG,OAAO;CAEpC,MAAM,QAAQ;EACV,MAAM,I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O;CACZ,QAAQ,MAAM,EAAE;CAChB,KAAK,MAAM,QAAQ,OAAO,QAAQ,MAAM,IAAI;CAC5C,QAAQ,MAAM,EAAE;CAChB,QAAQ,KAAK,CAAC;AAClB"}
@@ -1,8 +1,8 @@
1
- import { c as findProjectRoot, d as readEnvFile } from "./project-CasK56vN.js";
1
+ import { c as findProjectRoot, d as readEnvFile } from "./project-CLcF5i8c.js";
2
2
  import { t as Refusal } from "./refusal-ReeeGP8a.js";
3
- import { t as composeDatabaseUrl } from "./dev-preflight-Cxv3TiD1.js";
3
+ import { t as composeDatabaseUrl } from "./dev-preflight-DjvcV6SK.js";
4
4
  import { n as MANAGED_LIMITATIONS } from "./constraints-CtiylsGf.js";
5
- import { n as ensureManagedDatabase } from "./daemon-Cp7oNXth.js";
5
+ import { n as ensureManagedDatabase } from "./daemon-w30PsdwV.js";
6
6
  import fs from "fs";
7
7
  import path from "path";
8
8
  import { resourceEnvSuffix } from "@rebasepro/types";
@@ -535,4 +535,4 @@ function managedNotices(prepared) {
535
535
  //#endregion
536
536
  export { DEV_DATABASE_KIND_ENV, lastDevDatabasePath as a, branchDatabaseName as c, clearActiveBranch as d, devDatabaseKind, databaseNameOf as f, lastDevDatabaseNotice as i, branchPointerPath as l, writeActiveBranch as m, managedNotices, outrankedDockerFlagNotice as n, readLastDevDocker as o, readActiveBranch as p, prepareDatabaseEnv, resolveDevDatabase as r, resolveComposeUrl, resolveProjectDatabase, resolveProjectDatabaseAndBranch, recordLastDevDatabase as s, describeDevDatabase as t, branchUrl as u };
537
537
 
538
- //# sourceMappingURL=prepare-CTw9NEkh.js.map
538
+ //# sourceMappingURL=prepare-Ccxspoj-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prepare-CTw9NEkh.js","names":[],"sources":["../src/dev-db/branch-pointer.ts","../src/dev-db/last-dev-database.ts","../src/dev-db/resolve.ts","../src/dev-db/prepare.ts"],"sourcesContent":["/**\n * Which database branch this checkout is working on.\n *\n * `rebase db branch create` made a full copy of the database in about a second\n * and then stopped one step short of being a feature: there was no `switch`, no\n * `--branch` on `rebase dev`, and nothing wrote the branch anywhere a command\n * would read it. The only way to *use* a branch was to hand-edit\n * `DATABASE_URL`, and the documentation claimed otherwise — \"the CLI updates\n * your local development configuration\" — which it did not; the `.env` was\n * byte-identical afterwards.\n *\n * This is that missing step, and the shape of it is chosen to avoid three\n * things:\n *\n * 1. **It does not touch `.env`.** That file holds secrets, comments and the\n * developer's own ordering, and a command that rewrites it in place will\n * eventually lose something that was not its business. The branch is\n * recorded beside the other per-checkout state in `.rebase/`, which is\n * already gitignored — a branch is a fact about one machine, never about\n * the project.\n *\n * 2. **It stores a name, not a connection string.** The credentials stay in\n * exactly one place; the URL is derived by swapping the database name on\n * the base one at resolution time. A stored URL would be a second copy of\n * the password, and would go stale the moment `.env` changed.\n *\n * 3. **It does not outrank an explicit instruction.** `--database-url` and a\n * `DATABASE_URL` in the shell are more immediate and more specific than a\n * switch made yesterday, so they still win. The pointer sits directly above\n * the project's `.env`: it is a deliberate, persistent choice, and `.env` is\n * the project default it is meant to override. Anything less and `switch`\n * would silently do nothing on every project that sets `DATABASE_URL` —\n * which is every project not using the managed database.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\n\n/** Where the pointer lives, next to the rest of the per-checkout state. */\nexport function branchPointerPath(projectRoot: string): string {\n return path.join(projectRoot, \".rebase\", \"branch.json\");\n}\n\nexport interface ActiveBranch {\n /** The name the developer typed. */\n name: string;\n /** The PostgreSQL database that name refers to. */\n database: string;\n}\n\n/**\n * The prefix `BranchService` puts on every branch database.\n *\n * Duplicated from the driver rather than imported because the CLI must answer\n * \"which database\" without loading a database driver — `rebase dev` reads this\n * before it knows which plugin the project uses. It is covered by a test that\n * fails if the driver's prefix moves.\n */\nexport const BRANCH_DB_PREFIX = \"rb_\";\n\nexport function branchDatabaseName(name: string): string {\n return `${BRANCH_DB_PREFIX}${name}`;\n}\n\n/** Read the active branch, or null when the checkout is on the main database. */\nexport function readActiveBranch(projectRoot: string): ActiveBranch | null {\n try {\n const raw = fs.readFileSync(branchPointerPath(projectRoot), \"utf-8\");\n const parsed = JSON.parse(raw) as Partial<ActiveBranch>;\n if (typeof parsed.name !== \"string\" || typeof parsed.database !== \"string\") return null;\n if (!parsed.name || !parsed.database) return null;\n\n return { name: parsed.name, database: parsed.database };\n } catch {\n // Absent is the common case and is not an error. A corrupt file is\n // treated the same way: the answer is \"no branch\", which is the state\n // the developer can always get back to with `branch switch --off`.\n return null;\n }\n}\n\nexport function writeActiveBranch(projectRoot: string, branch: ActiveBranch): void {\n const file = branchPointerPath(projectRoot);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, `${JSON.stringify(branch, null, 2)}\\n`, \"utf-8\");\n}\n\n/** Return to the main database. Absent is success — this is idempotent. */\nexport function clearActiveBranch(projectRoot: string): void {\n fs.rmSync(branchPointerPath(projectRoot), { force: true });\n}\n\n/**\n * The base connection string with its database swapped for the branch's.\n *\n * Everything else is carried across untouched — credentials, host, port, and\n * the query string, which is load-bearing here: `?sslmode=disable` is what a\n * local Docker Postgres needs, and dropping it turns a switch into a TLS error\n * that says nothing about branches.\n *\n * Returns null for a connection string that cannot be parsed, so the caller can\n * say so plainly rather than emitting a mangled URL that fails later.\n */\nexport function branchUrl(baseUrl: string, database: string): string | null {\n try {\n const url = new URL(baseUrl);\n // `pathname` keeps its leading slash; a URL with no database at all\n // still gets one, which is what connecting to a named branch means.\n url.pathname = `/${database}`;\n\n return url.toString();\n } catch {\n return null;\n }\n}\n\n/** The database name in a connection string, for reporting what you are on. */\nexport function databaseNameOf(connectionString: string): string | null {\n try {\n const name = new URL(connectionString).pathname.replace(/^\\//, \"\");\n\n return name || null;\n } catch {\n return null;\n }\n}\n","/**\n * Which database the last `rebase dev` ran on, when nothing else records it.\n *\n * `rebase dev --docker` is a choice made on one command line, and every other\n * command resolved without it: while dev served the project from its compose\n * database, `rebase db url` printed a managed PGlite URL — and started that\n * daemon to print it — and `db push`, `console` and the rest would have used\n * the same empty database. Nothing said the two disagreed.\n *\n * So `rebase dev` records its choice here, and the other commands follow it\n * (`resolve.ts`, rule 5). Only Docker is recorded. Every other database is\n * already somewhere each command reads — `--database-url` aside, which is a\n * choice for one command line — or is the default, so the record holds\n * `docker` exactly when the last `rebase dev` ran on it, and any other start\n * of `rebase dev` removes it. That is also the way back: `rebase dev` without\n * `--docker`.\n *\n * Beside the branch pointer in `.rebase/`, which is gitignored: which database\n * this checkout last ran on is a fact about one machine, never the project.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport type { DevDatabase } from \"./resolve\";\n\nexport function lastDevDatabasePath(projectRoot: string): string {\n return path.join(projectRoot, \".rebase\", \"dev-database.json\");\n}\n\n/** Whether the last `rebase dev` ran on the compose database. */\nexport function readLastDevDocker(projectRoot: string): boolean {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(lastDevDatabasePath(projectRoot), \"utf8\"));\n return typeof parsed === \"object\" && parsed !== null && \"kind\" in parsed && parsed.kind === \"docker\";\n } catch {\n // Absent is the common case; unreadable has the same answer.\n return false;\n }\n}\n\n/** What this `rebase dev` was asked for, beside what it runs on. */\nexport interface LastDevRun {\n /** `--docker` was on this command line. */\n dockerFlag?: boolean;\n}\n\n/**\n * Record what this `rebase dev` runs on, and say what the last one ran on.\n *\n * A run that asked for Docker and was outranked by a connection string leaves\n * the record as it was. It is not on Docker, so it records nothing; but it is\n * not a run without `--docker` either, which is what forgets the record. The\n * reader was told to comment the `.env` line out to reach Docker, and once\n * they have, the other commands follow Docker as they did before.\n *\n * Best effort: a checkout whose `.rebase/` cannot be written still runs, and\n * the other commands then resolve as they did before this existed.\n */\nexport function recordLastDevDatabase(\n projectRoot: string,\n kind: DevDatabase[\"kind\"],\n run: LastDevRun = {}\n): { previous: \"docker\" | null } {\n const previous = readLastDevDocker(projectRoot) ? \"docker\" : null;\n if (run.dockerFlag && kind !== \"docker\") return { previous };\n const file = lastDevDatabasePath(projectRoot);\n try {\n if (kind === \"docker\") {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, `${JSON.stringify({ kind: \"docker\", recordedAt: new Date().toISOString() }, null, 2)}\\n`);\n } else {\n fs.rmSync(file, { force: true });\n }\n } catch {\n // See above: not worth failing a dev start over.\n }\n\n return { previous };\n}\n\n/**\n * What `rebase dev` says when it leaves the Docker database the last run used.\n *\n * Said rather than left to be noticed: the data a developer was working with\n * is in the container, and the managed database this run is on is a different,\n * possibly empty, one. Not said to a run that asked for Docker: the line that\n * says `--docker` was ignored, and what outranked it, is the one that applies.\n */\nexport function lastDevDatabaseNotice(previous: \"docker\" | null, kind: DevDatabase[\"kind\"], run: LastDevRun = {}): string | null {\n if (previous !== \"docker\" || kind === \"docker\" || run.dockerFlag) return null;\n\n return \"The last `rebase dev` ran on Postgres in Docker; this one does not. \"\n + \"Pass --docker to stay on it — the other commands now follow this run.\";\n}\n","/**\n * Which database a command should talk to, decided in one place.\n *\n * Before this existed every command that needed Postgres read `DATABASE_URL`\n * for itself, which was fine while there was exactly one answer. Introducing a\n * managed database makes the question real: a project may have no\n * `DATABASE_URL` at all and still expect `rebase db push` to work, and a\n * project that *does* set one must never be quietly redirected somewhere else.\n *\n * So the rule is ordered and boring, and the order is the promise:\n *\n * 1. `--database-url <url>` — said on this command line, wins over everything\n * 2. `DATABASE_URL` in the shell environment\n * 3. the database branch this checkout is switched to\n * 4. `DATABASE_URL` in the project's `.env`\n * 5. `--docker`, or the last `rebase dev` having run with it\n * 6. the managed PGlite database\n *\n * An explicit connection string always wins. That is the whole point of the\n * override: someone pointing Rebase at their own Postgres — a colleague's\n * staging box, a Neon branch, a container they manage — must get exactly that,\n * with no cleverness in between. The managed database is what fills the vacuum\n * when nobody has said anything, and it is the only case where the CLI picks.\n *\n * The second half of (5) is `rebase dev --docker` remembered, so that `rebase\n * db url`, `db push` and the rest reach the database a dev server is on rather\n * than start an empty PGlite beside it (`last-dev-database.ts`). It is exactly\n * as strong as the flag it stands in for, and no stronger.\n *\n * The branch at (3) is the one addition that is not an explicit connection\n * string, and it sits where it does deliberately. It has to outrank `.env` or\n * `rebase db branch switch` would silently do nothing on every project that\n * sets `DATABASE_URL` — which is every project not on the managed database.\n * It must not outrank (1) or (2), because a flag on this command line and a\n * variable in this shell are more immediate than a switch made yesterday.\n *\n * {@link resolveDevDatabase} is pure: inputs in, decision out, no filesystem\n * and no process. Reading `.env`, reading the branch pointer and starting a\n * daemon happen elsewhere, so the ordering above can be tested without any of\n * them.\n */\n\n/** Where the answer came from. Carried so diagnostics can name it. */\nexport type DevDatabaseSource =\n /** `--database-url` on the command line. */\n | \"flag\"\n /** `DATABASE_URL` in the shell environment. */\n | \"environment\"\n /** `DATABASE_URL` in the project's `.env`. */\n | \"env-file\"\n /** The branch this checkout is switched to, over the base connection. */\n | \"branch\"\n /** `--docker`. */\n | \"docker\"\n /** `--docker`, on the last `rebase dev` rather than this command line. */\n | \"last-dev\"\n /** Nobody said anything, so the managed database fills in. */\n | \"managed\";\n\nexport type DevDatabase =\n | {\n kind: \"external\";\n /** The connection string, exactly as given. Never rewritten. */\n url: string;\n source: Extract<DevDatabaseSource, \"flag\" | \"environment\" | \"env-file\" | \"branch\">;\n /** The branch name, when this checkout is switched to one. */\n branch?: string;\n }\n | {\n kind: \"docker\";\n source: Extract<DevDatabaseSource, \"docker\" | \"last-dev\">;\n /**\n * The compose `db` service's connection string, derived by the caller.\n *\n * Null when the project has no compose file to derive one from, which\n * is a `--docker` that cannot be honoured rather than a fallback: the\n * caller says so instead of guessing at `localhost:5432`.\n */\n url: string | null;\n }\n | {\n kind: \"managed\";\n source: \"managed\";\n };\n\nexport interface ResolveDevDatabaseInput {\n /** `--database-url <url>`, if given. */\n flagUrl?: string | null;\n /** `--docker`, if given. */\n flagDocker?: boolean;\n /**\n * Whether the last `rebase dev` ran with `--docker`. Followed only while\n * the compose file still names a database, since there is none to go back\n * to otherwise.\n */\n lastDevDocker?: boolean;\n /** The shell environment. Only `DATABASE_URL` is read. */\n env?: Record<string, string | undefined>;\n /** Parsed `.env` from the project root. Only `DATABASE_URL` is read. */\n envFile?: Record<string, string> | null;\n /**\n * The compose `db` service's connection string, when the project has one.\n *\n * Passed in rather than read here so this function stays pure. Only\n * consulted for the Docker case; an explicit `DATABASE_URL` still wins.\n */\n composeUrl?: string | null;\n /**\n * The branch this checkout is switched to, already resolved to a URL.\n *\n * Resolved by the caller rather than here so this stays pure: deriving it\n * needs the base connection string, which needs the `.env` this function is\n * handed rather than reads.\n */\n branch?: { name: string; url: string } | null;\n}\n\n/**\n * A value that is present but empty is treated as absent.\n *\n * `DATABASE_URL=` in a `.env` is what a developer writes when they mean \"not\n * this one\" — honouring it literally would hand an empty connection string to\n * libpq and produce an error about a missing host, which explains nothing.\n */\nfunction present(value: string | undefined | null): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n\n return trimmed.length > 0 ? trimmed : null;\n}\n\nexport function resolveDevDatabase(input: ResolveDevDatabaseInput = {}): DevDatabase {\n const flagUrl = present(input.flagUrl);\n if (flagUrl) return { kind: \"external\", url: flagUrl, source: \"flag\" };\n\n const fromEnvironment = present(input.env?.DATABASE_URL);\n if (fromEnvironment) return { kind: \"external\", url: fromEnvironment, source: \"environment\" };\n\n // Above `.env`, below anything said explicitly — see the ordering note at\n // the top of this file.\n const fromBranch = present(input.branch?.url);\n if (fromBranch && input.branch) {\n return { kind: \"external\", url: fromBranch, source: \"branch\", branch: input.branch.name };\n }\n\n const fromEnvFile = present(input.envFile?.DATABASE_URL);\n if (fromEnvFile) return { kind: \"external\", url: fromEnvFile, source: \"env-file\" };\n\n // Only consulted once every explicit connection string is exhausted: asking\n // for Docker is a choice about *how to get* a database, not which one, so a\n // DATABASE_URL that already names one outranks it.\n if (input.flagDocker) {\n return { kind: \"docker\", source: \"docker\", url: present(input.composeUrl) };\n }\n const composeUrl = present(input.composeUrl);\n if (input.lastDevDocker && composeUrl) {\n return { kind: \"docker\", source: \"last-dev\", url: composeUrl };\n }\n\n return { kind: \"managed\", source: \"managed\" };\n}\n\n/**\n * The line to print when `--docker` was typed and a connection string outranked\n * it, or null when it was not typed or was what this command used.\n *\n * The order stays as documented: asking for Docker says how to get a database,\n * and a `DATABASE_URL` that already names one wins. But a flag on this command\n * line that changes nothing without a word reads as a flag that worked. Only the\n * typed flag is reported — the last `rebase dev --docker` standing in for it is\n * a default, and losing to `.env` is what a default does.\n */\nexport function outrankedDockerFlagNotice(database: DevDatabase, flagDocker: boolean | undefined): string | null {\n if (!flagDocker || database.kind !== \"external\") return null;\n const ignored = \"--docker is ignored:\";\n switch (database.source) {\n case \"flag\":\n return `${ignored} --database-url outranks it.`;\n case \"environment\":\n return `${ignored} DATABASE_URL in the environment outranks it. Unset it to use Postgres in Docker.`;\n case \"branch\":\n return `${ignored} branch \"${database.branch}\" (rebase db branch switch) outranks it. ` +\n \"`rebase db branch switch --off` returns to the database in .env.\";\n case \"env-file\":\n return `${ignored} DATABASE_URL in .env outranks it. Comment that line out to use Postgres in Docker.`;\n }\n}\n\n/** One line for the startup banner, naming both the database and why. */\nexport function describeDevDatabase(database: DevDatabase): string {\n switch (database.kind) {\n case \"external\":\n switch (database.source) {\n case \"flag\":\n return \"your database (--database-url)\";\n case \"environment\":\n return \"your database (DATABASE_URL in the environment)\";\n case \"env-file\":\n return \"your database (DATABASE_URL in .env)\";\n case \"branch\":\n return `branch \"${database.branch}\" (rebase db branch switch)`;\n }\n break;\n case \"docker\":\n return database.source === \"last-dev\"\n ? \"Postgres in Docker, as the last `rebase dev --docker` did\"\n : \"Postgres in Docker\";\n case \"managed\":\n return \"the managed development database (PGlite)\";\n }\n\n // Unreachable while the union is exhaustive; kept so a future variant fails\n // loudly in review rather than printing \"undefined\" to a user.\n throw new Error(`Unhandled dev database: ${JSON.stringify(database)}`);\n}\n","/**\n * The one place a command asks \"which database, and how do I reach it?\".\n *\n * Every command that touches Postgres — `dev`, and the whole `db` namespace\n * through the driver plugin — goes through {@link prepareDatabaseEnv}. It\n * resolves the ordering in `resolve.ts`, starts the managed database if that is\n * what the ordering chose, and hands back the environment additions the child\n * process needs.\n *\n * Two things it deliberately does *not* do:\n *\n * - **It never overwrites an existing `DATABASE_URL`.** When the developer has\n * named a database, the returned environment is empty and the child inherits\n * exactly what it would have inherited before this feature existed. A\n * migration must never be redirected away from the database its author meant.\n *\n * - **It never starts anything for a command that is not going to connect.**\n * `--help` and argument errors are handled by the caller before this is\n * reached, because booting a Postgres to print usage would be absurd.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { composeDatabaseUrl } from \"../utils/dev-preflight\";\nimport { findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { Refusal } from \"../utils/refusal\";\nimport { resourceEnvSuffix } from \"@rebasepro/types\";\nimport { branchUrl, databaseNameOf, readActiveBranch } from \"./branch-pointer\";\nimport { readLastDevDocker } from \"./last-dev-database\";\nimport { MANAGED_LIMITATIONS, MANAGED_POOL_MAX } from \"./constraints\";\nimport { ensureManagedDatabase } from \"./daemon\";\nimport { type DevDatabase, describeDevDatabase, outrankedDockerFlagNotice, resolveDevDatabase } from \"./resolve\";\n\nexport interface PrepareOptions {\n /** `--database-url <url>`. */\n flagUrl?: string | null;\n /** `--docker`. */\n flagDocker?: boolean;\n /**\n * Follow the database the last `rebase dev` ran on (`last-dev-database.ts`).\n * On by default; `rebase dev` itself turns it off, because its own flags are\n * the choice being recorded.\n */\n followLastDev?: boolean;\n /** Suppress the \"starting…\" progress line. */\n quiet?: boolean;\n /** Where human-facing lines go. Defaults to stdout via the caller. */\n onProgress?: (message: string) => void;\n /**\n * Keys of the additional databases the project declares —\n * `database(\"analytics\")` → `analytics`. On the managed path each gets\n * its own PGlite instance and a `DATABASE_URL__<KEY>` in the child's\n * environment, unless the developer set that variable themselves. On an\n * external database nothing is added: whoever chose the database binds\n * the rest of them.\n */\n additionalKeys?: readonly string[];\n}\n\nexport interface PreparedDatabase {\n /** What the resolver chose, for the banner and for tests. */\n database: DevDatabase;\n /**\n * Variables to add to a child process's environment.\n *\n * Empty for an external database: the child already has what it needs, and\n * adding to it could only do harm.\n */\n env: Record<string, string>;\n /** One line naming the database, suitable for a startup banner. */\n description: string;\n /** Absolute path of the managed data directory, when there is one. */\n dataDir?: string;\n /** True when this call started the managed database rather than finding it. */\n startedDaemon?: boolean;\n /** The additional managed databases, by declared key, when any were asked for. */\n additional?: Record<string, string>;\n}\n\n/**\n * The branch this checkout is switched to, over the `DATABASE_URL` in `.env`.\n *\n * Derived rather than stored: the pointer holds a name, and the credentials\n * stay in the one place the developer wrote them. The base here is the\n * project's `.env` — a switch is a statement about *this project's* database,\n * so a `DATABASE_URL` that happens to be in the shell is not the thing being\n * branched, and it outranks the branch anyway.\n *\n * Returns null when there is no branch, and also when `.env` names no base to\n * swap the database name on. That is not the end of it: a project on Postgres\n * in Docker has no `DATABASE_URL` either, and its branch is applied over the\n * compose URL once the order has picked Docker — see\n * {@link resolveProjectDatabaseAndBranch}.\n *\n * Exported for its tests. Asserting this through {@link prepareDatabaseEnv}\n * would start a real PGlite daemon to check a decision made before any daemon\n * is involved.\n */\nexport function resolveActiveBranch(\n projectRoot: string,\n envFile: Record<string, string>\n): { name: string; url: string } | null {\n const active = readActiveBranch(projectRoot);\n if (!active) return null;\n\n const base = envFile.DATABASE_URL?.trim();\n if (!base) return null;\n\n const url = branchUrl(base, active.database);\n\n return url ? { name: active.name, url } : null;\n}\n\n/**\n * The compose `db` service's connection string for this project, or null.\n *\n * Read here rather than in `resolve.ts` so the ordering there stays pure, and\n * exported for the commands that feed the resolver themselves (`rebase status`,\n * `db branch switch`). The preflight that starts the container takes the URL\n * from {@link resolveProjectDatabase}, so it starts one only when the order\n * picks Docker.\n */\nexport function resolveComposeUrl(projectRoot: string, envFile: Record<string, string>): string | null {\n const composePath = path.join(projectRoot, \"docker-compose.yml\");\n if (!fs.existsSync(composePath)) return null;\n try {\n return composeDatabaseUrl(fs.readFileSync(composePath, \"utf8\"), envFile);\n } catch {\n return null;\n }\n}\n\n/**\n * Which database a project is on, decided without starting anything.\n *\n * `resolveDevDatabase` is pure, so the answer is available to help text and to\n * a driver child alike — and neither should pay for a daemon to learn it. The\n * driver cannot work it out for itself: on the managed path `DATABASE_URL` is a\n * perfectly ordinary connection string to a Postgres on loopback, so a child\n * handed only that has no way to know that `rebase db generate` will be refused.\n *\n * Null when there is no project here, which is legal — `rebase db --help` is\n * answered outside one — and when anything at all goes wrong reading the\n * project, because help text must not fail to print over an unreadable `.env`.\n */\nexport function devDatabaseKind(projectRoot?: string | null): DevDatabase[\"kind\"] | null {\n try {\n const root = projectRoot ?? findProjectRoot();\n if (!root) return null;\n\n return resolveProjectDatabase(root).kind;\n } catch {\n return null;\n }\n}\n\n/**\n * The database this command resolves to in this project, decided without\n * starting anything: the ordering in `resolve.ts`, fed from the project's\n * `.env`, its branch pointer, its compose file and the last `rebase dev`.\n *\n * The one place those four are read for a resolution, so a command that asks\n * \"which database\" and a command that then connects to it cannot disagree.\n */\nexport function resolveProjectDatabase(\n projectRoot: string,\n options: Pick<PrepareOptions, \"flagUrl\" | \"flagDocker\" | \"followLastDev\"> = {}\n): DevDatabase {\n return resolveProjectDatabaseAndBranch(projectRoot, options).database;\n}\n\n/** The branch a resolution landed on. */\nexport interface ResolvedBranch {\n /** The name the developer switched to. */\n name: string;\n /** The PostgreSQL database that name refers to. */\n database: string;\n /**\n * The database the branch was taken from, where the branch registry lives:\n * the one the switch swapped the name on.\n */\n parent: string | null;\n}\n\nexport interface ProjectDatabase {\n database: DevDatabase;\n /** Set when the resolved database is this checkout's branch rather than the main one. */\n branch: ResolvedBranch | null;\n /**\n * The branch this checkout is switched to, when the database resolved to\n * is the managed one — which serves exactly one database, so the switch\n * cannot be honoured and the main database is used instead. Null otherwise.\n */\n ignoredBranch: string | null;\n}\n\n/**\n * {@link resolveProjectDatabase}, and which branch the answer is.\n *\n * The switch applies to whichever base the order picks, not to `.env` alone. A\n * project on Postgres in Docker — `rebase dev --docker`, remembered, with the\n * scaffold's `DATABASE_URL` left commented out, which is the setup the docs\n * point to for branching — resolved its branch to nothing, and every command\n * went on using the main database while `switch` said they had moved. So the\n * branch is applied over the compose URL whenever the order picks Docker, by a\n * typed `--docker` or the remembered one, and the answer stays Docker: that is\n * what has the container started and what `rebase dev` records.\n *\n * What outranks a switch still does. `--database-url` and a `DATABASE_URL` in\n * the shell name a database outright, and the managed database cannot hold a\n * branch at all — that last one is reported as `ignoredBranch`, so the caller\n * can say so instead of quietly using main.\n *\n * `env` is the shell environment to judge against, `process.env` by default;\n * `rebase status` passes `{}`, because it asks what *this project* is on.\n */\nexport function resolveProjectDatabaseAndBranch(\n projectRoot: string,\n options: Pick<PrepareOptions, \"flagUrl\" | \"flagDocker\" | \"followLastDev\"> & {\n env?: Record<string, string | undefined>;\n } = {}\n): ProjectDatabase {\n const envFile = readEnvFile(projectRoot);\n const active = readActiveBranch(projectRoot);\n\n const database = resolveDevDatabase({\n flagUrl: options.flagUrl,\n flagDocker: options.flagDocker,\n lastDevDocker: options.followLastDev !== false && readLastDevDocker(projectRoot),\n env: options.env ?? process.env,\n envFile,\n branch: resolveActiveBranch(projectRoot, envFile),\n composeUrl: resolveComposeUrl(projectRoot, envFile)\n });\n\n if (!active) return { database, branch: null, ignoredBranch: null };\n\n if (database.kind === \"external\" && database.source === \"branch\") {\n const parent = databaseNameOf(envFile.DATABASE_URL?.trim() ?? \"\");\n return { database, branch: { ...active, parent }, ignoredBranch: null };\n }\n\n if (database.kind === \"docker\" && database.url) {\n const url = branchUrl(database.url, active.database);\n if (url) {\n return {\n database: { ...database, url },\n branch: { ...active, parent: databaseNameOf(database.url) },\n ignoredBranch: null\n };\n }\n }\n\n return { database, branch: null, ignoredBranch: database.kind === \"managed\" ? active.name : null };\n}\n\n/**\n * The variable a driver child reads {@link devDatabaseKind} from.\n *\n * One name, exported, because three commands build that child's environment and\n * a fourth reads it in another package.\n */\nexport const DEV_DATABASE_KIND_ENV = \"REBASE_DEV_DATABASE_KIND\";\n\n/**\n * The variable that tells a server started on a branch which database it was\n * branched from.\n *\n * The branch registry lives in that database, and a branch database holds\n * only a snapshot of it taken when it was copied — so a server on a branch\n * keeps its branches, and copies new ones from, the database named here. A\n * branch URL does not say which that is; only this checkout's `.env` does.\n */\nexport const BRANCH_PARENT_DATABASE_ENV = \"REBASE_BRANCH_PARENT_DATABASE\";\n\n/**\n * Resolve, start if needed, and describe the database for this command.\n *\n * `projectRoot` is where the managed database's data lives, so two projects on\n * one machine get two databases without either being told about the other.\n */\nexport async function prepareDatabaseEnv(\n projectRoot: string,\n options: PrepareOptions = {}\n): Promise<PreparedDatabase> {\n const envFile = readEnvFile(projectRoot);\n const { database, branch, ignoredBranch } = resolveProjectDatabaseAndBranch(projectRoot, options);\n\n // A branch on Docker is still Docker to the resolver, so its own line does\n // not name the branch; this does, because that is the database in use.\n const description = database.kind === \"docker\" && branch\n ? `branch \"${branch.name}\" (rebase db branch switch) on ${describeDevDatabase(database)}`\n : describeDevDatabase(database);\n // Where a branch lives, for the server: the registry is kept in the\n // database the branch was taken from, and a branch URL does not say which.\n const parentEnv: Record<string, string> = branch?.parent ? { [BRANCH_PARENT_DATABASE_ENV]: branch.parent } : {};\n\n // Said even on a quiet command: `rebase db url --docker` is quiet, and its\n // progress goes to stderr, which is where a flag it did not follow belongs.\n const outranked = outrankedDockerFlagNotice(database, options.flagDocker);\n if (outranked) options.onProgress?.(outranked);\n\n if (ignoredBranch) {\n options.onProgress?.(\n `Branch \"${ignoredBranch}\" is switched to, but this uses the managed database, which has no branches, `\n + \"so the main database is used. `--docker` (or DATABASE_URL in .env) reaches the branch; \"\n + \"`rebase db branch switch --off` clears the switch.\"\n );\n }\n\n if (database.kind === \"external\" && (database.source === \"branch\" || database.source === \"flag\")) {\n // The two external cases that MUST be exported. `environment` and\n // `env-file` are already somewhere the child will look — the shell it\n // inherits, or `.env` via DOTENV_CONFIG_PATH — but a branch URL is\n // derived here and exists nowhere else, and `--database-url` lives only\n // in this process's argv. Without this the pointer resolves correctly\n // and then changes nothing: `rebase db backup` on a switched checkout\n // still reported `Database: leadgen`, and `rebase dev --database-url …`\n // announced the database and then died on `DATABASE_URL: is required`.\n //\n // Safe to set: `dotenv` does not overwrite a variable that is already\n // in the environment, so the child's own `.env` load cannot undo it.\n // On a branch, the database it was branched from too.\n return { database, env: { DATABASE_URL: database.url, ...parentEnv }, description };\n }\n\n if (database.kind === \"docker\") {\n // Docker is the one case where nothing has named a connection string:\n // `.env` leaves DATABASE_URL commented out, so without this the child\n // booted with no database at all and failed on the message a project\n // that configured nothing gets — while the container it had just been\n // asked for was never started either.\n if (!database.url) {\n throw new Refusal(\n \"--docker needs a docker-compose.yml with a db service in this project, \" +\n \"and this one has none that names POSTGRES_USER, POSTGRES_DB and a published port. \" +\n \"Set DATABASE_URL in .env to point at the database you mean instead.\"\n );\n }\n // Said every time it decides, because nothing on this command line\n // asked for Docker: the reader should not have to remember that an\n // earlier `rebase dev` did.\n if (database.source === \"last-dev\") {\n options.onProgress?.(\n `Using ${branch ? `branch \"${branch.name}\" (${branch.database}) of ` : \"\"}Postgres in Docker, `\n + \"as the last `rebase dev --docker` did. `rebase dev` without --docker goes back to the managed database.\"\n );\n }\n return { database, env: { DATABASE_URL: database.url, ...parentEnv }, description };\n }\n\n if (database.kind !== \"managed\") {\n // `environment` or `env-file`: the connection string is already in a\n // place the child reads for itself, so this adds nothing to it.\n return { database, env: {}, description };\n }\n\n // Only the keys nobody bound by hand. A developer who set\n // DATABASE_URL__ANALYTICS to a warehouse of their own has said which\n // database that is, and the managed one fills a vacuum, never a choice.\n const unbound = (options.additionalKeys ?? []).filter((key) => {\n const name = `DATABASE_URL${resourceEnvSuffix(key)}`;\n return !process.env[name] && !envFile[name];\n });\n\n const managed = await ensureManagedDatabase(projectRoot, {\n quiet: options.quiet,\n onProgress: options.onProgress,\n additionalKeys: unbound\n });\n\n const additionalEnv: Record<string, string> = {};\n for (const [key, url] of Object.entries(managed.additional)) {\n additionalEnv[`DATABASE_URL${resourceEnvSuffix(key)}`] = url;\n }\n\n return {\n database,\n description,\n dataDir: managed.dataDir,\n startedDaemon: managed.started,\n additional: managed.additional,\n env: {\n DATABASE_URL: managed.url,\n // PGlite is one session behind a multiplexer: two pooled clients in\n // overlapping transactions deadlock there. This is the ceiling that\n // turns that into ordinary queueing — see `constraints.ts`.\n REBASE_DB_POOL_MAX: String(MANAGED_POOL_MAX),\n ...additionalEnv\n }\n };\n}\n\n/**\n * The lines to print about a managed database, in the order to print them.\n *\n * Returned rather than printed so the caller decides where they go — `dev` has\n * a banner, `db push` has a single line above its own output — and so a test can\n * assert on them without capturing a stream.\n */\nexport function managedNotices(prepared: PreparedDatabase): string[] {\n if (prepared.database.kind !== \"managed\") return [];\n\n const lines = [`Using ${prepared.description}.`];\n if (prepared.dataDir) lines.push(`Data: ${prepared.dataDir}`);\n for (const key of Object.keys(prepared.additional ?? {})) {\n lines.push(`Also serving database \"${key}\" as DATABASE_URL${resourceEnvSuffix(key)}`);\n }\n\n // Stated every time rather than discovered. A developer who does not know\n // requests are serialized here will read a concurrency difference as a bug\n // in their own code.\n for (const limitation of MANAGED_LIMITATIONS) {\n lines.push(`${limitation.summary} ${limitation.remedy}`);\n }\n lines.push(\"To use your own Postgres instead, set DATABASE_URL in .env.\");\n\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,kBAAkB,aAA6B;CAC3D,OAAO,KAAK,KAAK,aAAa,WAAW,aAAa;AAC1D;AAmBA,SAAgB,mBAAmB,MAAsB;CACrD,OAAO,MAAsB;AACjC;;AAGA,SAAgB,iBAAiB,aAA0C;CACvE,IAAI;EACA,MAAM,MAAM,GAAG,aAAa,kBAAkB,WAAW,GAAG,OAAO;EACnE,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,IAAI,OAAO,OAAO,SAAS,YAAY,OAAO,OAAO,aAAa,UAAU,OAAO;EACnF,IAAI,CAAC,OAAO,QAAQ,CAAC,OAAO,UAAU,OAAO;EAE7C,OAA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AAK,CAAC;EAAG;CAAY;CAM5C,MAAM,WAAW,QAAQ,kBAAkB,CAAC,EAAA,CAAG,QAAQ,QAAQ;EAC3D,MAAM,OAAO,eAAe,kBAAkB,GAAG;EACjD,OAAO,CAAC,QAAQ,IAAI,SAAS,CAAC,QAAQ;CAC1C,CAAC;CAED,MAAM,UAAU,MAAM,sBAAsB,aAAa;EACrD,OAAO,QAAQ;EACf,YAAY,QAAQ;EACpB,gBAAgB;CACpB,CAAC;CAED,MAAM,gBAAwC,CAAC;CAC/C,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,QAAQ,UAAU,GACtD,cAAc,eAAe,kBAAkB,GAAG,OAAO;CAG7D,OAAO;EACH;EACA;EACA,SAAS,QAAQ;EACjB,eAAe,QAAQ;EACvB,YAAY,QAAQ;EACpB,KAAK;GACD,cAAc,QAAQ;GAItB,oBAAoB,OAAA,CAAuB;GAC3C,GAAG;EACP;CACJ;AACJ;;;;;;;;AASA,SAAgB,eAAe,UAAsC;CACjE,IAAI,SAAS,SAAS,SAAS,WAAW,OAAO,CAAC;CAElD,MAAM,QAAQ,CAAC,SAAS,SAAS,YAAY,EAAE;CAC/C,IAAI,SAAS,SAAS,MAAM,KAAK,SAAS,SAAS,SAAS;CAC5D,KAAK,MAAM,OAAO,OAAO,KAAK,SAAS,cAAc,CAAC,CAAC,GACnD,MAAM,KAAK,0BAA0B,IAAI,mBAAmB,kBAAkB,GAAG,GAAG;CAMxF,KAAK,MAAM,cAAc,qBACrB,MAAM,KAAK,GAAG,WAAW,QAAQ,GAAG,WAAW,QAAQ;CAE3D,MAAM,KAAK,6DAA6D;CAExE,OAAO;AACX"}
1
+ {"version":3,"file":"prepare-Ccxspoj-.js","names":[],"sources":["../src/dev-db/branch-pointer.ts","../src/dev-db/last-dev-database.ts","../src/dev-db/resolve.ts","../src/dev-db/prepare.ts"],"sourcesContent":["/**\n * Which database branch this checkout is working on.\n *\n * `rebase db branch create` made a full copy of the database in about a second\n * and then stopped one step short of being a feature: there was no `switch`, no\n * `--branch` on `rebase dev`, and nothing wrote the branch anywhere a command\n * would read it. The only way to *use* a branch was to hand-edit\n * `DATABASE_URL`, and the documentation claimed otherwise — \"the CLI updates\n * your local development configuration\" — which it did not; the `.env` was\n * byte-identical afterwards.\n *\n * This is that missing step, and the shape of it is chosen to avoid three\n * things:\n *\n * 1. **It does not touch `.env`.** That file holds secrets, comments and the\n * developer's own ordering, and a command that rewrites it in place will\n * eventually lose something that was not its business. The branch is\n * recorded beside the other per-checkout state in `.rebase/`, which is\n * already gitignored — a branch is a fact about one machine, never about\n * the project.\n *\n * 2. **It stores a name, not a connection string.** The credentials stay in\n * exactly one place; the URL is derived by swapping the database name on\n * the base one at resolution time. A stored URL would be a second copy of\n * the password, and would go stale the moment `.env` changed.\n *\n * 3. **It does not outrank an explicit instruction.** `--database-url` and a\n * `DATABASE_URL` in the shell are more immediate and more specific than a\n * switch made yesterday, so they still win. The pointer sits directly above\n * the project's `.env`: it is a deliberate, persistent choice, and `.env` is\n * the project default it is meant to override. Anything less and `switch`\n * would silently do nothing on every project that sets `DATABASE_URL` —\n * which is every project not using the managed database.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\n\n/** Where the pointer lives, next to the rest of the per-checkout state. */\nexport function branchPointerPath(projectRoot: string): string {\n return path.join(projectRoot, \".rebase\", \"branch.json\");\n}\n\nexport interface ActiveBranch {\n /** The name the developer typed. */\n name: string;\n /** The PostgreSQL database that name refers to. */\n database: string;\n}\n\n/**\n * The prefix `BranchService` puts on every branch database.\n *\n * Duplicated from the driver rather than imported because the CLI must answer\n * \"which database\" without loading a database driver — `rebase dev` reads this\n * before it knows which plugin the project uses. It is covered by a test that\n * fails if the driver's prefix moves.\n */\nexport const BRANCH_DB_PREFIX = \"rb_\";\n\nexport function branchDatabaseName(name: string): string {\n return `${BRANCH_DB_PREFIX}${name}`;\n}\n\n/** Read the active branch, or null when the checkout is on the main database. */\nexport function readActiveBranch(projectRoot: string): ActiveBranch | null {\n try {\n const raw = fs.readFileSync(branchPointerPath(projectRoot), \"utf-8\");\n const parsed = JSON.parse(raw) as Partial<ActiveBranch>;\n if (typeof parsed.name !== \"string\" || typeof parsed.database !== \"string\") return null;\n if (!parsed.name || !parsed.database) return null;\n\n return { name: parsed.name, database: parsed.database };\n } catch {\n // Absent is the common case and is not an error. A corrupt file is\n // treated the same way: the answer is \"no branch\", which is the state\n // the developer can always get back to with `branch switch --off`.\n return null;\n }\n}\n\nexport function writeActiveBranch(projectRoot: string, branch: ActiveBranch): void {\n const file = branchPointerPath(projectRoot);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, `${JSON.stringify(branch, null, 2)}\\n`, \"utf-8\");\n}\n\n/** Return to the main database. Absent is success — this is idempotent. */\nexport function clearActiveBranch(projectRoot: string): void {\n fs.rmSync(branchPointerPath(projectRoot), { force: true });\n}\n\n/**\n * The base connection string with its database swapped for the branch's.\n *\n * Everything else is carried across untouched — credentials, host, port, and\n * the query string, which is load-bearing here: `?sslmode=disable` is what a\n * local Docker Postgres needs, and dropping it turns a switch into a TLS error\n * that says nothing about branches.\n *\n * Returns null for a connection string that cannot be parsed, so the caller can\n * say so plainly rather than emitting a mangled URL that fails later.\n */\nexport function branchUrl(baseUrl: string, database: string): string | null {\n try {\n const url = new URL(baseUrl);\n // `pathname` keeps its leading slash; a URL with no database at all\n // still gets one, which is what connecting to a named branch means.\n url.pathname = `/${database}`;\n\n return url.toString();\n } catch {\n return null;\n }\n}\n\n/** The database name in a connection string, for reporting what you are on. */\nexport function databaseNameOf(connectionString: string): string | null {\n try {\n const name = new URL(connectionString).pathname.replace(/^\\//, \"\");\n\n return name || null;\n } catch {\n return null;\n }\n}\n","/**\n * Which database the last `rebase dev` ran on, when nothing else records it.\n *\n * `rebase dev --docker` is a choice made on one command line, and every other\n * command resolved without it: while dev served the project from its compose\n * database, `rebase db url` printed a managed PGlite URL — and started that\n * daemon to print it — and `db push`, `console` and the rest would have used\n * the same empty database. Nothing said the two disagreed.\n *\n * So `rebase dev` records its choice here, and the other commands follow it\n * (`resolve.ts`, rule 5). Only Docker is recorded. Every other database is\n * already somewhere each command reads — `--database-url` aside, which is a\n * choice for one command line — or is the default, so the record holds\n * `docker` exactly when the last `rebase dev` ran on it, and any other start\n * of `rebase dev` removes it. That is also the way back: `rebase dev` without\n * `--docker`.\n *\n * Beside the branch pointer in `.rebase/`, which is gitignored: which database\n * this checkout last ran on is a fact about one machine, never the project.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport type { DevDatabase } from \"./resolve\";\n\nexport function lastDevDatabasePath(projectRoot: string): string {\n return path.join(projectRoot, \".rebase\", \"dev-database.json\");\n}\n\n/** Whether the last `rebase dev` ran on the compose database. */\nexport function readLastDevDocker(projectRoot: string): boolean {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(lastDevDatabasePath(projectRoot), \"utf8\"));\n return typeof parsed === \"object\" && parsed !== null && \"kind\" in parsed && parsed.kind === \"docker\";\n } catch {\n // Absent is the common case; unreadable has the same answer.\n return false;\n }\n}\n\n/** What this `rebase dev` was asked for, beside what it runs on. */\nexport interface LastDevRun {\n /** `--docker` was on this command line. */\n dockerFlag?: boolean;\n}\n\n/**\n * Record what this `rebase dev` runs on, and say what the last one ran on.\n *\n * A run that asked for Docker and was outranked by a connection string leaves\n * the record as it was. It is not on Docker, so it records nothing; but it is\n * not a run without `--docker` either, which is what forgets the record. The\n * reader was told to comment the `.env` line out to reach Docker, and once\n * they have, the other commands follow Docker as they did before.\n *\n * Best effort: a checkout whose `.rebase/` cannot be written still runs, and\n * the other commands then resolve as they did before this existed.\n */\nexport function recordLastDevDatabase(\n projectRoot: string,\n kind: DevDatabase[\"kind\"],\n run: LastDevRun = {}\n): { previous: \"docker\" | null } {\n const previous = readLastDevDocker(projectRoot) ? \"docker\" : null;\n if (run.dockerFlag && kind !== \"docker\") return { previous };\n const file = lastDevDatabasePath(projectRoot);\n try {\n if (kind === \"docker\") {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, `${JSON.stringify({ kind: \"docker\", recordedAt: new Date().toISOString() }, null, 2)}\\n`);\n } else {\n fs.rmSync(file, { force: true });\n }\n } catch {\n // See above: not worth failing a dev start over.\n }\n\n return { previous };\n}\n\n/**\n * What `rebase dev` says when it leaves the Docker database the last run used.\n *\n * Said rather than left to be noticed: the data a developer was working with\n * is in the container, and the managed database this run is on is a different,\n * possibly empty, one. Not said to a run that asked for Docker: the line that\n * says `--docker` was ignored, and what outranked it, is the one that applies.\n */\nexport function lastDevDatabaseNotice(previous: \"docker\" | null, kind: DevDatabase[\"kind\"], run: LastDevRun = {}): string | null {\n if (previous !== \"docker\" || kind === \"docker\" || run.dockerFlag) return null;\n\n return \"The last `rebase dev` ran on Postgres in Docker; this one does not. \"\n + \"Pass --docker to stay on it — the other commands now follow this run.\";\n}\n","/**\n * Which database a command should talk to, decided in one place.\n *\n * Before this existed every command that needed Postgres read `DATABASE_URL`\n * for itself, which was fine while there was exactly one answer. Introducing a\n * managed database makes the question real: a project may have no\n * `DATABASE_URL` at all and still expect `rebase db push` to work, and a\n * project that *does* set one must never be quietly redirected somewhere else.\n *\n * So the rule is ordered and boring, and the order is the promise:\n *\n * 1. `--database-url <url>` — said on this command line, wins over everything\n * 2. `DATABASE_URL` in the shell environment\n * 3. the database branch this checkout is switched to\n * 4. `DATABASE_URL` in the project's `.env`\n * 5. `--docker`, or the last `rebase dev` having run with it\n * 6. the managed PGlite database\n *\n * An explicit connection string always wins. That is the whole point of the\n * override: someone pointing Rebase at their own Postgres — a colleague's\n * staging box, a Neon branch, a container they manage — must get exactly that,\n * with no cleverness in between. The managed database is what fills the vacuum\n * when nobody has said anything, and it is the only case where the CLI picks.\n *\n * The second half of (5) is `rebase dev --docker` remembered, so that `rebase\n * db url`, `db push` and the rest reach the database a dev server is on rather\n * than start an empty PGlite beside it (`last-dev-database.ts`). It is exactly\n * as strong as the flag it stands in for, and no stronger.\n *\n * The branch at (3) is the one addition that is not an explicit connection\n * string, and it sits where it does deliberately. It has to outrank `.env` or\n * `rebase db branch switch` would silently do nothing on every project that\n * sets `DATABASE_URL` — which is every project not on the managed database.\n * It must not outrank (1) or (2), because a flag on this command line and a\n * variable in this shell are more immediate than a switch made yesterday.\n *\n * {@link resolveDevDatabase} is pure: inputs in, decision out, no filesystem\n * and no process. Reading `.env`, reading the branch pointer and starting a\n * daemon happen elsewhere, so the ordering above can be tested without any of\n * them.\n */\n\n/** Where the answer came from. Carried so diagnostics can name it. */\nexport type DevDatabaseSource =\n /** `--database-url` on the command line. */\n | \"flag\"\n /** `DATABASE_URL` in the shell environment. */\n | \"environment\"\n /** `DATABASE_URL` in the project's `.env`. */\n | \"env-file\"\n /** The branch this checkout is switched to, over the base connection. */\n | \"branch\"\n /** `--docker`. */\n | \"docker\"\n /** `--docker`, on the last `rebase dev` rather than this command line. */\n | \"last-dev\"\n /** Nobody said anything, so the managed database fills in. */\n | \"managed\";\n\nexport type DevDatabase =\n | {\n kind: \"external\";\n /** The connection string, exactly as given. Never rewritten. */\n url: string;\n source: Extract<DevDatabaseSource, \"flag\" | \"environment\" | \"env-file\" | \"branch\">;\n /** The branch name, when this checkout is switched to one. */\n branch?: string;\n }\n | {\n kind: \"docker\";\n source: Extract<DevDatabaseSource, \"docker\" | \"last-dev\">;\n /**\n * The compose `db` service's connection string, derived by the caller.\n *\n * Null when the project has no compose file to derive one from, which\n * is a `--docker` that cannot be honoured rather than a fallback: the\n * caller says so instead of guessing at `localhost:5432`.\n */\n url: string | null;\n }\n | {\n kind: \"managed\";\n source: \"managed\";\n };\n\nexport interface ResolveDevDatabaseInput {\n /** `--database-url <url>`, if given. */\n flagUrl?: string | null;\n /** `--docker`, if given. */\n flagDocker?: boolean;\n /**\n * Whether the last `rebase dev` ran with `--docker`. Followed only while\n * the compose file still names a database, since there is none to go back\n * to otherwise.\n */\n lastDevDocker?: boolean;\n /** The shell environment. Only `DATABASE_URL` is read. */\n env?: Record<string, string | undefined>;\n /** Parsed `.env` from the project root. Only `DATABASE_URL` is read. */\n envFile?: Record<string, string> | null;\n /**\n * The compose `db` service's connection string, when the project has one.\n *\n * Passed in rather than read here so this function stays pure. Only\n * consulted for the Docker case; an explicit `DATABASE_URL` still wins.\n */\n composeUrl?: string | null;\n /**\n * The branch this checkout is switched to, already resolved to a URL.\n *\n * Resolved by the caller rather than here so this stays pure: deriving it\n * needs the base connection string, which needs the `.env` this function is\n * handed rather than reads.\n */\n branch?: { name: string; url: string } | null;\n}\n\n/**\n * A value that is present but empty is treated as absent.\n *\n * `DATABASE_URL=` in a `.env` is what a developer writes when they mean \"not\n * this one\" — honouring it literally would hand an empty connection string to\n * libpq and produce an error about a missing host, which explains nothing.\n */\nfunction present(value: string | undefined | null): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n\n return trimmed.length > 0 ? trimmed : null;\n}\n\nexport function resolveDevDatabase(input: ResolveDevDatabaseInput = {}): DevDatabase {\n const flagUrl = present(input.flagUrl);\n if (flagUrl) return { kind: \"external\", url: flagUrl, source: \"flag\" };\n\n const fromEnvironment = present(input.env?.DATABASE_URL);\n if (fromEnvironment) return { kind: \"external\", url: fromEnvironment, source: \"environment\" };\n\n // Above `.env`, below anything said explicitly — see the ordering note at\n // the top of this file.\n const fromBranch = present(input.branch?.url);\n if (fromBranch && input.branch) {\n return { kind: \"external\", url: fromBranch, source: \"branch\", branch: input.branch.name };\n }\n\n const fromEnvFile = present(input.envFile?.DATABASE_URL);\n if (fromEnvFile) return { kind: \"external\", url: fromEnvFile, source: \"env-file\" };\n\n // Only consulted once every explicit connection string is exhausted: asking\n // for Docker is a choice about *how to get* a database, not which one, so a\n // DATABASE_URL that already names one outranks it.\n if (input.flagDocker) {\n return { kind: \"docker\", source: \"docker\", url: present(input.composeUrl) };\n }\n const composeUrl = present(input.composeUrl);\n if (input.lastDevDocker && composeUrl) {\n return { kind: \"docker\", source: \"last-dev\", url: composeUrl };\n }\n\n return { kind: \"managed\", source: \"managed\" };\n}\n\n/**\n * The line to print when `--docker` was typed and a connection string outranked\n * it, or null when it was not typed or was what this command used.\n *\n * The order stays as documented: asking for Docker says how to get a database,\n * and a `DATABASE_URL` that already names one wins. But a flag on this command\n * line that changes nothing without a word reads as a flag that worked. Only the\n * typed flag is reported — the last `rebase dev --docker` standing in for it is\n * a default, and losing to `.env` is what a default does.\n */\nexport function outrankedDockerFlagNotice(database: DevDatabase, flagDocker: boolean | undefined): string | null {\n if (!flagDocker || database.kind !== \"external\") return null;\n const ignored = \"--docker is ignored:\";\n switch (database.source) {\n case \"flag\":\n return `${ignored} --database-url outranks it.`;\n case \"environment\":\n return `${ignored} DATABASE_URL in the environment outranks it. Unset it to use Postgres in Docker.`;\n case \"branch\":\n return `${ignored} branch \"${database.branch}\" (rebase db branch switch) outranks it. ` +\n \"`rebase db branch switch --off` returns to the database in .env.\";\n case \"env-file\":\n return `${ignored} DATABASE_URL in .env outranks it. Comment that line out to use Postgres in Docker.`;\n }\n}\n\n/** One line for the startup banner, naming both the database and why. */\nexport function describeDevDatabase(database: DevDatabase): string {\n switch (database.kind) {\n case \"external\":\n switch (database.source) {\n case \"flag\":\n return \"your database (--database-url)\";\n case \"environment\":\n return \"your database (DATABASE_URL in the environment)\";\n case \"env-file\":\n return \"your database (DATABASE_URL in .env)\";\n case \"branch\":\n return `branch \"${database.branch}\" (rebase db branch switch)`;\n }\n break;\n case \"docker\":\n return database.source === \"last-dev\"\n ? \"Postgres in Docker, as the last `rebase dev --docker` did\"\n : \"Postgres in Docker\";\n case \"managed\":\n return \"the managed development database (PGlite)\";\n }\n\n // Unreachable while the union is exhaustive; kept so a future variant fails\n // loudly in review rather than printing \"undefined\" to a user.\n throw new Error(`Unhandled dev database: ${JSON.stringify(database)}`);\n}\n","/**\n * The one place a command asks \"which database, and how do I reach it?\".\n *\n * Every command that touches Postgres — `dev`, and the whole `db` namespace\n * through the driver plugin — goes through {@link prepareDatabaseEnv}. It\n * resolves the ordering in `resolve.ts`, starts the managed database if that is\n * what the ordering chose, and hands back the environment additions the child\n * process needs.\n *\n * Two things it deliberately does *not* do:\n *\n * - **It never overwrites an existing `DATABASE_URL`.** When the developer has\n * named a database, the returned environment is empty and the child inherits\n * exactly what it would have inherited before this feature existed. A\n * migration must never be redirected away from the database its author meant.\n *\n * - **It never starts anything for a command that is not going to connect.**\n * `--help` and argument errors are handled by the caller before this is\n * reached, because booting a Postgres to print usage would be absurd.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { composeDatabaseUrl } from \"../utils/dev-preflight\";\nimport { findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { Refusal } from \"../utils/refusal\";\nimport { resourceEnvSuffix } from \"@rebasepro/types\";\nimport { branchUrl, databaseNameOf, readActiveBranch } from \"./branch-pointer\";\nimport { readLastDevDocker } from \"./last-dev-database\";\nimport { MANAGED_LIMITATIONS, MANAGED_POOL_MAX } from \"./constraints\";\nimport { ensureManagedDatabase } from \"./daemon\";\nimport { type DevDatabase, describeDevDatabase, outrankedDockerFlagNotice, resolveDevDatabase } from \"./resolve\";\n\nexport interface PrepareOptions {\n /** `--database-url <url>`. */\n flagUrl?: string | null;\n /** `--docker`. */\n flagDocker?: boolean;\n /**\n * Follow the database the last `rebase dev` ran on (`last-dev-database.ts`).\n * On by default; `rebase dev` itself turns it off, because its own flags are\n * the choice being recorded.\n */\n followLastDev?: boolean;\n /** Suppress the \"starting…\" progress line. */\n quiet?: boolean;\n /** Where human-facing lines go. Defaults to stdout via the caller. */\n onProgress?: (message: string) => void;\n /**\n * Keys of the additional databases the project declares —\n * `database(\"analytics\")` → `analytics`. On the managed path each gets\n * its own PGlite instance and a `DATABASE_URL__<KEY>` in the child's\n * environment, unless the developer set that variable themselves. On an\n * external database nothing is added: whoever chose the database binds\n * the rest of them.\n */\n additionalKeys?: readonly string[];\n}\n\nexport interface PreparedDatabase {\n /** What the resolver chose, for the banner and for tests. */\n database: DevDatabase;\n /**\n * Variables to add to a child process's environment.\n *\n * Empty for an external database: the child already has what it needs, and\n * adding to it could only do harm.\n */\n env: Record<string, string>;\n /** One line naming the database, suitable for a startup banner. */\n description: string;\n /** Absolute path of the managed data directory, when there is one. */\n dataDir?: string;\n /** True when this call started the managed database rather than finding it. */\n startedDaemon?: boolean;\n /** The additional managed databases, by declared key, when any were asked for. */\n additional?: Record<string, string>;\n}\n\n/**\n * The branch this checkout is switched to, over the `DATABASE_URL` in `.env`.\n *\n * Derived rather than stored: the pointer holds a name, and the credentials\n * stay in the one place the developer wrote them. The base here is the\n * project's `.env` — a switch is a statement about *this project's* database,\n * so a `DATABASE_URL` that happens to be in the shell is not the thing being\n * branched, and it outranks the branch anyway.\n *\n * Returns null when there is no branch, and also when `.env` names no base to\n * swap the database name on. That is not the end of it: a project on Postgres\n * in Docker has no `DATABASE_URL` either, and its branch is applied over the\n * compose URL once the order has picked Docker — see\n * {@link resolveProjectDatabaseAndBranch}.\n *\n * Exported for its tests. Asserting this through {@link prepareDatabaseEnv}\n * would start a real PGlite daemon to check a decision made before any daemon\n * is involved.\n */\nexport function resolveActiveBranch(\n projectRoot: string,\n envFile: Record<string, string>\n): { name: string; url: string } | null {\n const active = readActiveBranch(projectRoot);\n if (!active) return null;\n\n const base = envFile.DATABASE_URL?.trim();\n if (!base) return null;\n\n const url = branchUrl(base, active.database);\n\n return url ? { name: active.name, url } : null;\n}\n\n/**\n * The compose `db` service's connection string for this project, or null.\n *\n * Read here rather than in `resolve.ts` so the ordering there stays pure, and\n * exported for the commands that feed the resolver themselves (`rebase status`,\n * `db branch switch`). The preflight that starts the container takes the URL\n * from {@link resolveProjectDatabase}, so it starts one only when the order\n * picks Docker.\n */\nexport function resolveComposeUrl(projectRoot: string, envFile: Record<string, string>): string | null {\n const composePath = path.join(projectRoot, \"docker-compose.yml\");\n if (!fs.existsSync(composePath)) return null;\n try {\n return composeDatabaseUrl(fs.readFileSync(composePath, \"utf8\"), envFile);\n } catch {\n return null;\n }\n}\n\n/**\n * Which database a project is on, decided without starting anything.\n *\n * `resolveDevDatabase` is pure, so the answer is available to help text and to\n * a driver child alike — and neither should pay for a daemon to learn it. The\n * driver cannot work it out for itself: on the managed path `DATABASE_URL` is a\n * perfectly ordinary connection string to a Postgres on loopback, so a child\n * handed only that has no way to know that `rebase db generate` will be refused.\n *\n * Null when there is no project here, which is legal — `rebase db --help` is\n * answered outside one — and when anything at all goes wrong reading the\n * project, because help text must not fail to print over an unreadable `.env`.\n */\nexport function devDatabaseKind(projectRoot?: string | null): DevDatabase[\"kind\"] | null {\n try {\n const root = projectRoot ?? findProjectRoot();\n if (!root) return null;\n\n return resolveProjectDatabase(root).kind;\n } catch {\n return null;\n }\n}\n\n/**\n * The database this command resolves to in this project, decided without\n * starting anything: the ordering in `resolve.ts`, fed from the project's\n * `.env`, its branch pointer, its compose file and the last `rebase dev`.\n *\n * The one place those four are read for a resolution, so a command that asks\n * \"which database\" and a command that then connects to it cannot disagree.\n */\nexport function resolveProjectDatabase(\n projectRoot: string,\n options: Pick<PrepareOptions, \"flagUrl\" | \"flagDocker\" | \"followLastDev\"> = {}\n): DevDatabase {\n return resolveProjectDatabaseAndBranch(projectRoot, options).database;\n}\n\n/** The branch a resolution landed on. */\nexport interface ResolvedBranch {\n /** The name the developer switched to. */\n name: string;\n /** The PostgreSQL database that name refers to. */\n database: string;\n /**\n * The database the branch was taken from, where the branch registry lives:\n * the one the switch swapped the name on.\n */\n parent: string | null;\n}\n\nexport interface ProjectDatabase {\n database: DevDatabase;\n /** Set when the resolved database is this checkout's branch rather than the main one. */\n branch: ResolvedBranch | null;\n /**\n * The branch this checkout is switched to, when the database resolved to\n * is the managed one — which serves exactly one database, so the switch\n * cannot be honoured and the main database is used instead. Null otherwise.\n */\n ignoredBranch: string | null;\n}\n\n/**\n * {@link resolveProjectDatabase}, and which branch the answer is.\n *\n * The switch applies to whichever base the order picks, not to `.env` alone. A\n * project on Postgres in Docker — `rebase dev --docker`, remembered, with the\n * scaffold's `DATABASE_URL` left commented out, which is the setup the docs\n * point to for branching — resolved its branch to nothing, and every command\n * went on using the main database while `switch` said they had moved. So the\n * branch is applied over the compose URL whenever the order picks Docker, by a\n * typed `--docker` or the remembered one, and the answer stays Docker: that is\n * what has the container started and what `rebase dev` records.\n *\n * What outranks a switch still does. `--database-url` and a `DATABASE_URL` in\n * the shell name a database outright, and the managed database cannot hold a\n * branch at all — that last one is reported as `ignoredBranch`, so the caller\n * can say so instead of quietly using main.\n *\n * `env` is the shell environment to judge against, `process.env` by default;\n * `rebase status` passes `{}`, because it asks what *this project* is on.\n */\nexport function resolveProjectDatabaseAndBranch(\n projectRoot: string,\n options: Pick<PrepareOptions, \"flagUrl\" | \"flagDocker\" | \"followLastDev\"> & {\n env?: Record<string, string | undefined>;\n } = {}\n): ProjectDatabase {\n const envFile = readEnvFile(projectRoot);\n const active = readActiveBranch(projectRoot);\n\n const database = resolveDevDatabase({\n flagUrl: options.flagUrl,\n flagDocker: options.flagDocker,\n lastDevDocker: options.followLastDev !== false && readLastDevDocker(projectRoot),\n env: options.env ?? process.env,\n envFile,\n branch: resolveActiveBranch(projectRoot, envFile),\n composeUrl: resolveComposeUrl(projectRoot, envFile)\n });\n\n if (!active) return { database, branch: null, ignoredBranch: null };\n\n if (database.kind === \"external\" && database.source === \"branch\") {\n const parent = databaseNameOf(envFile.DATABASE_URL?.trim() ?? \"\");\n return { database, branch: { ...active, parent }, ignoredBranch: null };\n }\n\n if (database.kind === \"docker\" && database.url) {\n const url = branchUrl(database.url, active.database);\n if (url) {\n return {\n database: { ...database, url },\n branch: { ...active, parent: databaseNameOf(database.url) },\n ignoredBranch: null\n };\n }\n }\n\n return { database, branch: null, ignoredBranch: database.kind === \"managed\" ? active.name : null };\n}\n\n/**\n * The variable a driver child reads {@link devDatabaseKind} from.\n *\n * One name, exported, because three commands build that child's environment and\n * a fourth reads it in another package.\n */\nexport const DEV_DATABASE_KIND_ENV = \"REBASE_DEV_DATABASE_KIND\";\n\n/**\n * The variable that tells a server started on a branch which database it was\n * branched from.\n *\n * The branch registry lives in that database, and a branch database holds\n * only a snapshot of it taken when it was copied — so a server on a branch\n * keeps its branches, and copies new ones from, the database named here. A\n * branch URL does not say which that is; only this checkout's `.env` does.\n */\nexport const BRANCH_PARENT_DATABASE_ENV = \"REBASE_BRANCH_PARENT_DATABASE\";\n\n/**\n * Resolve, start if needed, and describe the database for this command.\n *\n * `projectRoot` is where the managed database's data lives, so two projects on\n * one machine get two databases without either being told about the other.\n */\nexport async function prepareDatabaseEnv(\n projectRoot: string,\n options: PrepareOptions = {}\n): Promise<PreparedDatabase> {\n const envFile = readEnvFile(projectRoot);\n const { database, branch, ignoredBranch } = resolveProjectDatabaseAndBranch(projectRoot, options);\n\n // A branch on Docker is still Docker to the resolver, so its own line does\n // not name the branch; this does, because that is the database in use.\n const description = database.kind === \"docker\" && branch\n ? `branch \"${branch.name}\" (rebase db branch switch) on ${describeDevDatabase(database)}`\n : describeDevDatabase(database);\n // Where a branch lives, for the server: the registry is kept in the\n // database the branch was taken from, and a branch URL does not say which.\n const parentEnv: Record<string, string> = branch?.parent ? { [BRANCH_PARENT_DATABASE_ENV]: branch.parent } : {};\n\n // Said even on a quiet command: `rebase db url --docker` is quiet, and its\n // progress goes to stderr, which is where a flag it did not follow belongs.\n const outranked = outrankedDockerFlagNotice(database, options.flagDocker);\n if (outranked) options.onProgress?.(outranked);\n\n if (ignoredBranch) {\n options.onProgress?.(\n `Branch \"${ignoredBranch}\" is switched to, but this uses the managed database, which has no branches, `\n + \"so the main database is used. `--docker` (or DATABASE_URL in .env) reaches the branch; \"\n + \"`rebase db branch switch --off` clears the switch.\"\n );\n }\n\n if (database.kind === \"external\" && (database.source === \"branch\" || database.source === \"flag\")) {\n // The two external cases that MUST be exported. `environment` and\n // `env-file` are already somewhere the child will look — the shell it\n // inherits, or `.env` via DOTENV_CONFIG_PATH — but a branch URL is\n // derived here and exists nowhere else, and `--database-url` lives only\n // in this process's argv. Without this the pointer resolves correctly\n // and then changes nothing: `rebase db backup` on a switched checkout\n // still reported `Database: leadgen`, and `rebase dev --database-url …`\n // announced the database and then died on `DATABASE_URL: is required`.\n //\n // Safe to set: `dotenv` does not overwrite a variable that is already\n // in the environment, so the child's own `.env` load cannot undo it.\n // On a branch, the database it was branched from too.\n return { database, env: { DATABASE_URL: database.url, ...parentEnv }, description };\n }\n\n if (database.kind === \"docker\") {\n // Docker is the one case where nothing has named a connection string:\n // `.env` leaves DATABASE_URL commented out, so without this the child\n // booted with no database at all and failed on the message a project\n // that configured nothing gets — while the container it had just been\n // asked for was never started either.\n if (!database.url) {\n throw new Refusal(\n \"--docker needs a docker-compose.yml with a db service in this project, \" +\n \"and this one has none that names POSTGRES_USER, POSTGRES_DB and a published port. \" +\n \"Set DATABASE_URL in .env to point at the database you mean instead.\"\n );\n }\n // Said every time it decides, because nothing on this command line\n // asked for Docker: the reader should not have to remember that an\n // earlier `rebase dev` did.\n if (database.source === \"last-dev\") {\n options.onProgress?.(\n `Using ${branch ? `branch \"${branch.name}\" (${branch.database}) of ` : \"\"}Postgres in Docker, `\n + \"as the last `rebase dev --docker` did. `rebase dev` without --docker goes back to the managed database.\"\n );\n }\n return { database, env: { DATABASE_URL: database.url, ...parentEnv }, description };\n }\n\n if (database.kind !== \"managed\") {\n // `environment` or `env-file`: the connection string is already in a\n // place the child reads for itself, so this adds nothing to it.\n return { database, env: {}, description };\n }\n\n // Only the keys nobody bound by hand. A developer who set\n // DATABASE_URL__ANALYTICS to a warehouse of their own has said which\n // database that is, and the managed one fills a vacuum, never a choice.\n const unbound = (options.additionalKeys ?? []).filter((key) => {\n const name = `DATABASE_URL${resourceEnvSuffix(key)}`;\n return !process.env[name] && !envFile[name];\n });\n\n const managed = await ensureManagedDatabase(projectRoot, {\n quiet: options.quiet,\n onProgress: options.onProgress,\n additionalKeys: unbound\n });\n\n const additionalEnv: Record<string, string> = {};\n for (const [key, url] of Object.entries(managed.additional)) {\n additionalEnv[`DATABASE_URL${resourceEnvSuffix(key)}`] = url;\n }\n\n return {\n database,\n description,\n dataDir: managed.dataDir,\n startedDaemon: managed.started,\n additional: managed.additional,\n env: {\n DATABASE_URL: managed.url,\n // PGlite is one session behind a multiplexer: two pooled clients in\n // overlapping transactions deadlock there. This is the ceiling that\n // turns that into ordinary queueing — see `constraints.ts`.\n REBASE_DB_POOL_MAX: String(MANAGED_POOL_MAX),\n ...additionalEnv\n }\n };\n}\n\n/**\n * The lines to print about a managed database, in the order to print them.\n *\n * Returned rather than printed so the caller decides where they go — `dev` has\n * a banner, `db push` has a single line above its own output — and so a test can\n * assert on them without capturing a stream.\n */\nexport function managedNotices(prepared: PreparedDatabase): string[] {\n if (prepared.database.kind !== \"managed\") return [];\n\n const lines = [`Using ${prepared.description}.`];\n if (prepared.dataDir) lines.push(`Data: ${prepared.dataDir}`);\n for (const key of Object.keys(prepared.additional ?? {})) {\n lines.push(`Also serving database \"${key}\" as DATABASE_URL${resourceEnvSuffix(key)}`);\n }\n\n // Stated every time rather than discovered. A developer who does not know\n // requests are serialized here will read a concurrency difference as a bug\n // in their own code.\n for (const limitation of MANAGED_LIMITATIONS) {\n lines.push(`${limitation.summary} ${limitation.remedy}`);\n }\n lines.push(\"To use your own Postgres instead, set DATABASE_URL in .env.\");\n\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,kBAAkB,aAA6B;CAC3D,OAAO,KAAK,KAAK,aAAa,WAAW,aAAa;AAC1D;AAmBA,SAAgB,mBAAmB,MAAsB;CACrD,OAAO,MAAsB;AACjC;;AAGA,SAAgB,iBAAiB,aAA0C;CACvE,IAAI;EACA,MAAM,MAAM,GAAG,aAAa,kBAAkB,WAAW,GAAG,OAAO;EACnE,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,IAAI,OAAO,OAAO,SAAS,YAAY,OAAO,OAAO,aAAa,UAAU,OAAO;EACnF,IAAI,CAAC,OAAO,QAAQ,CAAC,OAAO,UAAU,OAAO;EAE7C,OAAO;GAAE,MAAM,OAAO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