@rebasepro/cli 0.30.0 → 0.31.0-canary.g59cd6fd

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 (286) 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-D96QYgFR.js} +7 -6
  13. package/dist/{auth-Bv0rTbQX.js.map → auth-D96QYgFR.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-C1d3LwB7.js} +14 -14
  81. package/dist/console-C1d3LwB7.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-DQZK9n9c.js} +52 -51
  87. package/dist/db-DQZK9n9c.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-C93d4QIv.js → dev-PY5h4O6u.js} +142 -84
  91. package/dist/dev-PY5h4O6u.js.map +1 -0
  92. package/dist/dev-db/attver.d.ts +32 -0
  93. package/dist/dev-db/pull.d.ts +15 -1
  94. package/dist/{dev-preflight-Cxv3TiD1.js → dev-preflight-DjvcV6SK.js} +5 -5
  95. package/dist/dev-preflight-DjvcV6SK.js.map +1 -0
  96. package/dist/{dev-server-OJsUGZEB.js → dev-server-BLxCbQEP.js} +2 -2
  97. package/dist/{dev-server-OJsUGZEB.js.map → dev-server-BLxCbQEP.js.map} +1 -1
  98. package/dist/{doctor-BBPQUO2g.js → doctor-CnUu8kpM.js} +39 -62
  99. package/dist/doctor-CnUu8kpM.js.map +1 -0
  100. package/dist/doctor-environment.d.ts +6 -6
  101. package/dist/{eject-DABcDnPN.js → eject-Bhzd6hgb.js} +25 -16
  102. package/dist/eject-Bhzd6hgb.js.map +1 -0
  103. package/dist/{fold-static-BWzxNn06.js → fold-static-CKewnAPX.js} +5 -3
  104. package/dist/fold-static-CKewnAPX.js.map +1 -0
  105. package/dist/{generate-view-IFwCADvb.js → generate-view-CTOluXvH.js} +160 -89
  106. package/dist/generate-view-CTOluXvH.js.map +1 -0
  107. package/dist/{generate_sdk-DNmNuFuW.js → generate_sdk-De-aLC1L.js} +120 -137
  108. package/dist/generate_sdk-De-aLC1L.js.map +1 -0
  109. package/dist/import-schema-module-Df67TIWj.js +51 -0
  110. package/dist/import-schema-module-Df67TIWj.js.map +1 -0
  111. package/dist/index.es.js +64 -51
  112. package/dist/index.es.js.map +1 -1
  113. package/dist/{init-vL1DWOeC.js → init-Dtl-IcXf.js} +83 -80
  114. package/dist/init-Dtl-IcXf.js.map +1 -0
  115. package/dist/last-dev-database-Dc8cP01o.js +2 -0
  116. package/dist/{manifest-BtzDy7KQ.js → manifest-C3uLDrrJ.js} +115 -40
  117. package/dist/manifest-C3uLDrrJ.js.map +1 -0
  118. package/dist/manifest.d.ts +79 -24
  119. package/dist/migrate-VrKoi3nB.js +138 -0
  120. package/dist/migrate-VrKoi3nB.js.map +1 -0
  121. package/dist/{normalize-imports-Bd5Y4yLp.js → normalize-imports-DwxqEMYq.js} +3 -3
  122. package/dist/{normalize-imports-Bd5Y4yLp.js.map → normalize-imports-DwxqEMYq.js.map} +1 -1
  123. package/dist/path-flags-7O5uPBcQ.js +139 -0
  124. package/dist/path-flags-7O5uPBcQ.js.map +1 -0
  125. package/dist/{prepare-CTw9NEkh.js → prepare-Ccxspoj-.js} +4 -4
  126. package/dist/{prepare-CTw9NEkh.js.map → prepare-Ccxspoj-.js.map} +1 -1
  127. package/dist/project-CLcF5i8c.js +360 -0
  128. package/dist/project-CLcF5i8c.js.map +1 -0
  129. package/dist/project-schema-CsSOG2gE.js +30 -0
  130. package/dist/project-schema-CsSOG2gE.js.map +1 -0
  131. package/dist/{pull-DDMpsZ5r.js → pull-DRWqBZp5.js} +327 -4
  132. package/dist/pull-DRWqBZp5.js.map +1 -0
  133. package/dist/resolve-BY7bSFRT.js +2 -0
  134. package/dist/resources/derive.d.ts +19 -13
  135. package/dist/{resources-CPSC5Kcu.js → resources-Dpfs2y8P.js} +5 -4
  136. package/dist/{resources-CPSC5Kcu.js.map → resources-Dpfs2y8P.js.map} +1 -1
  137. package/dist/{schema-DtLPsXbT.js → schema-CdDjv5zI.js} +41 -39
  138. package/dist/schema-CdDjv5zI.js.map +1 -0
  139. package/dist/schema-dir-Cd1kvYbf.js +98 -0
  140. package/dist/schema-dir-Cd1kvYbf.js.map +1 -0
  141. package/dist/schema-reconcile-BAupXfkd.js +2 -0
  142. package/dist/schema-text-CpNrsuMe.js +73 -0
  143. package/dist/schema-text-CpNrsuMe.js.map +1 -0
  144. package/dist/{skills-CbwV6vw_.js → skills-CXjA9TWw.js} +54 -10
  145. package/dist/skills-CXjA9TWw.js.map +1 -0
  146. package/dist/{start-YOr3X5Zm.js → start-Bwbtt2W5.js} +7 -10
  147. package/dist/{start-YOr3X5Zm.js.map → start-Bwbtt2W5.js.map} +1 -1
  148. package/dist/{status-BREvtzJm.js → status-D7XCGHu2.js} +12 -12
  149. package/dist/status-D7XCGHu2.js.map +1 -0
  150. package/dist/{storage-CO9ouK76.js → storage-iTqj5-Av.js} +12 -11
  151. package/dist/storage-iTqj5-Av.js.map +1 -0
  152. package/dist/{telemetry-DwK5RQJl.js → telemetry-BP_1Cl9r.js} +4 -4
  153. package/dist/{telemetry-DwK5RQJl.js.map → telemetry-BP_1Cl9r.js.map} +1 -1
  154. package/dist/{telemetry-CgwJPVMO.js → telemetry-M3HjlyhZ.js} +2 -2
  155. package/dist/{telemetry-CgwJPVMO.js.map → telemetry-M3HjlyhZ.js.map} +1 -1
  156. package/dist/{upgrade-B7sVwL8S.js → upgrade-oZzJ13jM.js} +5 -4
  157. package/dist/{upgrade-B7sVwL8S.js.map → upgrade-oZzJ13jM.js.map} +1 -1
  158. package/dist/utils/backend-guard.d.ts +47 -0
  159. package/dist/utils/cms-directories.d.ts +6 -0
  160. package/dist/utils/dev-preflight.d.ts +2 -2
  161. package/dist/utils/import-schema-module.d.ts +16 -0
  162. package/dist/utils/path-flags.d.ts +35 -16
  163. package/dist/utils/project-schema.d.ts +40 -0
  164. package/dist/utils/project.d.ts +8 -2
  165. package/dist/utils/schema-dir.d.ts +32 -0
  166. package/dist/utils/schema-drift.d.ts +6 -0
  167. package/dist/utils/schema-text.d.ts +24 -0
  168. package/dist/verify-5p_vaUG2.js +1160 -0
  169. package/dist/verify-5p_vaUG2.js.map +1 -0
  170. package/package.json +11 -8
  171. package/runtime/dev-server.mjs +5 -1
  172. package/templates/eject/Dockerfile +1 -4
  173. package/templates/eject/backend/src/env.ts +1 -1
  174. package/templates/eject/backend/src/index.ts +53 -40
  175. package/templates/eject/docker-compose.custom.yml +1 -1
  176. package/templates/overlays/baas/README.md +39 -12
  177. package/templates/overlays/baas/ai-instructions.md +8 -8
  178. package/templates/overlays/baas/{config → backend}/storage.ts +3 -4
  179. package/templates/overlays/baas/backend/tsconfig.json +10 -12
  180. package/templates/overlays/baas/package.json +1 -2
  181. package/templates/overlays/baas/pnpm-workspace.yaml +0 -1
  182. package/templates/presets/blank/backend/schema/index.ts +19 -0
  183. package/templates/presets/blank/frontend/src/App.tsx +56 -0
  184. package/templates/presets/ecommerce/backend/schema/categories.ts +12 -0
  185. package/templates/presets/ecommerce/backend/schema/index.ts +23 -0
  186. package/templates/presets/ecommerce/backend/schema/orders.ts +13 -0
  187. package/templates/presets/ecommerce/backend/schema/products.ts +18 -0
  188. package/templates/presets/ecommerce/frontend/src/App.tsx +59 -0
  189. package/templates/presets/ecommerce/frontend/src/cms/categories.tsx +12 -0
  190. package/templates/presets/ecommerce/frontend/src/cms/orders.tsx +38 -0
  191. package/templates/presets/ecommerce/frontend/src/cms/products.tsx +27 -0
  192. package/templates/resource-graphs/blank.json +2 -2
  193. package/templates/resource-graphs/blog.json +5 -5
  194. package/templates/resource-graphs/ecommerce.json +5 -5
  195. package/templates/resource-graphs/headless.json +1 -1
  196. package/templates/template/.claude/hooks/post-edit-collection.sh +27 -23
  197. package/templates/template/.cursorrules +2 -2
  198. package/templates/template/.env.example +6 -17
  199. package/templates/template/.github/copilot-instructions.md +2 -2
  200. package/templates/template/.windsurfrules +2 -2
  201. package/templates/template/AGENTS.md +2 -2
  202. package/templates/template/CLAUDE.md +2 -2
  203. package/templates/template/README.md +47 -13
  204. package/templates/template/ai-instructions.md +15 -14
  205. package/templates/template/backend/functions/hello.ts +1 -1
  206. package/templates/template/backend/package.json +0 -2
  207. package/templates/template/{config → backend}/resources.ts +3 -3
  208. package/templates/template/backend/schema/authors.ts +11 -0
  209. package/templates/template/backend/schema/index.ts +29 -0
  210. package/templates/template/backend/schema/posts.ts +29 -0
  211. package/templates/template/backend/schema/tags.ts +9 -0
  212. package/templates/template/backend/schema/users.ts +32 -0
  213. package/templates/template/{config → backend}/storage.ts +4 -4
  214. package/templates/template/backend/tsconfig.json +15 -20
  215. package/templates/template/docker-compose.yml +3 -3
  216. package/templates/template/frontend/package.json +0 -2
  217. package/templates/template/frontend/src/App.tsx +10 -4
  218. package/templates/template/frontend/src/cms/authors.tsx +7 -0
  219. package/templates/template/frontend/src/cms/posts.tsx +27 -0
  220. package/templates/template/frontend/src/cms/tags.tsx +11 -0
  221. package/templates/template/frontend/src/cms/ui-config.json +3 -0
  222. package/templates/template/frontend/src/cms/users.tsx +54 -0
  223. package/templates/template/frontend/src/{virtual.d.ts → vite-env.d.ts} +0 -4
  224. package/templates/template/frontend/vite.config.ts +6 -2
  225. package/templates/template/gitignore +1 -1
  226. package/templates/template/package.json +1 -2
  227. package/templates/template/pnpm-workspace.yaml +0 -1
  228. package/templates/template/scripts/example.ts +3 -3
  229. package/templates/template/tsconfig.json +1 -1
  230. package/templates/views/AppView.tsx.tmpl +4 -4
  231. package/templates/views/EntityView.tsx.tmpl +3 -4
  232. package/dist/api-keys-Dfw5-9s1.js.map +0 -1
  233. package/dist/apps-MKQbgDtN.js.map +0 -1
  234. package/dist/build-BuKTnec8.js.map +0 -1
  235. package/dist/bundle-BAH4FCju.js.map +0 -1
  236. package/dist/cloud-Cj5ey3l_.js.map +0 -1
  237. package/dist/collection-drift-BKj_BoMq.js +0 -106
  238. package/dist/collection-drift-BKj_BoMq.js.map +0 -1
  239. package/dist/collections-dir-DlvDhime.js +0 -69
  240. package/dist/collections-dir-DlvDhime.js.map +0 -1
  241. package/dist/console-CdwIYOMV.js.map +0 -1
  242. package/dist/context-AXdAh-q8.js.map +0 -1
  243. package/dist/db-DBbKpjYX.js.map +0 -1
  244. package/dist/derive-ae9UOoOB.js.map +0 -1
  245. package/dist/dev-C93d4QIv.js.map +0 -1
  246. package/dist/dev-preflight-Cxv3TiD1.js.map +0 -1
  247. package/dist/doctor-BBPQUO2g.js.map +0 -1
  248. package/dist/eject-DABcDnPN.js.map +0 -1
  249. package/dist/fold-static-BWzxNn06.js.map +0 -1
  250. package/dist/generate-view-IFwCADvb.js.map +0 -1
  251. package/dist/generate_sdk-DNmNuFuW.js.map +0 -1
  252. package/dist/init-vL1DWOeC.js.map +0 -1
  253. package/dist/last-dev-database-DpW5dfoX.js +0 -2
  254. package/dist/manifest-BtzDy7KQ.js.map +0 -1
  255. package/dist/path-flags-DNvtEi2-.js +0 -92
  256. package/dist/path-flags-DNvtEi2-.js.map +0 -1
  257. package/dist/project-CasK56vN.js.map +0 -1
  258. package/dist/pull-DDMpsZ5r.js.map +0 -1
  259. package/dist/resolve-D647F1LA.js +0 -2
  260. package/dist/schema-DtLPsXbT.js.map +0 -1
  261. package/dist/schema-reconcile-DkArN9jF.js +0 -2
  262. package/dist/skills-CbwV6vw_.js.map +0 -1
  263. package/dist/status-BREvtzJm.js.map +0 -1
  264. package/dist/storage-CO9ouK76.js.map +0 -1
  265. package/dist/utils/collection-drift.d.ts +0 -27
  266. package/dist/utils/collections-dir.d.ts +0 -14
  267. package/dist/verify-Y3rWSgfA.js +0 -730
  268. package/dist/verify-Y3rWSgfA.js.map +0 -1
  269. package/templates/overlays/baas/config/index.ts +0 -24
  270. package/templates/overlays/baas/config/package.json +0 -30
  271. package/templates/template/config/cms.d.ts +0 -15
  272. package/templates/template/config/collections/authors.ts +0 -47
  273. package/templates/template/config/collections/index.ts +0 -44
  274. package/templates/template/config/collections/posts.ts +0 -94
  275. package/templates/template/config/collections/presets/blank/index.ts +0 -5
  276. package/templates/template/config/collections/presets/ecommerce/categories.ts +0 -42
  277. package/templates/template/config/collections/presets/ecommerce/index.ts +0 -31
  278. package/templates/template/config/collections/presets/ecommerce/orders.ts +0 -78
  279. package/templates/template/config/collections/presets/ecommerce/products.ts +0 -73
  280. package/templates/template/config/collections/tags.ts +0 -27
  281. package/templates/template/config/collections/users.ts +0 -149
  282. package/templates/template/config/frontend-assets.d.ts +0 -17
  283. package/templates/template/config/index.ts +0 -12
  284. package/templates/template/config/package.json +0 -30
  285. package/templates/template/config/tsconfig.json +0 -35
  286. /package/templates/eject/{config → backend}/resources.ts +0 -0
@@ -2,6 +2,302 @@ import { r as PGLITE_EXTENSIONS } from "./constraints-CtiylsGf.js";
2
2
  import { i as hostOf, n as connectionErrorText, t as banner } from "./connection-banner-DbLJzWf4.js";
3
3
  import fs from "fs";
4
4
  import { execa } from "execa";
5
+ //#region src/dev-db/attver.ts
6
+ /**
7
+ * `pg_attver` in a dump, and taking it out before a restore.
8
+ *
9
+ * The November 2026 PostgreSQL minor releases (every branch from 14 up;
10
+ * upstream commit c23382f0a8, "Introduce attribute versioning to prevent
11
+ * unsafe deforming") keep a per-column version as an attribute option: a
12
+ * `pg_attver` key in `pg_attribute.attoptions`, set on every column created or
13
+ * altered. A `pg_dump` from before that release, pointed at a server from
14
+ * after it, dumps the key like any other attribute option:
15
+ *
16
+ * ALTER TABLE ONLY public.authors ALTER COLUMN id SET (pg_attver=33846480);
17
+ *
18
+ * and every server without the change — PGlite, which the managed development
19
+ * database runs on, and a local Postgres on an older minor — refuses it with
20
+ * `unrecognized parameter "pg_attver"`. The statement sits in the same archive
21
+ * entry as the table's `CREATE TABLE`, so that entry fails whole: no table,
22
+ * and every row, index and constraint of it after. A server with the change
23
+ * ignores the key on input, so it carries nothing a restore needs.
24
+ *
25
+ * pg_dump's own fix leaves the key out, but a pull should not depend on the
26
+ * local client being newer than the source server. So the dump is edited in
27
+ * place before pg_restore reads it: in each TOC entry's definition, the key is
28
+ * overwritten with spaces — the whole statement when it is the only option,
29
+ * the key and its comma when there are others. Byte for byte the same length,
30
+ * because the TOC records the file offset of every data block after it.
31
+ *
32
+ * The definitions are edited as bytes, never decoded: pg_dump writes them in
33
+ * the database's encoding, which need not be UTF-8. Every encoding a server
34
+ * can store is ASCII-safe — a byte below 0x80 is always that ASCII character —
35
+ * so the ASCII statement is found by reading one character per byte, and the
36
+ * bytes around it are written back exactly as they were. The client-only
37
+ * encodings (SJIS, BIG5, GBK, UHC, GB18030, JOHAB, SHIFT_JIS_2004) are not
38
+ * ASCII-safe; a dump taken in one, through `PGCLIENTENCODING` or a
39
+ * `client_encoding` in the connection string, is left as it was.
40
+ */
41
+ var ATTVER_ONLY = /^(ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET )\(pg_attver=\d+\);$/gm;
42
+ var ATTVER_FIRST = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \()pg_attver=\d+, (?=.*\);$)/gm;
43
+ var ATTVER_LATER = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \(.*), pg_attver=\d+(?=.*\);$)/gm;
44
+ function spaces(text) {
45
+ return " ".repeat(text.length);
46
+ }
47
+ /**
48
+ * A TOC entry's definition, as the bytes pg_dump wrote, without its
49
+ * `pg_attver` options: what was taken out is spaces, and every other byte is
50
+ * as it was. Matched one character per byte (`latin1`), which finds the ASCII
51
+ * statement in any ASCII-safe encoding without decoding anything else.
52
+ */
53
+ function blankAttverOptions(definition) {
54
+ const text = definition.toString("latin1");
55
+ if (!text.includes("pg_attver=")) return definition;
56
+ const blanked = text.replace(ATTVER_ONLY, (statement) => spaces(statement)).replace(ATTVER_FIRST, (option) => spaces(option)).replace(ATTVER_LATER, (option) => spaces(option));
57
+ return blanked === text ? definition : Buffer.from(blanked, "latin1");
58
+ }
59
+ /**
60
+ * The entries whose definition can hold attribute options: pg_dump's
61
+ * `dumpTableSchema` writes `ALTER … ALTER COLUMN … SET (…)` for every relation
62
+ * but a view, under the entry it describes as one of these.
63
+ */
64
+ var RELATION_ENTRIES = /* @__PURE__ */ new Set([
65
+ "TABLE",
66
+ "FOREIGN TABLE",
67
+ "MATERIALIZED VIEW"
68
+ ]);
69
+ /**
70
+ * The encodings a server can store (`PG_SQL_ASCII` … `PG_KOI8U` in
71
+ * pg_wchar.h), named as `pg_encoding_to_char` names them in the ENCODING
72
+ * entry. Each is ASCII-safe; the client-only encodings after them are not.
73
+ */
74
+ var ASCII_SAFE_ENCODINGS = /* @__PURE__ */ new Set([
75
+ "SQL_ASCII",
76
+ "EUC_JP",
77
+ "EUC_CN",
78
+ "EUC_KR",
79
+ "EUC_TW",
80
+ "EUC_JIS_2004",
81
+ "UTF8",
82
+ "MULE_INTERNAL",
83
+ "LATIN1",
84
+ "LATIN2",
85
+ "LATIN3",
86
+ "LATIN4",
87
+ "LATIN5",
88
+ "LATIN6",
89
+ "LATIN7",
90
+ "LATIN8",
91
+ "LATIN9",
92
+ "LATIN10",
93
+ "WIN1256",
94
+ "WIN1258",
95
+ "WIN866",
96
+ "WIN874",
97
+ "KOI8R",
98
+ "WIN1251",
99
+ "WIN1252",
100
+ "ISO_8859_5",
101
+ "ISO_8859_6",
102
+ "ISO_8859_7",
103
+ "ISO_8859_8",
104
+ "WIN1250",
105
+ "WIN1253",
106
+ "WIN1254",
107
+ "WIN1255",
108
+ "WIN1257",
109
+ "KOI8U"
110
+ ]);
111
+ /** `K_VERS_1_12`…`K_VERS_MAX` (1.16 at any revision): the custom-format archives pg_dump 11 to 18 write. */
112
+ var OLDEST = archiveVersion(1, 12, 0);
113
+ var NEWEST = archiveVersion(1, 16, 255);
114
+ var V1_14 = archiveVersion(1, 14, 0);
115
+ var V1_15 = archiveVersion(1, 15, 0);
116
+ var V1_16 = archiveVersion(1, 16, 0);
117
+ /** `archCustom` in pg_backup.h. */
118
+ var CUSTOM_FORMAT = 1;
119
+ /** `K_OFFSET_POS_SET` in pg_backup_custom.c: the entry's data block is at the offset that follows. */
120
+ var OFFSET_SET = 2;
121
+ function archiveVersion(major, minor, revision) {
122
+ return major << 16 | minor << 8 | revision;
123
+ }
124
+ /** Reads a custom-format archive's header and TOC straight from the file, without loading its data. */
125
+ var ArchiveReader = class {
126
+ fd;
127
+ size;
128
+ position = 0;
129
+ intSize = 4;
130
+ offSize = 8;
131
+ constructor(fd, size) {
132
+ this.fd = fd;
133
+ this.size = size;
134
+ }
135
+ bytes(length) {
136
+ if (length < 0 || this.position + length > this.size) throw new RangeError("past the end of the archive");
137
+ const buffer = Buffer.alloc(length);
138
+ let read = 0;
139
+ while (read < length) {
140
+ const n = fs.readSync(this.fd, buffer, read, length - read, this.position + read);
141
+ if (n === 0) throw new RangeError("past the end of the archive");
142
+ read += n;
143
+ }
144
+ this.position += length;
145
+ return buffer;
146
+ }
147
+ byte() {
148
+ return this.bytes(1)[0] ?? 0;
149
+ }
150
+ /** `ReadInt`: a sign byte, then `intSize` bytes, least significant first. */
151
+ int() {
152
+ const negative = this.byte() !== 0;
153
+ const digits = this.bytes(this.intSize);
154
+ let value = 0;
155
+ for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);
156
+ return negative ? -value : value;
157
+ }
158
+ /** `ReadStr`: a length, then that many bytes; a negative length is NULL. Returns the bytes and where they are. */
159
+ str() {
160
+ const length = this.int();
161
+ if (length < 0) return null;
162
+ return {
163
+ at: this.position,
164
+ bytes: this.bytes(length)
165
+ };
166
+ }
167
+ /** `ReadStr` for a field that is ASCII in every dump: a tag, a description, a version. */
168
+ ascii() {
169
+ return this.str()?.bytes.toString("latin1") ?? null;
170
+ }
171
+ /** `ReadOffset`: a flag byte, then `offSize` bytes, least significant first. */
172
+ offset() {
173
+ const flag = this.byte();
174
+ const digits = this.bytes(this.offSize);
175
+ let value = 0;
176
+ for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);
177
+ return {
178
+ set: flag === OFFSET_SET,
179
+ value
180
+ };
181
+ }
182
+ };
183
+ var NOT_AN_ARCHIVE = "it is not a pg_dump custom-format archive this can read";
184
+ /** The edits that blank `pg_attver` in an archive's TOC, or why there are none to make safely. */
185
+ function planPatches(fd, size, blank) {
186
+ const reader = new ArchiveReader(fd, size);
187
+ let serverVersion = null;
188
+ let dumpVersion = null;
189
+ const refuse = (reason) => ({
190
+ ok: false,
191
+ reason,
192
+ serverVersion,
193
+ dumpVersion
194
+ });
195
+ if (reader.bytes(5).toString("latin1") !== "PGDMP") return refuse(NOT_AN_ARCHIVE);
196
+ const major = reader.byte();
197
+ const minor = reader.byte();
198
+ const revision = reader.byte();
199
+ const version = archiveVersion(major, minor, revision);
200
+ if (version < OLDEST || version > NEWEST) return refuse(`its archive format is version ${major}.${minor}.${revision}, which this version of Rebase does not read`);
201
+ reader.intSize = reader.byte();
202
+ reader.offSize = reader.byte();
203
+ if (reader.intSize < 1 || reader.intSize > 8 || reader.offSize < 1 || reader.offSize > 8) return refuse(NOT_AN_ARCHIVE);
204
+ if (reader.byte() !== CUSTOM_FORMAT) return refuse(NOT_AN_ARCHIVE);
205
+ if (version >= V1_15) reader.byte();
206
+ else reader.int();
207
+ for (let i = 0; i < 7; i++) reader.int();
208
+ reader.str();
209
+ serverVersion = reader.ascii();
210
+ dumpVersion = reader.ascii();
211
+ const patches = [];
212
+ let encoding = null;
213
+ let firstData = Number.POSITIVE_INFINITY;
214
+ const entries = reader.int();
215
+ if (entries < 0) return refuse(NOT_AN_ARCHIVE);
216
+ for (let i = 0; i < entries; i++) {
217
+ reader.int();
218
+ reader.int();
219
+ reader.str();
220
+ reader.str();
221
+ reader.str();
222
+ const desc = reader.ascii();
223
+ reader.int();
224
+ const definition = reader.str();
225
+ reader.str();
226
+ reader.str();
227
+ reader.str();
228
+ reader.str();
229
+ if (version >= V1_14) reader.str();
230
+ if (version >= V1_16) reader.int();
231
+ reader.str();
232
+ reader.str();
233
+ while (reader.str() !== null);
234
+ const data = reader.offset();
235
+ if (data.set) firstData = Math.min(firstData, data.value);
236
+ if (!definition) continue;
237
+ if (desc === "ENCODING") encoding = /client_encoding = '([^']*)'/.exec(definition.bytes.toString("latin1"))?.[1] ?? null;
238
+ else if (desc !== null && RELATION_ENTRIES.has(desc)) {
239
+ const blanked = blank(definition.bytes);
240
+ if (blanked.equals(definition.bytes)) continue;
241
+ if (blanked.length !== definition.bytes.length) return refuse(`taking pg_attver out of one of its entries would have changed that entry's length (${definition.bytes.length} bytes to ${blanked.length})`);
242
+ patches.push({
243
+ at: definition.at,
244
+ bytes: blanked
245
+ });
246
+ }
247
+ }
248
+ if (reader.position > firstData) return refuse(NOT_AN_ARCHIVE);
249
+ if (patches.length > 0 && (encoding === null || !ASCII_SAFE_ENCODINGS.has(encoding))) return refuse(encoding === null ? "it does not say which encoding it is written in" : `it is written in the ${encoding} encoding, which this cannot edit safely; dump in the database's own encoding instead (unset PGCLIENTENCODING)`);
250
+ return {
251
+ ok: true,
252
+ patches,
253
+ serverVersion,
254
+ dumpVersion
255
+ };
256
+ }
257
+ /**
258
+ * Blank every `pg_attver` attribute option in a custom-format dump, in place.
259
+ *
260
+ * A file this does not recognise, or cannot edit safely, is left byte for
261
+ * byte as it was — pg_restore then reads it as it is — and the result says
262
+ * why. `blank` is the edit made to each table's definition: the pull always
263
+ * uses the default, {@link blankAttverOptions}; it is a parameter so that the
264
+ * guard against an edit that changes a definition's length can be tested.
265
+ */
266
+ function stripAttverFromArchive(dumpFile, blank = blankAttverOptions) {
267
+ const fd = fs.openSync(dumpFile, "r+");
268
+ try {
269
+ let plan;
270
+ try {
271
+ plan = planPatches(fd, fs.fstatSync(fd).size, blank);
272
+ } catch (error) {
273
+ if (!(error instanceof RangeError)) throw error;
274
+ plan = {
275
+ ok: false,
276
+ reason: NOT_AN_ARCHIVE,
277
+ serverVersion: null,
278
+ dumpVersion: null
279
+ };
280
+ }
281
+ const versions = {
282
+ serverVersion: plan.serverVersion,
283
+ dumpVersion: plan.dumpVersion
284
+ };
285
+ if (!plan.ok) return {
286
+ entries: 0,
287
+ skipped: plan.reason,
288
+ ...versions
289
+ };
290
+ for (const patch of plan.patches) fs.writeSync(fd, patch.bytes, 0, patch.bytes.length, patch.at);
291
+ return {
292
+ entries: plan.patches.length,
293
+ skipped: null,
294
+ ...versions
295
+ };
296
+ } finally {
297
+ fs.closeSync(fd);
298
+ }
299
+ }
300
+ //#endregion
5
301
  //#region src/dev-db/pull.ts
6
302
  /**
7
303
  * `rebase db pull` — copy a database's contents into local development.
@@ -671,8 +967,13 @@ function describeDumpFailure(source, run) {
671
967
  * advice names that, rather than "pull again", which sent people in a loop.
672
968
  * On the managed database an extension cannot be installed at all, so the
673
969
  * advice there is Postgres in Docker.
970
+ *
971
+ * One cause is named for what it is: a target refusing `pg_attver`, which
972
+ * means the local pg_dump is older than the source server and the dump could
973
+ * not be edited to drop the key (`attver`, what {@link stripAttverFromArchive}
974
+ * said, tells why).
674
975
  */
675
- function restoreOutcome(run, engine = "postgres") {
976
+ function restoreOutcome(run, engine = "postgres", attver = null) {
676
977
  if (run.signal) return {
677
978
  started: true,
678
979
  failure: `pg_restore was stopped by ${run.signal} before it finished.`,
@@ -689,7 +990,7 @@ function restoreOutcome(run, engine = "postgres") {
689
990
  advice: null
690
991
  };
691
992
  const ignored = /errors ignored on restore: (\d+)/.exec(run.stderr ?? "");
692
- const repeats = engine === "pglite" ? `Pulling again repeats these errors until what they name is fixed — most often an extension the source uses that the managed database does not have (it has ${PGLITE_EXTENSIONS.map((extension) => extension.name).join(", ")}). Pull into Postgres in Docker instead (\`rebase db pull --docker\`), or pull only the schemas that do not need it (--schema).` : "Pulling again repeats these errors until what they name is fixed — most often an extension the source uses that this Postgres does not have installed. Install it here, or pull only the schemas that do not need it (--schema).";
993
+ const repeats = (run.stderr ?? "").includes("unrecognized parameter \"pg_attver\"") ? attverAdvice(attver) : engine === "pglite" ? `Pulling again repeats these errors until what they name is fixed — most often an extension the source uses that the managed database does not have (it has ${PGLITE_EXTENSIONS.map((extension) => extension.name).join(", ")}). Pull into Postgres in Docker instead (\`rebase db pull --docker\`), or pull only the schemas that do not need it (--schema).` : "Pulling again repeats these errors until what they name is fixed — most often an extension the source uses that this Postgres does not have installed. Install it here, or pull only the schemas that do not need it (--schema).";
693
994
  return {
694
995
  started: true,
695
996
  failure: ignored ? `pg_restore could not restore ${ignored[1]} object(s) — the errors are above.` : `pg_restore exited with code ${run.exitCode} — the errors are above.`,
@@ -697,6 +998,25 @@ function restoreOutcome(run, engine = "postgres") {
697
998
  };
698
999
  }
699
1000
  /**
1001
+ * What to do when the target refused the dump's `pg_attver` options: they are
1002
+ * there because the local pg_dump is older than the server it dumped from,
1003
+ * and a pg_dump at least as new leaves them out.
1004
+ */
1005
+ function attverAdvice(attver) {
1006
+ return `${attver?.dumpVersion && attver.serverVersion ? `Your pg_dump (${attver.dumpVersion}) is older than the server it dumped from (${attver.serverVersion})` : "Your pg_dump is older than the server it dumped from"}: it wrote pg_attver column options, which this database refuses${attver?.skipped ? `, and Rebase could not take them out of this dump: ${attver.skipped}` : ""}. Upgrade the PostgreSQL client tools to ${attver?.serverVersion ? `at least ${attver.serverVersion}` : "at least the server's minor version"} (check with \`pg_dump --version\`), then pull again.`;
1007
+ }
1008
+ /**
1009
+ * The line a pull prints when it took `pg_attver` out of the dump: the copy is
1010
+ * whole, but the local pg_dump is older than the source server, which is what
1011
+ * to fix. Null when nothing was taken out.
1012
+ */
1013
+ function attverNotice(attver) {
1014
+ if (attver.entries === 0) return null;
1015
+ const older = attver.dumpVersion && attver.serverVersion ? `Your pg_dump (${attver.dumpVersion}) is older than the server it dumped from (${attver.serverVersion})` : "Your pg_dump is older than the server it dumped from";
1016
+ const atLeast = attver.serverVersion ? `at least ${attver.serverVersion}` : "at least the server's minor version";
1017
+ return `${older}: its dump carried pg_attver column options this database would refuse, so they were taken out of ${attver.entries} table(s) before restoring. Upgrading the PostgreSQL client tools to ${atLeast} is the supported fix.`;
1018
+ }
1019
+ /**
700
1020
  * The local schemas a pull empties before it restores: every one of the local
701
1021
  * database's own for a whole-database pull, and those it copies for a
702
1022
  * `--schema` pull. `pg_catalog`, `information_schema` and the `pg_*` internals
@@ -781,6 +1101,7 @@ async function restoreCopy(plan, dumpFile) {
781
1101
  } finally {
782
1102
  await client.end().catch(() => void 0);
783
1103
  }
1104
+ const attver = stripAttverFromArchive(dumpFile);
784
1105
  const run = await execa("pg_restore", restoreArgs(plan, dumpFile), {
785
1106
  env: restoreEnv(plan),
786
1107
  stdin: "ignore",
@@ -789,9 +1110,11 @@ async function restoreCopy(plan, dumpFile) {
789
1110
  reject: false
790
1111
  });
791
1112
  if (engine === "pglite") await resetSharedSession(plan.target);
1113
+ const notice = attverNotice(attver);
792
1114
  return {
793
1115
  cleared: true,
794
- ...restoreOutcome(run, engine)
1116
+ ...restoreOutcome(run, engine, attver),
1117
+ ...notice ? { notice } : {}
795
1118
  };
796
1119
  }
797
1120
  /**
@@ -834,4 +1157,4 @@ function describeRestoreFailure(outcome, source) {
834
1157
  //#endregion
835
1158
  export { anonymizeCopy, describeRestoreFailure, describeTarget, dumpSource, findPgTool, provisionableSchemas, restoreCopy, sourceProblem };
836
1159
 
837
- //# sourceMappingURL=pull-DDMpsZ5r.js.map
1160
+ //# sourceMappingURL=pull-DRWqBZp5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull-DRWqBZp5.js","names":[],"sources":["../src/dev-db/attver.ts","../src/dev-db/pull.ts"],"sourcesContent":["/**\n * `pg_attver` in a dump, and taking it out before a restore.\n *\n * The November 2026 PostgreSQL minor releases (every branch from 14 up;\n * upstream commit c23382f0a8, \"Introduce attribute versioning to prevent\n * unsafe deforming\") keep a per-column version as an attribute option: a\n * `pg_attver` key in `pg_attribute.attoptions`, set on every column created or\n * altered. A `pg_dump` from before that release, pointed at a server from\n * after it, dumps the key like any other attribute option:\n *\n * ALTER TABLE ONLY public.authors ALTER COLUMN id SET (pg_attver=33846480);\n *\n * and every server without the change — PGlite, which the managed development\n * database runs on, and a local Postgres on an older minor — refuses it with\n * `unrecognized parameter \"pg_attver\"`. The statement sits in the same archive\n * entry as the table's `CREATE TABLE`, so that entry fails whole: no table,\n * and every row, index and constraint of it after. A server with the change\n * ignores the key on input, so it carries nothing a restore needs.\n *\n * pg_dump's own fix leaves the key out, but a pull should not depend on the\n * local client being newer than the source server. So the dump is edited in\n * place before pg_restore reads it: in each TOC entry's definition, the key is\n * overwritten with spaces — the whole statement when it is the only option,\n * the key and its comma when there are others. Byte for byte the same length,\n * because the TOC records the file offset of every data block after it.\n *\n * The definitions are edited as bytes, never decoded: pg_dump writes them in\n * the database's encoding, which need not be UTF-8. Every encoding a server\n * can store is ASCII-safe — a byte below 0x80 is always that ASCII character —\n * so the ASCII statement is found by reading one character per byte, and the\n * bytes around it are written back exactly as they were. The client-only\n * encodings (SJIS, BIG5, GBK, UHC, GB18030, JOHAB, SHIFT_JIS_2004) are not\n * ASCII-safe; a dump taken in one, through `PGCLIENTENCODING` or a\n * `client_encoding` in the connection string, is left as it was.\n */\nimport fs from \"fs\";\n\nconst ATTVER_ONLY = /^(ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET )\\(pg_attver=\\d+\\);$/gm;\nconst ATTVER_FIRST = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \\()pg_attver=\\d+, (?=.*\\);$)/gm;\nconst ATTVER_LATER = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \\(.*), pg_attver=\\d+(?=.*\\);$)/gm;\n\nfunction spaces(text: string): string {\n return \" \".repeat(text.length);\n}\n\n/**\n * A TOC entry's definition, as the bytes pg_dump wrote, without its\n * `pg_attver` options: what was taken out is spaces, and every other byte is\n * as it was. Matched one character per byte (`latin1`), which finds the ASCII\n * statement in any ASCII-safe encoding without decoding anything else.\n */\nexport function blankAttverOptions(definition: Buffer): Buffer {\n const text = definition.toString(\"latin1\");\n if (!text.includes(\"pg_attver=\")) return definition;\n\n const blanked = text\n .replace(ATTVER_ONLY, (statement) => spaces(statement))\n .replace(ATTVER_FIRST, (option) => spaces(option))\n .replace(ATTVER_LATER, (option) => spaces(option));\n\n return blanked === text ? definition : Buffer.from(blanked, \"latin1\");\n}\n\n/**\n * The entries whose definition can hold attribute options: pg_dump's\n * `dumpTableSchema` writes `ALTER … ALTER COLUMN … SET (…)` for every relation\n * but a view, under the entry it describes as one of these.\n */\nconst RELATION_ENTRIES = new Set([\"TABLE\", \"FOREIGN TABLE\", \"MATERIALIZED VIEW\"]);\n\n/**\n * The encodings a server can store (`PG_SQL_ASCII` … `PG_KOI8U` in\n * pg_wchar.h), named as `pg_encoding_to_char` names them in the ENCODING\n * entry. Each is ASCII-safe; the client-only encodings after them are not.\n */\nconst ASCII_SAFE_ENCODINGS = new Set([\n \"SQL_ASCII\", \"EUC_JP\", \"EUC_CN\", \"EUC_KR\", \"EUC_TW\", \"EUC_JIS_2004\", \"UTF8\", \"MULE_INTERNAL\",\n \"LATIN1\", \"LATIN2\", \"LATIN3\", \"LATIN4\", \"LATIN5\", \"LATIN6\", \"LATIN7\", \"LATIN8\", \"LATIN9\", \"LATIN10\",\n \"WIN1256\", \"WIN1258\", \"WIN866\", \"WIN874\", \"KOI8R\", \"WIN1251\", \"WIN1252\",\n \"ISO_8859_5\", \"ISO_8859_6\", \"ISO_8859_7\", \"ISO_8859_8\",\n \"WIN1250\", \"WIN1253\", \"WIN1254\", \"WIN1255\", \"WIN1257\", \"KOI8U\"\n]);\n\n/** `K_VERS_1_12`…`K_VERS_MAX` (1.16 at any revision): the custom-format archives pg_dump 11 to 18 write. */\nconst OLDEST = archiveVersion(1, 12, 0);\nconst NEWEST = archiveVersion(1, 16, 255);\nconst V1_14 = archiveVersion(1, 14, 0);\nconst V1_15 = archiveVersion(1, 15, 0);\nconst V1_16 = archiveVersion(1, 16, 0);\n/** `archCustom` in pg_backup.h. */\nconst CUSTOM_FORMAT = 1;\n/** `K_OFFSET_POS_SET` in pg_backup_custom.c: the entry's data block is at the offset that follows. */\nconst OFFSET_SET = 2;\n\nfunction archiveVersion(major: number, minor: number, revision: number): number {\n return (major << 16) | (minor << 8) | revision;\n}\n\n/** Reads a custom-format archive's header and TOC straight from the file, without loading its data. */\nclass ArchiveReader {\n position = 0;\n intSize = 4;\n offSize = 8;\n\n constructor(private readonly fd: number, private readonly size: number) {}\n\n bytes(length: number): Buffer {\n if (length < 0 || this.position + length > this.size) throw new RangeError(\"past the end of the archive\");\n const buffer = Buffer.alloc(length);\n let read = 0;\n while (read < length) {\n const n = fs.readSync(this.fd, buffer, read, length - read, this.position + read);\n if (n === 0) throw new RangeError(\"past the end of the archive\");\n read += n;\n }\n this.position += length;\n return buffer;\n }\n\n byte(): number {\n return this.bytes(1)[0] ?? 0;\n }\n\n /** `ReadInt`: a sign byte, then `intSize` bytes, least significant first. */\n int(): number {\n const negative = this.byte() !== 0;\n const digits = this.bytes(this.intSize);\n let value = 0;\n for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);\n return negative ? -value : value;\n }\n\n /** `ReadStr`: a length, then that many bytes; a negative length is NULL. Returns the bytes and where they are. */\n str(): { at: number; bytes: Buffer } | null {\n const length = this.int();\n if (length < 0) return null;\n const at = this.position;\n return { at, bytes: this.bytes(length) };\n }\n\n /** `ReadStr` for a field that is ASCII in every dump: a tag, a description, a version. */\n ascii(): string | null {\n return this.str()?.bytes.toString(\"latin1\") ?? null;\n }\n\n /** `ReadOffset`: a flag byte, then `offSize` bytes, least significant first. */\n offset(): { set: boolean; value: number } {\n const flag = this.byte();\n const digits = this.bytes(this.offSize);\n let value = 0;\n for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);\n return { set: flag === OFFSET_SET, value };\n }\n}\n\ninterface Patch {\n at: number;\n bytes: Buffer;\n}\n\n/** What {@link stripAttverFromArchive} did to a dump. */\nexport interface AttverStrip {\n /** How many TOC entries had their `pg_attver` options blanked. */\n entries: number;\n /**\n * Why the dump was left exactly as it was, when it could not be read or\n * edited safely; null when it was read through. A skipped dump that holds\n * `pg_attver` options fails to restore on a server without the change.\n */\n skipped: string | null;\n /** The source server's version, as the archive's header records it; null when it was not read. */\n serverVersion: string | null;\n /** The version of the pg_dump that wrote the archive, from its header; null when it was not read. */\n dumpVersion: string | null;\n}\n\ntype Plan =\n | { ok: true; patches: Patch[]; serverVersion: string | null; dumpVersion: string | null }\n | { ok: false; reason: string; serverVersion: string | null; dumpVersion: string | null };\n\nconst NOT_AN_ARCHIVE = \"it is not a pg_dump custom-format archive this can read\";\n\n/** The edits that blank `pg_attver` in an archive's TOC, or why there are none to make safely. */\nfunction planPatches(fd: number, size: number, blank: (definition: Buffer) => Buffer): Plan {\n const reader = new ArchiveReader(fd, size);\n let serverVersion: string | null = null;\n let dumpVersion: string | null = null;\n const refuse = (reason: string): Plan => ({ ok: false, reason, serverVersion, dumpVersion });\n\n if (reader.bytes(5).toString(\"latin1\") !== \"PGDMP\") return refuse(NOT_AN_ARCHIVE);\n const major = reader.byte();\n const minor = reader.byte();\n const revision = reader.byte();\n const version = archiveVersion(major, minor, revision);\n if (version < OLDEST || version > NEWEST) {\n return refuse(`its archive format is version ${major}.${minor}.${revision}, which this version of Rebase does not read`);\n }\n reader.intSize = reader.byte();\n reader.offSize = reader.byte();\n if (reader.intSize < 1 || reader.intSize > 8 || reader.offSize < 1 || reader.offSize > 8) return refuse(NOT_AN_ARCHIVE);\n if (reader.byte() !== CUSTOM_FORMAT) return refuse(NOT_AN_ARCHIVE);\n\n // ReadHead: compression, creation time, database name, server and pg_dump versions.\n if (version >= V1_15) reader.byte();\n else reader.int();\n for (let i = 0; i < 7; i++) reader.int();\n reader.str();\n serverVersion = reader.ascii();\n dumpVersion = reader.ascii();\n\n // ReadToc, with the custom format's ReadExtraToc after each entry.\n const patches: Patch[] = [];\n let encoding: string | null = null;\n let firstData = Number.POSITIVE_INFINITY;\n const entries = reader.int();\n if (entries < 0) return refuse(NOT_AN_ARCHIVE);\n for (let i = 0; i < entries; i++) {\n reader.int(); // dumpId\n reader.int(); // hadDumper\n reader.str(); // tableoid\n reader.str(); // oid\n reader.str(); // tag\n const desc = reader.ascii();\n reader.int(); // section\n const definition = reader.str();\n reader.str(); // dropStmt\n reader.str(); // copyStmt\n reader.str(); // namespace\n reader.str(); // tablespace\n if (version >= V1_14) reader.str(); // tableam\n if (version >= V1_16) reader.int(); // relkind\n reader.str(); // owner\n reader.str(); // \"false\": the old withOids\n while (reader.str() !== null); // dependencies, ended by NULL\n const data = reader.offset();\n if (data.set) firstData = Math.min(firstData, data.value);\n\n if (!definition) continue;\n if (desc === \"ENCODING\") {\n encoding = /client_encoding = '([^']*)'/.exec(definition.bytes.toString(\"latin1\"))?.[1] ?? null;\n } else if (desc !== null && RELATION_ENTRIES.has(desc)) {\n const blanked = blank(definition.bytes);\n if (blanked.equals(definition.bytes)) continue;\n if (blanked.length !== definition.bytes.length) {\n return refuse(`taking pg_attver out of one of its entries would have changed that entry's length (${definition.bytes.length} bytes to ${blanked.length})`);\n }\n patches.push({ at: definition.at, bytes: blanked });\n }\n }\n\n // The data blocks follow the TOC. If they do not start after where this\n // read it to end, the layout was not the one assumed: change nothing.\n if (reader.position > firstData) return refuse(NOT_AN_ARCHIVE);\n\n // Found by matching bytes as ASCII, which only an ASCII-safe encoding\n // makes the statement it looks like.\n if (patches.length > 0 && (encoding === null || !ASCII_SAFE_ENCODINGS.has(encoding))) {\n return refuse(encoding === null\n ? \"it does not say which encoding it is written in\"\n : `it is written in the ${encoding} encoding, which this cannot edit safely; dump in the database's own encoding instead (unset PGCLIENTENCODING)`);\n }\n\n return { ok: true, patches, serverVersion, dumpVersion };\n}\n\n/**\n * Blank every `pg_attver` attribute option in a custom-format dump, in place.\n *\n * A file this does not recognise, or cannot edit safely, is left byte for\n * byte as it was — pg_restore then reads it as it is — and the result says\n * why. `blank` is the edit made to each table's definition: the pull always\n * uses the default, {@link blankAttverOptions}; it is a parameter so that the\n * guard against an edit that changes a definition's length can be tested.\n */\nexport function stripAttverFromArchive(\n dumpFile: string,\n blank: (definition: Buffer) => Buffer = blankAttverOptions\n): AttverStrip {\n const fd = fs.openSync(dumpFile, \"r+\");\n try {\n let plan: Plan;\n try {\n plan = planPatches(fd, fs.fstatSync(fd).size, blank);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n plan = { ok: false, reason: NOT_AN_ARCHIVE, serverVersion: null, dumpVersion: null };\n }\n const versions = { serverVersion: plan.serverVersion, dumpVersion: plan.dumpVersion };\n if (!plan.ok) return { entries: 0, skipped: plan.reason, ...versions };\n for (const patch of plan.patches) fs.writeSync(fd, patch.bytes, 0, patch.bytes.length, patch.at);\n return { entries: plan.patches.length, skipped: null, ...versions };\n } finally {\n fs.closeSync(fd);\n }\n}\n","/**\n * `rebase db pull` — copy a database's contents into local development.\n *\n * The common case is production into local, and the reason it exists is that\n * the alternative is worse: without it people hand-roll a `pg_dump | psql` and\n * get the flags wrong in ways that either fail loudly at 2am or, more often,\n * quietly restore half a schema.\n *\n * Three things this command insists on, because copying a production database\n * onto a laptop is a data-protection event whether or not anyone calls it one:\n *\n * 1. **It says what it is about to do, in full, before doing it** — which\n * database it will read, which one it will overwrite, and where the data will\n * come to rest on disk. The target path matters: people forget that\n * `.rebase/pgdata` is a directory their backup software may be indexing.\n *\n * 2. **It refuses to run unattended without being told to.** The target is\n * destroyed, so a mistyped `--from` with no confirmation would take the\n * developer's working database with it.\n *\n * 3. **It will not write to a remote database.** The target is always the local\n * development database; there is no flag that makes this push. A tool that\n * can copy in both directions eventually copies in the wrong one.\n *\n * Anonymization is opt-in (`--anonymize`), which is a deliberate choice and not\n * an obviously safe one — the flag nobody types is the flag nobody gets. It is\n * a best-effort pass over columns whose *names* look like personal data, and\n * {@link ANONYMIZE_PATTERNS} says exactly which. It cannot find personal data in\n * a column called `notes`, and this file says so rather than implying a\n * guarantee it cannot keep.\n *\n * What it does guarantee is that it never half-happens: {@link anonymizeCopy}\n * runs the pass in one transaction, and when the pass fails it empties the\n * tables it would have rewritten rather than leave their real values behind.\n */\n\nimport { execa } from \"execa\";\nimport fs from \"fs\";\nimport type { Client } from \"pg\";\n\nimport { type AttverStrip, stripAttverFromArchive } from \"./attver\";\nimport { banner, connectionErrorText, hostOf } from \"./connection-banner\";\nimport { PGLITE_EXTENSIONS } from \"./constraints\";\n\n/**\n * How one kind of personal-looking column is overwritten.\n *\n * Two forms, because a constant is the most readable replacement and is wrong\n * for exactly one kind of column: a unique one. Every `token_hash` becoming\n * `'REDACTED'` is what `UNIQUE(token_hash)` refused on the second row of\n * `rebase.refresh_tokens` — so on any project where someone had signed in twice.\n */\nexport interface AnonymizeRule {\n pattern: RegExp;\n /**\n * Only on a table of people (see {@link isPeopleTable}), when set. For a\n * column name that is personal on one table and not on another: a user's\n * `name` is a person's, a tag's is not.\n */\n peopleOnly?: true;\n /** The value for a column no unique index covers, or null to always use the unique form. */\n value: string | null;\n /** The unique form is `prefix` + random hex + `suffix`, cut to fit the column. */\n prefix: string;\n suffix: string;\n}\n\n/**\n * Tables whose rows are people, by name: `rebase.users`, the blog scaffold's\n * `authors`, and the usual spellings of a project's own. Singular or plural.\n */\nconst PERSON_TABLES = /^(users?|user_profiles?|profiles?|people|persons?|members?|customers?|contacts?|employees?|authors?)$/i;\n\n/** An email address column, by name: the email rule's own pattern. */\nconst EMAIL_COLUMN = /^(.*_)?e?mail(_.*)?$/i;\n\n/** The column types a replacement string fits. */\nconst TEXTUAL_TYPES = new Set([\"text\", \"character varying\", \"varchar\", \"character\", \"char\", \"citext\"]);\n\nfunction isTextual(column: ColumnRef): boolean {\n return TEXTUAL_TYPES.has(column.dataType.toLowerCase());\n}\n\n/** `\"schema\".\"table\"`, the key a column's table is known by. */\nfunction tableKey(column: ColumnRef): string {\n return `${quoteIdentifier(column.schema)}.${quoteIdentifier(column.table)}`;\n}\n\n/**\n * The tables whose rows are people: those {@link PERSON_TABLES} names, and any\n * that holds an email address column.\n *\n * The second is what reaches the tables no list of names could: a row with an\n * address of its own is a person's, so its `name` is one too. The blog\n * scaffold's `authors` (`name`, `email`, `picture`) arrived with every name\n * as it was. A table of organisations with a contact address gets its `name`\n * redacted too, which costs a local copy little.\n */\nexport function peopleTables(columns: readonly ColumnRef[]): Set<string> {\n const people = new Set<string>();\n for (const column of columns) {\n if (PERSON_TABLES.test(column.table) || (EMAIL_COLUMN.test(column.column) && isTextual(column))) {\n people.add(tableKey(column));\n }\n }\n return people;\n}\n\n/**\n * Column-name patterns the anonymizer overwrites.\n *\n * Names, not contents: inspecting values would be slower, and would still miss\n * the same things. This is a reasonable-effort measure for making a local copy\n * less dangerous, and it is not a compliance control.\n */\nexport const ANONYMIZE_PATTERNS: readonly AnonymizeRule[] = [\n // Emails are unique in practice even where nothing enforces it, so they\n // always get a value of their own.\n { pattern: EMAIL_COLUMN, value: null, prefix: \"user-\", suffix: \"@example.invalid\" },\n { pattern: /^(.*_)?(phone|mobile|tel|telephone)(_.*)?$/i, value: \"+10000000000\", prefix: \"+1-\", suffix: \"\" },\n // `display_name` is how `rebase.users` holds every user's name.\n {\n pattern: /^(.*_)?(display_name|first_name|last_name|full_name|middle_name|family_name|surname|given_name)(_.*)?$/i,\n value: \"Redacted\",\n prefix: \"Redacted-\",\n suffix: \"\"\n },\n // A bare `name` is a person's only on a table of people.\n { pattern: /^name$/i, peopleOnly: true, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(address|street|postcode|zip|zipcode)(_.*)?$/i, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(ssn|tax_id|national_id|passport)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(password|password_hash|secret|token|api_key|access_token|refresh_token)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(ip|ip_address|user_agent)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" }\n];\n\n/** The rule that overwrites this column, if any. A people-only rule applies only on a table of people. */\nfunction ruleFor(columnName: string, onPeopleTable: boolean): AnonymizeRule | undefined {\n return ANONYMIZE_PATTERNS.find((rule) => rule.pattern.test(columnName) && (!rule.peopleOnly || onPeopleTable));\n}\n\n/**\n * Whether a column of this name is overwritten. A table is judged a table of\n * people by its name here; {@link anonymizableColumns}, which sees the\n * table's other columns, also counts one that holds an email address.\n */\nexport function shouldAnonymize(columnName: string, table?: string): boolean {\n return ruleFor(columnName, table !== undefined && PERSON_TABLES.test(table)) !== undefined;\n}\n\n/** A text-ish column the anonymizer can overwrite without a type error. */\nexport interface ColumnRef {\n schema: string;\n table: string;\n column: string;\n dataType: string;\n /** `character_maximum_length`: null or absent for an unbounded type. */\n maxLength?: number | null;\n /** Covered by a unique index — a primary key, a UNIQUE constraint, or a unique expression index. */\n unique?: boolean;\n}\n\n/** Random hex of this length, per row. `gen_random_uuid()` is core since PostgreSQL 13. */\nfunction randomHex(length: number): string {\n return `left(replace(gen_random_uuid()::text, '-', ''), ${length})`;\n}\n\nfunction sqlLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Fewest random hex digits a unique replacement keeps. Twelve is 16^12 values:\n * a collision needs millions of rows, where eight would need tens of thousands.\n */\nconst MIN_UNIQUE_HEX = 12;\n\n/**\n * The SQL expression that overwrites one column, or null when no rule names it.\n *\n * Unique per row when an index makes the column unique, and always cut to the\n * column's declared length — `zip char(5)` refused `'Redacted'` outright, and a\n * failed statement now empties the tables rather than skip one. To fit a short\n * unique column the prefix goes first, then the suffix, and the random part is\n * kept to at least {@link MIN_UNIQUE_HEX} digits while there is room for them.\n * A NULL stays NULL: an empty optional field is not personal data.\n */\nexport function replacementFor(column: ColumnRef, onPeopleTable = PERSON_TABLES.test(column.table)): string | null {\n const rule = ruleFor(column.column, onPeopleTable);\n if (!rule) return null;\n const limit = typeof column.maxLength === \"number\" && column.maxLength > 0 ? column.maxLength : null;\n\n let value: string;\n if (rule.value !== null && !column.unique) {\n value = sqlLiteral(limit === null ? rule.value : rule.value.slice(0, limit));\n } else {\n const shapes = [[rule.prefix, rule.suffix], [\"\", rule.suffix], [\"\", \"\"]];\n const fitting = shapes.find(([prefix, suffix]) =>\n limit === null || limit - prefix.length - suffix.length >= MIN_UNIQUE_HEX);\n const [prefix, suffix] = fitting ?? [\"\", \"\"];\n const hex = Math.min(32, limit === null ? 32 : limit - prefix.length - suffix.length);\n value = `concat(${sqlLiteral(prefix)}, ${randomHex(Math.max(1, hex))}, ${sqlLiteral(suffix)})`;\n }\n\n const name = quoteIdentifier(column.column);\n return `CASE WHEN ${name} IS NULL THEN NULL ELSE ${value} END`;\n}\n\n/** A double-quoted identifier, with any `\"` in it doubled — a table called `order` or `a\"b` still works. */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Anonymizable columns: name looks personal, and the type can hold the\n * replacement.\n *\n * The type check is what stops this generating `UPDATE … SET user_id =\n * 'Redacted'` for an integer column called `user_id_email_seq` and failing the\n * whole pass on a technicality.\n */\nexport function anonymizableColumns(columns: readonly ColumnRef[]): ColumnRef[] {\n const people = peopleTables(columns);\n\n return columns.filter((column) =>\n isTextual(column) && ruleFor(column.column, people.has(tableKey(column))) !== undefined);\n}\n\n/** `\"schema\".\"table\"` for each table the pass rewrites, sorted. */\nexport function anonymizedTables(columns: readonly ColumnRef[]): string[] {\n return [...new Set(anonymizableColumns(columns).map(tableKey))].sort();\n}\n\n/** `UPDATE` statements for one anonymization pass, in a stable order. */\nexport function anonymizeStatements(columns: readonly ColumnRef[]): string[] {\n const people = peopleTables(columns);\n const byTable = new Map<string, ColumnRef[]>();\n for (const column of anonymizableColumns(columns)) {\n const key = tableKey(column);\n byTable.set(key, [...(byTable.get(key) ?? []), column]);\n }\n\n return [...byTable.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([table, cols]) => {\n const assignments = [...cols]\n .sort((a, b) => a.column.localeCompare(b.column))\n .map((column) => `${quoteIdentifier(column.column)} = ${replacementFor(column, people.has(table))}`)\n .join(\", \");\n\n return `UPDATE ${table} SET ${assignments};`;\n });\n}\n\n/**\n * Every column the pass could overwrite, with what decides how.\n *\n * Base tables only — a view has an `email` column too, and is not something to\n * UPDATE. Generated columns are skipped for the same reason: `email_domain\n * GENERATED ALWAYS AS (…)` matches by name and refuses any value but DEFAULT,\n * and it follows the column it is generated from anyway. An extension type such\n * as `citext` reports `USER-DEFINED`, so its own name is what is compared.\n *\n * `unique` comes from the indexes, through `pg_depend` as well as `indkey`: a\n * unique index on `lower(email)` names no column in `indkey`, and is exactly\n * what a constant replacement would violate.\n */\nexport const ANONYMIZE_COLUMNS_SQL = `\nWITH unique_columns AS (\n SELECT DISTINCT i.indrelid AS relid, a.attname AS column_name\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum > 0 AND NOT a.attisdropped\n WHERE i.indisunique\n AND (a.attnum = ANY (i.indkey)\n OR EXISTS (SELECT 1 FROM pg_depend d\n WHERE d.classid = 'pg_class'::regclass AND d.objid = i.indexrelid\n AND d.refclassid = 'pg_class'::regclass AND d.refobjid = i.indrelid\n AND d.refobjsubid = a.attnum))\n)\nSELECT c.table_schema AS \"schema\",\n c.table_name AS \"table\",\n c.column_name AS \"column\",\n CASE WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name ELSE c.data_type END AS \"dataType\",\n c.character_maximum_length AS \"maxLength\",\n (u.column_name IS NOT NULL) AS \"unique\"\n FROM information_schema.columns c\n JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name\n LEFT JOIN unique_columns u\n ON u.relid = format('%I.%I', c.table_schema, c.table_name)::regclass AND u.column_name = c.column_name\n WHERE t.table_type = 'BASE TABLE'\n AND c.is_generated = 'NEVER'\n AND c.table_schema NOT IN ('pg_catalog', 'information_schema')`;\n\n/** How {@link anonymizeCopy} ended. */\nexport type AnonymizeOutcome =\n | { ok: true; tables: string[] }\n | {\n ok: false;\n /** Why the pass failed. Nothing it wrote was kept. */\n error: string;\n /** The tables emptied instead, so none of their real values are left. */\n emptied: string[];\n /** Why they could not be emptied, when they could not: the copy then holds real data. */\n emptyError: string | null;\n };\n\nfunction errorText(error: unknown): string {\n return error instanceof Error && error.message ? error.message : String(error);\n}\n\n/**\n * Overwrite the personal-looking columns of a restored copy, all or nothing.\n *\n * One transaction, so a failure part-way leaves no table half done — the old\n * pass ran its UPDATEs one by one, so a failure on `rebase.refresh_tokens` left\n * `public.authors` anonymized and `rebase.users` holding every real email.\n *\n * A rollback alone would be worse than that, though: it puts back the real\n * value of every column, in a copy the developer asked to be anonymized. So on\n * failure the tables the pass would have rewritten are emptied (`TRUNCATE …\n * CASCADE`, which takes the rows that reference them too), and the outcome\n * says which — or, if even that failed, says the copy holds real data, so the\n * caller can say it louder.\n *\n * `row_security = off` makes a role that RLS would filter fail the pass instead\n * of rewriting only the rows its policies show it, which looked like success.\n */\nexport async function anonymizeCopy(client: Client): Promise<AnonymizeOutcome> {\n let listed = false;\n let tables: string[] = [];\n try {\n const { rows } = await client.query<ColumnRef>(ANONYMIZE_COLUMNS_SQL);\n tables = anonymizedTables(rows);\n listed = true;\n await client.query(\"BEGIN\");\n await client.query(\"SET LOCAL row_security = off\");\n for (const statement of anonymizeStatements(rows)) await client.query(statement);\n await client.query(\"COMMIT\");\n\n return { ok: true, tables };\n } catch (error) {\n const reason = errorText(error);\n await client.query(\"ROLLBACK\").catch(() => undefined);\n if (!listed) {\n return { ok: false, error: reason, emptied: [], emptyError: \"the tables to empty could not be listed\" };\n }\n if (tables.length === 0) return { ok: false, error: reason, emptied: [], emptyError: null };\n try {\n await client.query(`TRUNCATE TABLE ${tables.join(\", \")} CASCADE`);\n\n return { ok: false, error: reason, emptied: tables, emptyError: null };\n } catch (emptyError) {\n return { ok: false, error: reason, emptied: [], emptyError: errorText(emptyError) };\n }\n }\n}\n\n/**\n * Schemas the restored copy needs the app role provisioned on.\n *\n * `pg_dump --no-privileges` strips every GRANT, so a pulled database arrives\n * with its RLS policies and its `FORCE ROW LEVEL SECURITY` intact and no\n * privileges behind them. Measured on a 30-table project: 68 policies restored,\n * 14 tables with RLS on, and **0** grants to `rebase_user` — where the source\n * had 60. Reading one table as the role Rebase serves every request through:\n *\n * source: 6\n * copy: ERROR: permission denied for table leads\n *\n * The dump flags are right and stay: without `--no-owner`/`--no-privileges`\n * every `ALTER … OWNER TO` and `GRANT … TO <prod role>` in the dump fails\n * against roles that do not exist on a laptop, and buries the real output. The\n * repair belongs after the restore, and belongs to `ensureAppRole` — the same\n * routine boot and `rebase db push` call — rather than to a second list of\n * grants written here.\n *\n * Which schemas: every non-system schema the restored database actually has.\n * Boot knows its `managedSchemas` from the collections; a restore knows only\n * what arrived, and a source may carry schemas this project does not declare.\n * `pg_catalog`, `information_schema` and the `pg_*` internals are never ours to\n * grant on and PostgreSQL would refuse anyway.\n */\nexport function provisionableSchemas(rows: readonly { schema: string }[]): string[] {\n const skip = (name: string) => name === \"information_schema\" || name.startsWith(\"pg_\");\n\n return [...new Set(rows.map((row) => row.schema))].filter((name) => !skip(name)).sort();\n}\n\n/**\n * libpq's `keyword=value` form (`host=db.example.com port=5432 dbname=app`):\n * one or more pairs, a value bare or single-quoted with `\\'` and `\\\\` escapes.\n */\nconst KEYWORD_VALUE_DSN = /^\\s*[a-z_]+\\s*=\\s*(?:'(?:[^'\\\\]|\\\\.)*'|[^\\s']+)(?:\\s+[a-z_]+\\s*=\\s*(?:'(?:[^'\\\\]|\\\\.)*'|[^\\s']+))*\\s*$/i;\n\n/** One keyword's value in a `keyword=value` connection string, unquoted. */\nfunction keywordValue(dsn: string, keyword: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${keyword}\\\\s*=\\\\s*('(?:[^'\\\\\\\\]|\\\\\\\\.)*'|[^\\\\s']+)`, \"i\").exec(dsn);\n if (!match) return null;\n const value = match[1];\n return value.startsWith(\"'\") ? value.slice(1, -1).replace(/\\\\(.)/g, \"$1\") : value;\n}\n\n/**\n * Why a `--from` value is not a connection string pg_dump reads, or null\n * when it is one: a `postgres://` or `postgresql://` URL, or libpq's\n * `keyword=value` pairs.\n *\n * Asked before anything else, because the answer is known from the string:\n * `--from garbage --yes` printed \"This will replace your local database.\n * From (unparseable connection string)\" and started dumping before pg_dump\n * refused it. The value is never quoted back: it may carry a password in a\n * shape no redaction recognises.\n */\nexport function sourceProblem(source: string): string | null {\n const scheme = /^([a-z][a-z0-9+.-]*):\\/\\//i.exec(source)?.[1]?.toLowerCase();\n if (scheme !== undefined) {\n if (scheme !== \"postgres\" && scheme !== \"postgresql\") {\n return `it is a ${scheme}:// URL, and a pull copies from PostgreSQL (postgres:// or postgresql://)`;\n }\n try {\n new URL(source);\n return null;\n } catch {\n return \"it starts like a postgres:// URL but is not a valid one\";\n }\n }\n if (KEYWORD_VALUE_DSN.test(source)) return null;\n return \"it is neither a postgres:// URL nor libpq keyword=value pairs\";\n}\n\n/** Host and database of a connection string, with no credentials in it. */\nexport function describeTarget(connectionString: string): string {\n try {\n const url = new URL(connectionString);\n const database = url.pathname.replace(/^\\//, \"\") || \"(default)\";\n\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}/${database}`;\n } catch {\n if (KEYWORD_VALUE_DSN.test(connectionString)) {\n const host = keywordValue(connectionString, \"host\") ?? keywordValue(connectionString, \"hostaddr\") ?? \"(local socket)\";\n const port = keywordValue(connectionString, \"port\");\n return `${host}${port ? `:${port}` : \"\"}/${keywordValue(connectionString, \"dbname\") ?? \"(default)\"}`;\n }\n // Never echo the raw string: it carries a password, and this line is\n // printed to a terminal people paste into issues.\n return \"(unparseable connection string)\";\n }\n}\n\n/**\n * What the local database runs on.\n *\n * `pglite` is the managed development database: one PGlite session behind a\n * socket server. Two things a restore relies on are not there. The server runs\n * each protocol message on its own, so the `CopyData` that follows a `COPY …\n * FROM stdin` never reaches the backend waiting for it: the COPY fails on\n * \"unexpected EOF\", and the session stops answering anyone until the daemon\n * is killed. And every connection shares that one session, so what pg_restore\n * `SET`s for itself stays set for everyone after it disconnects.\n */\nexport type PullTargetEngine = \"postgres\" | \"pglite\";\n\nexport interface PullPlan {\n /** Where the data comes from. */\n source: string;\n /** Where it lands. Always local. */\n target: string;\n anonymize: boolean;\n /** Schemas to copy. Empty means every non-system schema. */\n schemas: string[];\n /**\n * What the target runs on, which decides how the dump carries its rows.\n * Absent means `postgres`. {@link dumpSource} reads it off the target.\n */\n targetEngine?: PullTargetEngine;\n}\n\n/**\n * Rows per `INSERT` in a dump for the managed database.\n *\n * One per statement restored 100k rows in 8s; a hundred took 0.8s. A hundred\n * 512KB rows, a 100MB statement, still went in.\n */\nconst ROWS_PER_INSERT = 100;\n\n/**\n * `pg_dump` arguments for the source.\n *\n * `--no-owner` and `--no-acl` because the roles on a production server do not\n * exist locally, and without them every `ALTER … OWNER TO` in the dump fails and\n * buries the real output in noise. `--format=custom` so `pg_restore` can be told\n * to continue past errors selectively rather than all-or-nothing.\n *\n * For the managed database the rows travel as `INSERT`s, which PGlite takes\n * like any other statement, instead of `COPY` data, which it cannot take at\n * all — see {@link PullTargetEngine}. The copy is the same; only how the rows\n * are written in the dump differs.\n */\nexport function dumpArgs(plan: PullPlan): string[] {\n const args = [\"--format=custom\", \"--no-owner\", \"--no-acl\", \"--no-privileges\"];\n if (plan.targetEngine === \"pglite\") args.push(`--rows-per-insert=${ROWS_PER_INSERT}`);\n for (const schema of plan.schemas) args.push(\"--schema\", schema);\n args.push(\"--dbname\", splitPassword(plan.source).connectionString);\n\n return args;\n}\n\n/** The environment `pg_dump` runs with: the source's password, if it has one. */\nexport function dumpEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.source);\n}\n\n/** The environment `pg_restore` runs with: the target's password, if it has one. */\nexport function restoreEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.target);\n}\n\nfunction passwordEnv(connectionString: string): Record<string, string> {\n const { password } = splitPassword(connectionString);\n return password === null ? {} : { PGPASSWORD: password };\n}\n\n/**\n * A libpq connection string without its password, and the password.\n *\n * The password goes in `PGPASSWORD`, never on a command line, where every\n * process listing can read it and every failure prints it back (execa's error\n * repeats the command). The same rule `db backup` follows; this mirrors\n * `splitPassword` in `@rebasepro/server-postgres`'s connection-string utils,\n * which is not exported. Covers the user-info password and a `password=`\n * parameter; anything that does not parse as a postgres URL is left alone.\n */\nfunction splitPassword(connectionString: string): { connectionString: string; password: string | null } {\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n return { connectionString, password: null };\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return { connectionString, password: null };\n\n const fromUserInfo = url.password ? decodePercent(url.password) : null;\n const fromParameter = url.searchParams.get(\"password\");\n if (fromUserInfo === null && fromParameter === null) return { connectionString, password: null };\n\n url.password = \"\";\n if (fromParameter !== null) {\n url.searchParams.delete(\"password\");\n // By hand: URLSearchParams writes a space as `+`, which libpq reads literally.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n }\n return { connectionString: url.toString(), password: fromUserInfo ?? fromParameter };\n}\n\nfunction decodePercent(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * `pg_restore` arguments for the target.\n *\n * It restores into schemas {@link restoreCopy} has already emptied, so\n * `--clean --if-exists` drops nothing that is there; it stays for whatever a\n * dump holds outside them — an extension, say — which would otherwise fail as\n * already existing. `--no-owner` for the same reason as the dump.\n */\nexport function restoreArgs(plan: PullPlan, dumpFile: string): string[] {\n return [\"--clean\", \"--if-exists\", \"--no-owner\", \"--no-privileges\", \"--dbname\", splitPassword(plan.target).connectionString, dumpFile];\n}\n\n/**\n * Is this PostgreSQL client tool on PATH, and what version? Both are checked\n * before anything destructive: discovering `pg_restore` is missing after the\n * dump has been taken — or after `--clean` has emptied the target — is the\n * worst possible ordering.\n */\nexport async function findPgTool(tool: \"pg_dump\" | \"pg_restore\"): Promise<string | null> {\n try {\n const { stdout } = await execa(tool, [\"--version\"]);\n\n return stdout.trim();\n } catch {\n return null;\n }\n}\n\n/** PGlite names itself in `version()`: `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`. */\nfunction engineOf(version: string): PullTargetEngine {\n return /\\bPGlite\\b/i.test(version) ? \"pglite\" : \"postgres\";\n}\n\nconst NOTHING_CHANGED = \"Nothing was changed: the local database is as it was.\";\n\n/** What the target database runs on, or why it could not be asked. */\nasync function readTargetEngine(target: string): Promise<{ engine: PullTargetEngine } | { error: unknown }> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: target, connectionTimeoutMillis: 10_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n const { rows } = await client.query<{ version: string }>(\"SELECT version() AS version\");\n\n return { engine: engineOf(rows[0]?.version ?? \"\") };\n } catch (error) {\n return { error };\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/** How {@link dumpSource} ended. */\nexport type DumpOutcome =\n | {\n ok: true;\n /** The plan the dump was taken for, with its target's engine read: what {@link restoreCopy} takes. */\n plan: PullPlan;\n }\n | {\n ok: false;\n /** What failed and what to do, as plain lines for the caller to print. Nothing was changed. */\n lines: string[];\n };\n\n/**\n * `pg_dump` the source into `dumpFile`, in the form the target can restore.\n *\n * It asks the target what it runs on first — the managed database cannot take\n * `COPY` data, see {@link PullTargetEngine} — which also finds a local\n * database that is not there before anything is read from the source.\n *\n * pg_dump's stderr is kept rather than shown as it arrives, so a failure is\n * reported once, in the reader's terms: an unreachable source, or credentials\n * it refused, get the banner every database command prints for a connection\n * that failed, and anything else is pg_dump's own words with a line saying\n * nothing was changed. A dump that succeeds with warnings still shows them.\n * A dump that fails leaves no file behind.\n */\nexport async function dumpSource(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n try {\n const outcome = await dumpInto(plan, dumpFile);\n if (!outcome.ok) fs.rmSync(dumpFile, { force: true });\n\n return outcome;\n } catch (error) {\n fs.rmSync(dumpFile, { force: true });\n throw error;\n }\n}\n\nasync function dumpInto(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n let targetEngine = plan.targetEngine;\n if (!targetEngine) {\n const read = await readTargetEngine(plan.target);\n if (\"error\" in read) {\n return {\n ok: false,\n lines: banner(`Cannot connect to PostgreSQL at ${hostOf(plan.target)}`,\n `The driver said: ${connectionErrorText(read.error)}`, [\n \"That is the local database the pull would replace, and nothing\",\n \"was read from the source.\",\n \"Start it — `rebase dev` starts the managed one, `rebase dev --docker`\",\n \"Postgres in Docker — or check DATABASE_URL in .env, then pull again.\"\n ])\n };\n }\n targetEngine = read.engine;\n }\n\n const planned: PullPlan = { ...plan, targetEngine };\n const run = await execa(\"pg_dump\", [...dumpArgs(planned), \"--file\", dumpFile], {\n env: dumpEnv(planned),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"pipe\",\n reject: false\n });\n if (run.exitCode === 0) {\n if (run.stderr.trim()) process.stderr.write(`${run.stderr.trimEnd()}\\n`);\n\n return { ok: true, plan: planned };\n }\n\n return { ok: false, lines: describeDumpFailure(plan.source, run) };\n}\n\n/**\n * Why `pg_dump` could not read the source, as plain lines for the caller to\n * print. The dump is taken before anything local is touched, so every one of\n * them ends the same way: nothing was changed.\n */\nexport function describeDumpFailure(source: string, run: RestoreRun): string[] {\n if (run.signal) return [`✗ pg_dump was stopped by ${run.signal} before it finished.`, NOTHING_CHANGED];\n if (run.exitCode === undefined) {\n return [\n `✗ pg_dump could not be started (${run.code ?? \"unknown error\"}).`,\n NOTHING_CHANGED,\n \"Check that the PostgreSQL client tools are installed (`pg_dump --version`).\"\n ];\n }\n\n const stderr = (run.stderr ?? \"\").trim();\n const host = hostOf(source);\n const error = /pg_dump: error: (.+)/.exec(stderr)?.[1]?.trim() ?? null;\n const said = error ? `pg_dump said: ${error}` : null;\n\n if (/could not translate host name|could not connect to server|connection to server .* failed: (?:Connection refused|timeout expired|No route to host|Network is unreachable|Operation timed out|Host is down)/i.test(stderr)) {\n return banner(`Cannot connect to PostgreSQL at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the host and port in --from, and that this machine can reach\",\n \"that server: a VPN, an allow-list, or an SSH tunnel.\"\n ]);\n }\n if (/password authentication failed|no pg_hba\\.conf entry|role \"[^\"]+\" does not exist/i.test(stderr)) {\n let user = \"unknown\";\n try {\n user = decodePercent(new URL(source).username) || \"unknown\";\n } catch { /* named as unknown */ }\n return banner(`Authentication failed for user \"${user}\" at ${host}`, said, [\n \"PostgreSQL rejected the credentials --from carries.\",\n NOTHING_CHANGED,\n \"Check the user and password in --from.\"\n ]);\n }\n // The server answered and has no database of that name: a typo in\n // --from, usually, or a database not created yet.\n const missing = /database \"([^\"]+)\" does not exist/i.exec(stderr)?.[1];\n if (missing) {\n return banner(`Database \"${missing}\" does not exist at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the database name in --from.\"\n ]);\n }\n\n const versions = /server version mismatch/i.test(stderr)\n ? [\"pg_dump is older than the server: install client tools at least as new as it (`brew install libpq`).\"]\n : [];\n return [\n ...(stderr ? stderr.split(\"\\n\") : []),\n `✗ pg_dump could not dump ${describeTarget(source)} (exit code ${run.exitCode}).`,\n NOTHING_CHANGED,\n ...versions\n ];\n}\n\n/** The fields of a finished `pg_restore` (or `pg_dump`) run that decide {@link restoreOutcome}. */\nexport interface RestoreRun {\n exitCode?: number;\n signal?: string;\n /** A spawn failure's code — `ENOENT` when the binary vanished. */\n code?: string;\n stderr?: string;\n}\n\n/** What a `pg_restore` run says about the copy. */\nexport interface RestoreRunOutcome {\n /** Whether anything can have arrived — what decides whether an anonymization pass has data to redact. */\n started: boolean;\n /** Null when the copy is complete. */\n failure: string | null;\n /**\n * What to do about the failure. \"Pull again\" only where a second pull is\n * what finishes the job: everything else repeats until its cause is fixed.\n */\n advice: string | null;\n}\n\n/**\n * What a finished `pg_restore` says about the copy.\n *\n * The target was emptied before anything was written, so every way this can\n * end short of exit 0 leaves a partial or empty local database, and none of\n * them may be reported as a copy. A non-zero exit is pg_restore saying it\n * skipped statements — \"errors ignored on restore: N\" — and whatever those\n * statements created (a table, its rows, an RLS policy) is missing locally.\n *\n * Restoring into an emptied database, those errors come from what the source\n * holds that this Postgres cannot create — an extension it does not have, a\n * feature of a newer server — and a second pull meets them again. So the\n * advice names that, rather than \"pull again\", which sent people in a loop.\n * On the managed database an extension cannot be installed at all, so the\n * advice there is Postgres in Docker.\n *\n * One cause is named for what it is: a target refusing `pg_attver`, which\n * means the local pg_dump is older than the source server and the dump could\n * not be edited to drop the key (`attver`, what {@link stripAttverFromArchive}\n * said, tells why).\n */\nexport function restoreOutcome(\n run: RestoreRun,\n engine: PullTargetEngine = \"postgres\",\n attver: AttverStrip | null = null\n): RestoreRunOutcome {\n if (run.signal) {\n return {\n started: true,\n failure: `pg_restore was stopped by ${run.signal} before it finished.`,\n advice: \"It was interrupted, not refused: pull again to finish the copy.\"\n };\n }\n if (run.exitCode === undefined) {\n return {\n started: false,\n failure: `pg_restore could not be started (${run.code ?? \"unknown error\"}).`,\n advice: \"Check that the PostgreSQL client tools are installed (`pg_restore --version`), then pull again.\"\n };\n }\n if (run.exitCode === 0) return { started: true, failure: null, advice: null };\n\n const ignored = /errors ignored on restore: (\\d+)/.exec(run.stderr ?? \"\");\n const refusedAttver = (run.stderr ?? \"\").includes(\"unrecognized parameter \\\"pg_attver\\\"\");\n const repeats = refusedAttver\n ? attverAdvice(attver)\n : engine === \"pglite\"\n ? \"Pulling again repeats these errors until what they name is fixed — most often an extension the \"\n + `source uses that the managed database does not have (it has ${PGLITE_EXTENSIONS.map(extension => extension.name).join(\", \")}). `\n + \"Pull into Postgres in Docker instead (`rebase db pull --docker`), or pull only the schemas that do \"\n + \"not need it (--schema).\"\n : \"Pulling again repeats these errors until what they name is fixed — most often an extension \"\n + \"the source uses that this Postgres does not have installed. Install it here, or pull only the schemas \"\n + \"that do not need it (--schema).\";\n\n return {\n started: true,\n failure: ignored\n ? `pg_restore could not restore ${ignored[1]} object(s) — the errors are above.`\n : `pg_restore exited with code ${run.exitCode} — the errors are above.`,\n advice: repeats\n };\n}\n\n/**\n * What to do when the target refused the dump's `pg_attver` options: they are\n * there because the local pg_dump is older than the server it dumped from,\n * and a pg_dump at least as new leaves them out.\n */\nfunction attverAdvice(attver: AttverStrip | null): string {\n const older = attver?.dumpVersion && attver.serverVersion\n ? `Your pg_dump (${attver.dumpVersion}) is older than the server it dumped from (${attver.serverVersion})`\n : \"Your pg_dump is older than the server it dumped from\";\n const skipped = attver?.skipped ? `, and Rebase could not take them out of this dump: ${attver.skipped}` : \"\";\n const atLeast = attver?.serverVersion ? `at least ${attver.serverVersion}` : \"at least the server's minor version\";\n\n return `${older}: it wrote pg_attver column options, which this database refuses${skipped}. `\n + `Upgrade the PostgreSQL client tools to ${atLeast} (check with \\`pg_dump --version\\`), then pull again.`;\n}\n\n/**\n * The line a pull prints when it took `pg_attver` out of the dump: the copy is\n * whole, but the local pg_dump is older than the source server, which is what\n * to fix. Null when nothing was taken out.\n */\nexport function attverNotice(attver: AttverStrip): string | null {\n if (attver.entries === 0) return null;\n const older = attver.dumpVersion && attver.serverVersion\n ? `Your pg_dump (${attver.dumpVersion}) is older than the server it dumped from (${attver.serverVersion})`\n : \"Your pg_dump is older than the server it dumped from\";\n const atLeast = attver.serverVersion ? `at least ${attver.serverVersion}` : \"at least the server's minor version\";\n\n return `${older}: its dump carried pg_attver column options this database would refuse, so they were taken `\n + `out of ${attver.entries} table(s) before restoring. Upgrading the PostgreSQL client tools to ${atLeast} is the supported fix.`;\n}\n\n/** How {@link restoreCopy} ended. */\nexport interface RestoreOutcome extends RestoreRunOutcome {\n /** Whether the local database was emptied first. False means it is exactly as it was. */\n cleared: boolean;\n /** Something the copy did that is worth one line, whether or not it succeeded — see {@link attverNotice}. */\n notice?: string;\n}\n\n/**\n * The local schemas a pull empties before it restores: every one of the local\n * database's own for a whole-database pull, and those it copies for a\n * `--schema` pull. `pg_catalog`, `information_schema` and the `pg_*` internals\n * never — see {@link provisionableSchemas}.\n */\nexport function schemasToClear(present: readonly { schema: string }[], planned: readonly string[]): string[] {\n const local = provisionableSchemas(present);\n\n return planned.length === 0 ? local : local.filter((schema) => planned.includes(schema));\n}\n\n/**\n * The statements that empty those schemas, in one transaction.\n *\n * `CASCADE`, which `pg_restore --clean` never uses: a table the source lacks —\n * `rebase.atlas_schema_revisions` from `rebase db migrate`, a collection added\n * locally that references a pulled table — is exactly what blocked its plain\n * `DROP SCHEMA` and `DROP TABLE`. `public` is put back empty, with the access\n * every role has to it by default, because a dump does not create a default\n * `public` and every table in it would otherwise have nowhere to go.\n */\nexport function clearStatements(schemas: readonly string[]): string[] {\n const statements = schemas.map((schema) => `DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`);\n if (schemas.includes(\"public\")) statements.push(\"CREATE SCHEMA public\", \"GRANT USAGE ON SCHEMA public TO PUBLIC\");\n\n return statements;\n}\n\n/**\n * How long emptying the local database waits for a lock before giving up.\n *\n * A `rebase dev` serving from the database holds connections, and one inside\n * a transaction would otherwise make the pull hang without a word.\n */\nconst CLEAR_LOCK_TIMEOUT = \"15s\";\n\n/** Why emptying the local database failed, in the reader's terms, and what fixes it. */\nfunction clearFailure(error: unknown): RestoreOutcome {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"\";\n const reason = errorText(error);\n const advice = code === \"55P03\"\n ? \"Something holds a lock on it — usually `rebase dev` serving from it. Stop that, then pull again.\"\n : code === \"42501\"\n ? \"This connection may not drop those schemas. Connect as the role that owns them — the one \"\n + \"that created them — and pull with that.\"\n : \"Fix what the error names; pulling again before that repeats it.\";\n\n return {\n cleared: false,\n started: false,\n failure: `Could not empty the local database before restoring: ${reason}`,\n advice\n };\n}\n\n/**\n * Replace the local database's contents with a dump: empty the schemas it\n * holds, then `pg_restore` into them.\n *\n * Only ever `plan.target`, the local development database the command\n * resolved — the pull's one destination, which no flag can change. Emptying it\n * is one transaction: if any schema cannot be dropped, none is, nothing is\n * restored, and the database is as it was.\n *\n * On the managed database the dump must be one {@link dumpSource} took for it,\n * with its rows as INSERTs: a COPY would leave the daemon answering nobody, so\n * one is refused before anything is emptied. And afterwards its one session —\n * every connection's — is given back its own settings: pg_restore leaves\n * `search_path` empty and `row_security` off behind it, which a running\n * `rebase dev` would otherwise query under.\n */\nexport async function restoreCopy(plan: PullPlan, dumpFile: string): Promise<RestoreOutcome> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: plan.target });\n client.on(\"error\", () => undefined);\n let engine: PullTargetEngine;\n try {\n await client.connect();\n engine = engineOf((await client.query<{ version: string }>(\"SELECT version() AS version\")).rows[0]?.version ?? \"\");\n if (engine === \"pglite\" && plan.targetEngine !== \"pglite\") {\n return {\n cleared: false,\n started: false,\n failure: \"The managed development database cannot take this dump: its rows are COPY data, which PGlite's socket server cannot receive.\",\n advice: \"Pull into Postgres in Docker instead: `rebase db pull --docker`.\"\n };\n }\n const { rows } = await client.query<{ schema: string }>(\"SELECT nspname AS \\\"schema\\\" FROM pg_namespace\");\n await client.query(\"BEGIN\");\n await client.query(`SET LOCAL lock_timeout = '${CLEAR_LOCK_TIMEOUT}'`);\n for (const statement of clearStatements(schemasToClear(rows, plan.schemas))) await client.query(statement);\n await client.query(\"COMMIT\");\n } catch (error) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n return clearFailure(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n\n // A pg_dump older than the source server's minor writes its `pg_attver`\n // attribute options, which the target may refuse — see attver.ts. A dump\n // it could not edit is restored as it is; if the target then refuses the\n // key, the advice says why (`restoreOutcome`).\n const attver = stripAttverFromArchive(dumpFile);\n\n // stderr is shown as it arrives and kept, for the count in its summary\n // line. Not rejected: every way this ends is judged by `restoreOutcome`.\n const run = await execa(\"pg_restore\", restoreArgs(plan, dumpFile), {\n env: restoreEnv(plan),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: [\"pipe\", \"inherit\"],\n reject: false\n });\n\n if (engine === \"pglite\") await resetSharedSession(plan.target);\n\n const notice = attverNotice(attver);\n\n return { cleared: true, ...restoreOutcome(run, engine, attver), ...(notice ? { notice } : {}) };\n}\n\n/**\n * Put the managed database's one session back to its own settings.\n *\n * `RESET ALL` and `DEALLOCATE ALL`, not `DISCARD ALL`: the session is every\n * connection's, and `DISCARD` would also drop the `LISTEN` a running\n * `rebase dev`'s realtime holds on it. The same pair the backup service runs\n * after its tools (`resetSharedSession` in server-postgres' backup-service). Best effort: a daemon that cannot take this cannot take the\n * re-grant that follows either, and that step reports it.\n */\nasync function resetSharedSession(target: string): Promise<void> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: target, connectionTimeoutMillis: 10_000, query_timeout: 15_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n await client.query(\"RESET ALL\");\n await client.query(\"DEALLOCATE ALL\");\n } catch {\n // Reported by the next step that connects; see above.\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * The lines that report a failed restore: what failed, what state the local\n * database is in now, and what to do. Plain text, for the caller to colour.\n */\nexport function describeRestoreFailure(outcome: RestoreOutcome, source: string): string[] {\n const state = outcome.started\n ? `The local database holds an incomplete copy of ${source}.`\n : outcome.cleared\n ? \"The local database was emptied, and nothing was restored into it.\"\n : \"Nothing was restored, and the local database is as it was.\";\n\n return [outcome.failure ?? \"The restore did not complete.\", state, ...(outcome.advice ? [outcome.advice] : [])];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAM,cAAc;AACpB,IAAM,eAAe;AACrB,IAAM,eAAe;AAErB,SAAS,OAAO,MAAsB;CAClC,OAAO,IAAI,OAAO,KAAK,MAAM;AACjC;;;;;;;AAQA,SAAgB,mBAAmB,YAA4B;CAC3D,MAAM,OAAO,WAAW,SAAS,QAAQ;CACzC,IAAI,CAAC,KAAK,SAAS,YAAY,GAAG,OAAO;CAEzC,MAAM,UAAU,KACX,QAAQ,cAAc,cAAc,OAAO,SAAS,CAAC,CAAC,CACtD,QAAQ,eAAe,WAAW,OAAO,MAAM,CAAC,CAAC,CACjD,QAAQ,eAAe,WAAW,OAAO,MAAM,CAAC;CAErD,OAAO,YAAY,OAAO,aAAa,OAAO,KAAK,SAAS,QAAQ;AACxE;;;;;;AAOA,IAAM,mCAAmB,IAAI,IAAI;CAAC;CAAS;CAAiB;AAAmB,CAAC;;;;;;AAOhF,IAAM,uCAAuB,IAAI,IAAI;CACjC;CAAa;CAAU;CAAU;CAAU;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C9G,OAAO,GAAG,eAAe,KAAA,CAAS;CAClC,IAAI;EACA,MAAM,OAAO,QAAQ;EACrB,MAAM,OAAO,MAAM,WAAW;EAC9B,MAAM,OAAO,MAAM,gBAAgB;CACvC,QAAQ,CAER,UAAU;EACN,MAAM,OAAO,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;CAC5C;AACJ;;;;;AAMA,SAAgB,uBAAuB,SAAyB,QAA0B;CACtF,MAAM,QAAQ,QAAQ,UAChB,kDAAkD,OAAO,KACzD,QAAQ,UACJ,sEACA;CAEV,OAAO;EAAC,QAAQ,WAAW;EAAiC;EAAO,GAAI,QAAQ,SAAS,CAAC,QAAQ,MAAM,IAAI,CAAC;CAAE;AAClH"}
@@ -0,0 +1,2 @@
1
+ import { r as resolveDevDatabase } from "./prepare-Ccxspoj-.js";
2
+ export { resolveDevDatabase };
@@ -1,4 +1,5 @@
1
1
  import { type RebaseBackendAppConfig, type ResourceDeclaration, type ResourceGraph } from "@rebasepro/types";
2
+ import type { ModuleAliases } from "../utils/project-schema.js";
2
3
  /** The committed, generated record of what a project needs. */
3
4
  export declare const RESOURCE_GRAPH_FILENAME = "rebase.resources.json";
4
5
  /** A problem found while deriving, reported with the rest rather than thrown one at a time. */
@@ -11,8 +12,8 @@ export interface ResourceIssue {
11
12
  *
12
13
  * `main` runs 497 commits ahead of npm `latest` and the docs site publishes from
13
14
  * `main`, so the shape this exists for is routine: a scaffold pinned to the
14
- * published version, config code written against today's documentation, and an
15
- * error about the config file. The fix is one command and the error named none
15
+ * published version, backend code written against today's documentation, and an
16
+ * error about the project's file. The fix is one command and the error named none
16
17
  * of it — the same failure as `404 No PUT route on collection 'projects'`, one
17
18
  * layer down.
18
19
  *
@@ -21,15 +22,20 @@ export interface ResourceIssue {
21
22
  */
22
23
  export declare function describeIssue(err: unknown, projectRoot: string, ownVersion?: string): string;
23
24
  export interface DeriveOptions {
24
- /** Absolute path to the project's config directory. */
25
- configDir: string;
25
+ /** The project root, absolute: what the importer is rooted at and every recorded path is relative to. */
26
+ projectRoot: string;
26
27
  /**
27
- * Whether to evaluate collection files too. Resources are conventionally
28
- * declared in `resources.ts`, but nothing stops a bucket being declared
29
- * beside the collection that stores into it, and a graph that missed it
30
- * would under-report what the project needs.
28
+ * The resources module, absolute, without or with its extension:
29
+ * `<root>/backend/resources`. Its `database()` / `bucket()` / `topic()` /
30
+ * `queue()` declarations are the graph's nodes.
31
31
  */
32
- includeCollections?: boolean;
32
+ resources?: string;
33
+ /**
34
+ * The schema directory, absolute. Its tables are evaluated too: a table
35
+ * reaches its database and every bucket a storage column stores into, and a
36
+ * bucket may be declared beside the table that stores into it.
37
+ */
38
+ schemaDir?: string;
33
39
  /**
34
40
  * Absolute path to the crons directory. Each file is evaluated through the
35
41
  * same loader the runtime uses, which declares the cron under the same id
@@ -42,13 +48,13 @@ export interface DeriveOptions {
42
48
  * scope belongs to a running backend, not a build.
43
49
  */
44
50
  functionsDir?: string;
45
- /** The project root, for the paths a graph records. Defaults to the config directory's parent. */
46
- projectRoot?: string;
51
+ /** Module specifiers mapped to files when importing (in-repo runs and tests). */
52
+ moduleAliases?: ModuleAliases;
47
53
  }
48
54
  /** The derive options for a backend app, from its manifest entry. */
49
55
  export declare function deriveOptionsFor(projectRoot: string, app: RebaseBackendAppConfig): DeriveOptions;
50
56
  /**
51
- * Evaluate a project's config and return the graph it declares.
57
+ * Evaluate a project's resources and tables and return the graph they declare.
52
58
  *
53
59
  * Clears any previously registered declarations first, so deriving twice in one
54
60
  * process — a watch mode, a test — describes the project rather than the union
@@ -66,7 +72,7 @@ export declare function readResourceGraphFile(projectRoot: string): string | nul
66
72
  * Write the graph, and say whether the file changed.
67
73
  *
68
74
  * The boolean is what a `--check` mode reports on: a project whose committed
69
- * graph disagrees with its config has a host reading one thing and a runtime
75
+ * graph disagrees with its declarations has a host reading one thing and a runtime
70
76
  * doing another.
71
77
  */
72
78
  export declare function writeResourceGraphFile(projectRoot: string, graph: ResourceGraph): {