@rebasepro/cli 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/{agent-setup-DqAcoDcn.js → agent-setup-Cg_zBWoW.js} +3 -3
  2. package/dist/{agent-setup-DqAcoDcn.js.map → agent-setup-Cg_zBWoW.js.map} +1 -1
  3. package/dist/api-TbmW33D7.js +275 -0
  4. package/dist/api-TbmW33D7.js.map +1 -0
  5. package/dist/{api-keys-eIUjMqWn.js → api-keys-fPQ55DCm.js} +151 -158
  6. package/dist/api-keys-fPQ55DCm.js.map +1 -0
  7. package/dist/{apps-DExO4PEl.js → apps-DBTRoOeP.js} +18 -13
  8. package/dist/apps-DBTRoOeP.js.map +1 -0
  9. package/dist/{args-CaCcrYE1.js → args-DHyrshtI.js} +3 -132
  10. package/dist/args-DHyrshtI.js.map +1 -0
  11. package/dist/{atlas-dev-database-DOCKk6ht.js → atlas-dev-database-D6h65f2x.js} +3 -3
  12. package/dist/{atlas-dev-database-DOCKk6ht.js.map → atlas-dev-database-D6h65f2x.js.map} +1 -1
  13. package/dist/{auth-ofQETpM5.js → auth-BpyYLEFY.js} +93 -12
  14. package/dist/auth-BpyYLEFY.js.map +1 -0
  15. package/dist/auth-session-B6aT0Dyj.js +371 -0
  16. package/dist/auth-session-B6aT0Dyj.js.map +1 -0
  17. package/dist/{backend-guard-C0mVkXBw.js → backend-guard-Cf8eMK_f.js} +2 -2
  18. package/dist/{backend-guard-C0mVkXBw.js.map → backend-guard-Cf8eMK_f.js.map} +1 -1
  19. package/dist/{branch-pointer-DMPyvZoK.js → branch-pointer-BJOF2Ubv.js} +1 -1
  20. package/dist/{build-CA5R07tw.js → build-BfdT-AUR.js} +12 -10
  21. package/dist/{build-CA5R07tw.js.map → build-BfdT-AUR.js.map} +1 -1
  22. package/dist/{bundle-DgILeA5b.js → bundle-CIiKGrte.js} +78 -12
  23. package/dist/bundle-CIiKGrte.js.map +1 -0
  24. package/dist/bundle.d.ts +31 -1
  25. package/dist/{cloud-CYMk92iG.js → cloud-MqnyPnmX.js} +1540 -1531
  26. package/dist/cloud-MqnyPnmX.js.map +1 -0
  27. package/dist/{cms-directories-BK3vcswg.js → cms-directories-BaV-Is9a.js} +2 -2
  28. package/dist/{cms-directories-BK3vcswg.js.map → cms-directories-BaV-Is9a.js.map} +1 -1
  29. package/dist/codemod/collections-to-tables/backend.d.ts +0 -2
  30. package/dist/codemod/collections-to-tables/customization.d.ts +2 -1
  31. package/dist/codemod/collections-to-tables/modules.d.ts +32 -0
  32. package/dist/codemod/collections-to-tables/plan-context.d.ts +7 -1
  33. package/dist/{command-D5lhW_-B.js → command-D9g46gg9.js} +68 -42
  34. package/dist/command-D9g46gg9.js.map +1 -0
  35. package/dist/commands/api-keys.d.ts +89 -52
  36. package/dist/commands/api.d.ts +114 -0
  37. package/dist/commands/auth-session.d.ts +94 -0
  38. package/dist/commands/auth.d.ts +1 -1
  39. package/dist/commands/cloud/alerts.d.ts +29 -0
  40. package/dist/commands/cloud/context.d.ts +8 -0
  41. package/dist/commands/cloud/debug.d.ts +16 -1
  42. package/dist/commands/cloud/deploy-hooks.d.ts +19 -0
  43. package/dist/commands/cloud/deploy.d.ts +25 -0
  44. package/dist/commands/cloud/env.d.ts +1 -0
  45. package/dist/commands/cloud/index.d.ts +5 -0
  46. package/dist/commands/cloud/maintenance.d.ts +26 -1
  47. package/dist/commands/cloud/not-served.d.ts +27 -0
  48. package/dist/commands/cloud/orgs.d.ts +5 -0
  49. package/dist/commands/cloud/resources.d.ts +82 -2
  50. package/dist/commands/cloud/runtime-logs.d.ts +57 -0
  51. package/dist/commands/cloud/settings.d.ts +3 -0
  52. package/dist/commands/cron.d.ts +68 -0
  53. package/dist/commands/data.d.ts +197 -0
  54. package/dist/commands/functions.d.ts +38 -0
  55. package/dist/commands/logs.d.ts +22 -0
  56. package/dist/commands/rls.d.ts +31 -0
  57. package/dist/commands/schema-reconcile.d.ts +2 -1
  58. package/dist/commands/schema-show.d.ts +38 -0
  59. package/dist/commands/storage-objects.d.ts +88 -0
  60. package/dist/commands/storage.d.ts +18 -2
  61. package/dist/commands/users.d.ts +147 -0
  62. package/dist/{consent-BXLIrMl8.js → consent-UV6ObCME.js} +2 -2
  63. package/dist/{consent-BXLIrMl8.js.map → consent-UV6ObCME.js.map} +1 -1
  64. package/dist/{console-DjThnr3f.js → console-BVoYOLAO.js} +6 -6
  65. package/dist/{console-DjThnr3f.js.map → console-BVoYOLAO.js.map} +1 -1
  66. package/dist/{context--JwaHaZp.js → context-BOMEoKxn.js} +80 -9
  67. package/dist/{context--JwaHaZp.js.map → context-BOMEoKxn.js.map} +1 -1
  68. package/dist/cron-CpUsQ739.js +298 -0
  69. package/dist/cron-CpUsQ739.js.map +1 -0
  70. package/dist/cron-ZRXsla0v.js +259 -0
  71. package/dist/cron-ZRXsla0v.js.map +1 -0
  72. package/dist/{daemon-w30PsdwV.js → daemon-D5gdG7gx.js} +3 -3
  73. package/dist/{daemon-w30PsdwV.js.map → daemon-D5gdG7gx.js.map} +1 -1
  74. package/dist/{daemon-entry-zOC1revO.js → daemon-entry--ummUJnk.js} +2 -2
  75. package/dist/{daemon-entry-zOC1revO.js.map → daemon-entry--ummUJnk.js.map} +1 -1
  76. package/dist/data-BJ9AZFUC.js +947 -0
  77. package/dist/data-BJ9AZFUC.js.map +1 -0
  78. package/dist/{db-Bz2RFGJj.js → db-D_iF4E-v.js} +38 -34
  79. package/dist/{db-Bz2RFGJj.js.map → db-D_iF4E-v.js.map} +1 -1
  80. package/dist/debug-nNbbxAeo.js +1114 -0
  81. package/dist/debug-nNbbxAeo.js.map +1 -0
  82. package/dist/{derive-C3ezmY-p.js → derive-Mky_u59_.js} +3 -3
  83. package/dist/{derive-C3ezmY-p.js.map → derive-Mky_u59_.js.map} +1 -1
  84. package/dist/{dev-D8TxrE_I.js → dev-bj6dEeSQ.js} +13 -13
  85. package/dist/{dev-D8TxrE_I.js.map → dev-bj6dEeSQ.js.map} +1 -1
  86. package/dist/dev-db/pull.d.ts +13 -3
  87. package/dist/{dev-preflight-DjvcV6SK.js → dev-preflight-BMOf2N6r.js} +2 -2
  88. package/dist/{dev-preflight-DjvcV6SK.js.map → dev-preflight-BMOf2N6r.js.map} +1 -1
  89. package/dist/{dev-server-BLxCbQEP.js → dev-server-2XHSHM_q.js} +2 -2
  90. package/dist/{dev-server-BLxCbQEP.js.map → dev-server-2XHSHM_q.js.map} +1 -1
  91. package/dist/{doctor-Du-mSxoE.js → doctor-2Jlau0Rm.js} +9 -8
  92. package/dist/{doctor-Du-mSxoE.js.map → doctor-2Jlau0Rm.js.map} +1 -1
  93. package/dist/{eject-Bhzd6hgb.js → eject-DK_M9kor.js} +4 -4
  94. package/dist/{eject-Bhzd6hgb.js.map → eject-DK_M9kor.js.map} +1 -1
  95. package/dist/{fold-static-CKewnAPX.js → fold-static-2t3UUX4z.js} +10 -6
  96. package/dist/fold-static-2t3UUX4z.js.map +1 -0
  97. package/dist/fold-static.d.ts +7 -0
  98. package/dist/functions-B4JR6EZL.js +120 -0
  99. package/dist/functions-B4JR6EZL.js.map +1 -0
  100. package/dist/{generate-view-CTOluXvH.js → generate-view-BMaLQm8H.js} +5 -5
  101. package/dist/{generate-view-CTOluXvH.js.map → generate-view-BMaLQm8H.js.map} +1 -1
  102. package/dist/{generate_sdk-De-aLC1L.js → generate_sdk-ByD-gTsK.js} +7 -7
  103. package/dist/{generate_sdk-De-aLC1L.js.map → generate_sdk-ByD-gTsK.js.map} +1 -1
  104. package/dist/index.es.js +123 -47
  105. package/dist/index.es.js.map +1 -1
  106. package/dist/{init-Dtl-IcXf.js → init-DHCe5mJ5.js} +59 -11
  107. package/dist/init-DHCe5mJ5.js.map +1 -0
  108. package/dist/{invoked-command-CG_rIa_o.js → invoked-command-FBeIBS8o.js} +2 -2
  109. package/dist/{invoked-command-CG_rIa_o.js.map → invoked-command-FBeIBS8o.js.map} +1 -1
  110. package/dist/last-dev-database-CBVkEUEl.js +2 -0
  111. package/dist/logs-CIgfLBsu.js +192 -0
  112. package/dist/logs-CIgfLBsu.js.map +1 -0
  113. package/dist/{manifest-C3uLDrrJ.js → manifest-RjqxfCpb.js} +114 -5
  114. package/dist/manifest-RjqxfCpb.js.map +1 -0
  115. package/dist/{migrate-VrKoi3nB.js → migrate-Cx8-Y4TG.js} +5 -4
  116. package/dist/{migrate-VrKoi3nB.js.map → migrate-Cx8-Y4TG.js.map} +1 -1
  117. package/dist/{normalize-imports-DwxqEMYq.js → normalize-imports-P86NVfpo.js} +3 -3
  118. package/dist/{normalize-imports-DwxqEMYq.js.map → normalize-imports-P86NVfpo.js.map} +1 -1
  119. package/dist/{path-flags-7O5uPBcQ.js → path-flags-ekLdkbra.js} +3 -3
  120. package/dist/{path-flags-7O5uPBcQ.js.map → path-flags-ekLdkbra.js.map} +1 -1
  121. package/dist/{prepare-Ccxspoj-.js → prepare-BaJe0Zik.js} +4 -4
  122. package/dist/{prepare-Ccxspoj-.js.map → prepare-BaJe0Zik.js.map} +1 -1
  123. package/dist/{project-CLcF5i8c.js → project-DALmhb5R.js} +2 -2
  124. package/dist/{project-CLcF5i8c.js.map → project-DALmhb5R.js.map} +1 -1
  125. package/dist/project-command-Cl9EZzjr.js +662 -0
  126. package/dist/project-command-Cl9EZzjr.js.map +1 -0
  127. package/dist/{project-schema-CsSOG2gE.js → project-schema-Dm6Jk0Y_.js} +4 -2
  128. package/dist/{project-schema-CsSOG2gE.js.map → project-schema-Dm6Jk0Y_.js.map} +1 -1
  129. package/dist/{pull-BMuiUyjb.js → pull-CTIsST6T.js} +66 -5
  130. package/dist/pull-CTIsST6T.js.map +1 -0
  131. package/dist/resolve-C36px9tR.js +2 -0
  132. package/dist/{resources-Dpfs2y8P.js → resources-Db3USuPO.js} +5 -5
  133. package/dist/{resources-Dpfs2y8P.js.map → resources-Db3USuPO.js.map} +1 -1
  134. package/dist/rls-BxrQ0P50.js +133 -0
  135. package/dist/rls-BxrQ0P50.js.map +1 -0
  136. package/dist/{schema-Dv6nHkb0.js → schema-_FzZEoB8.js} +54 -40
  137. package/dist/schema-_FzZEoB8.js.map +1 -0
  138. package/dist/{schema-dir-Cd1kvYbf.js → schema-dir-ChcYfWjP.js} +2 -2
  139. package/dist/{schema-dir-Cd1kvYbf.js.map → schema-dir-ChcYfWjP.js.map} +1 -1
  140. package/dist/schema-reconcile-DV14XY4o.js +2 -0
  141. package/dist/schema-show-h72UJ9zH.js +127 -0
  142. package/dist/schema-show-h72UJ9zH.js.map +1 -0
  143. package/dist/{skills-CXjA9TWw.js → skills-DQ2bZGkj.js} +6 -5
  144. package/dist/{skills-CXjA9TWw.js.map → skills-DQ2bZGkj.js.map} +1 -1
  145. package/dist/star-nudge.d.ts +28 -0
  146. package/dist/{start-Bwbtt2W5.js → start-Cjx4W0bJ.js} +7 -7
  147. package/dist/{start-Bwbtt2W5.js.map → start-Cjx4W0bJ.js.map} +1 -1
  148. package/dist/{status-BTgTWzlQ.js → status-CDBk25VO.js} +9 -9
  149. package/dist/{status-BTgTWzlQ.js.map → status-CDBk25VO.js.map} +1 -1
  150. package/dist/{storage-iTqj5-Av.js → storage-Clc8dLG8.js} +79 -36
  151. package/dist/storage-Clc8dLG8.js.map +1 -0
  152. package/dist/storage-objects-CfRKlTDe.js +279 -0
  153. package/dist/storage-objects-CfRKlTDe.js.map +1 -0
  154. package/dist/{telemetry-BP_1Cl9r.js → telemetry-DZU2-NCm.js} +5 -4
  155. package/dist/{telemetry-BP_1Cl9r.js.map → telemetry-DZU2-NCm.js.map} +1 -1
  156. package/dist/{telemetry-M3HjlyhZ.js → telemetry-EVtASbKb.js} +2 -2
  157. package/dist/{telemetry-M3HjlyhZ.js.map → telemetry-EVtASbKb.js.map} +1 -1
  158. package/dist/unknown-command-DnZ2uhGs.js +139 -0
  159. package/dist/unknown-command-DnZ2uhGs.js.map +1 -0
  160. package/dist/{upgrade-oZzJ13jM.js → upgrade-DhpUFb6p.js} +5 -5
  161. package/dist/{upgrade-oZzJ13jM.js.map → upgrade-DhpUFb6p.js.map} +1 -1
  162. package/dist/users-5PkqBY6R.js +561 -0
  163. package/dist/users-5PkqBY6R.js.map +1 -0
  164. package/dist/utils/project-command.d.ts +38 -0
  165. package/dist/utils/project-target.d.ts +193 -0
  166. package/dist/{verify-BkUVGLqo.js → verify-BdeqNb-V.js} +138 -12
  167. package/dist/verify-BdeqNb-V.js.map +1 -0
  168. package/dist/{version-Buyyo1ut.js → version-ONIeo7jl.js} +7 -2
  169. package/dist/{version-Buyyo1ut.js.map → version-ONIeo7jl.js.map} +1 -1
  170. package/package.json +10 -10
  171. package/dist/api-keys-eIUjMqWn.js.map +0 -1
  172. package/dist/apps-DExO4PEl.js.map +0 -1
  173. package/dist/args-CaCcrYE1.js.map +0 -1
  174. package/dist/auth-ofQETpM5.js.map +0 -1
  175. package/dist/bundle-DgILeA5b.js.map +0 -1
  176. package/dist/cloud-CYMk92iG.js.map +0 -1
  177. package/dist/command-D5lhW_-B.js.map +0 -1
  178. package/dist/fold-static-CKewnAPX.js.map +0 -1
  179. package/dist/init-Dtl-IcXf.js.map +0 -1
  180. package/dist/last-dev-database-Dc8cP01o.js +0 -2
  181. package/dist/manifest-C3uLDrrJ.js.map +0 -1
  182. package/dist/pull-BMuiUyjb.js.map +0 -1
  183. package/dist/resolve-BY7bSFRT.js +0 -2
  184. package/dist/schema-Dv6nHkb0.js.map +0 -1
  185. package/dist/schema-reconcile-CjxLaRHB.js +0 -2
  186. package/dist/storage-iTqj5-Av.js.map +0 -1
  187. package/dist/verify-BkUVGLqo.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-command-Cl9EZzjr.js","names":[],"sources":["../src/utils/project-target.ts","../src/utils/project-command.ts"],"sourcesContent":["/**\n * Which server a project command talks to, and as whom.\n *\n * Every command that acts on a running Rebase app — `rebase api`, `data`,\n * `users`, `cron`, `logs`, `functions`, `storage`, `api-keys`, `schema\n * reconcile` — resolves its target here, so they all accept the same flags,\n * refuse the same way, and never disagree about where the service key may go.\n *\n * ## Targets\n *\n * 1. `--project <slug>` (or `--cloud`, the project this directory is linked\n * to) — a Rebase Cloud project. The default transport is the console's\n * Studio proxy (`/api/functions/studio/<id>/proxy/*` on the control\n * plane): the CLI presents its `rebase cloud login` session there and the\n * control plane attaches the app's service key on its own side, so no\n * static secret ever reaches this machine. It answers an organization\n * owner or admin, on a project whose Studio switch is on — the gate the\n * console's Studio tab has. A command that only needs cron asks for a\n * platform token instead (see {@link ProjectTargetOptions.platformScopes}),\n * which any member with log access holds.\n * 2. `--url <server>` — a server the developer names.\n * 3. `REBASE_BASE_URL`, in the shell or in `.env`.\n * 4. The `rebase dev` this checkout is running (`.rebase/state.json`, while\n * the pid it names is alive).\n *\n * Nothing else: an address the CLI only guessed is one it would hand the\n * service key to without knowing whose server answers.\n *\n * ## Credentials, on a server target\n *\n * The service key from `.env` (`REBASE_SERVICE_KEY`, or the older\n * `SERVICE_KEY`; the shell's `REBASE_SERVICE_KEY` wins) unless the line says\n * otherwise: `--token <bearer>` sends that bearer (an `rk_` key, a user's\n * access token), `--session` sends the person session `rebase auth login`\n * stored for that server, and `--anon` sends nothing. On a cloud target the\n * same three flags skip the proxy and go to the app's public address directly.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport chalk from \"chalk\";\n\nimport { findProjectRoot, readEnvFile } from \"./project\";\nimport { cliUserAgent } from \"./version\";\nimport { serverUnreachableHint } from \"./dev-server\";\n\n/* ═══════════════════════════════════════════════════════════════\n Flags\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The flags every project command accepts, merged into its own spec.\n *\n * `--json` and `--yes` are here because the output mode and the confirmation\n * prompt are shared too (`commands/cloud/context.ts`): one JSON value on\n * stdout when piped or asked for, and a refusal rather than a prompt when\n * there is nobody to answer one.\n */\nexport const PROJECT_TARGET_FLAGS = {\n \"--project\": String,\n \"-p\": \"--project\",\n \"--cloud\": Boolean,\n \"--url\": String,\n \"--token\": String,\n \"--session\": Boolean,\n \"--anon\": Boolean,\n \"--json\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} as const;\n\n/** The same flags, as every project command's help page lists them. */\nexport const PROJECT_TARGET_HELP: Array<[string, string]> = [\n [\"--project, -p <slug>\", \"Act on a Rebase Cloud project, through the console's Studio proxy\"],\n [\"--cloud\", \"Act on the Rebase Cloud project this directory is linked to\"],\n [\"--url <server>\", \"Act on the server at this address (else REBASE_BASE_URL, then `rebase dev`)\"],\n [\"--token <bearer>\", \"Send this bearer instead of the service key (an rk_ key, a user's token)\"],\n [\"--session\", \"Send the session `rebase auth login` stored for this server\"],\n [\"--anon\", \"Send no credential at all\"],\n [\"--json\", \"Machine-readable output (also when piped, or REBASE_JSON=1)\"],\n [\"--yes, -y\", \"Skip confirmation prompts\"]\n];\n\n/** The values {@link PROJECT_TARGET_FLAGS} resolves to, as a command's parsed flags hold them. */\nexport type ProjectTargetFlags = {\n \"--project\"?: string;\n \"--cloud\"?: boolean;\n \"--url\"?: string;\n \"--token\"?: string;\n \"--session\"?: boolean;\n \"--anon\"?: boolean;\n};\n\n/* ═══════════════════════════════════════════════════════════════\n Where the local backend is\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Where this project's backend is — or why the CLI will not say.\n *\n * `configured` is an address the developer named; `running` is the one this\n * project's backend recorded when it bound, and is still serving on. There is\n * no third, guessed, answer.\n */\nexport type BackendAddress =\n | {\n url: string;\n source: \"configured\" | \"running\";\n /**\n * Set when the address came from `.env` and is the cloud project this\n * directory is linked to — which `rebase cloud init --claim` writes\n * there for the app and the SDK, not as a choice of where local\n * commands go. The command still goes there; {@link cloudTargetNote}\n * says so.\n */\n cloudProject?: string;\n }\n | { url: null; reason: string };\n\n/** Whether a process with this pid is alive and ours to signal. */\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n // ESRCH: gone. EPERM: alive, but another user's — not this project's backend.\n return false;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The address the service key may be sent to, from the project alone.\n *\n * In order: `REBASE_BASE_URL` in the shell or in `.env`, then the\n * `.rebase/state.json` this project's backend writes when it binds — and only\n * while the pid it names is alive, because a backend that was killed leaves\n * the file behind. `.env`'s `PORT` was once the fallback, and every scaffold\n * writes `PORT=3001`: with `rebase dev` stopped, the key went to whatever\n * listened on 3001.\n */\nexport function resolveBackendAddress(env: Record<string, string>, projectRoot: string): BackendAddress {\n const fromShell = process.env.REBASE_BASE_URL?.trim();\n const configured = fromShell || env.REBASE_BASE_URL?.trim();\n if (configured) {\n const cloudProject = fromShell ? undefined : linkedCloudProjectAt(projectRoot, configured);\n return cloudProject ? { url: configured, source: \"configured\", cloudProject } : { url: configured, source: \"configured\" };\n }\n\n const state = readBackendState(projectRoot);\n if (state && isAlive(state.pid)) return { url: state.url, source: \"running\" };\n\n const last = state ? ` The last one recorded here, at ${state.url} (pid ${state.pid}), has stopped.` : \"\";\n return {\n url: null,\n reason: `This project's server is not running, so the service key was not sent anywhere.${last} ` +\n \"Start it with `rebase dev`. If it runs some other way — `rebase start`, a container — \" +\n \"set REBASE_BASE_URL in .env to its address, or pass --url. For a Rebase Cloud project, pass --project <slug>.\"\n };\n}\n\n/** The slug of the cloud project `.rebase/cloud.json` links, when `url` is its address. */\nfunction linkedCloudProjectAt(projectRoot: string, url: string): string | undefined {\n const link = readJsonFile(path.join(projectRoot, \".rebase\", \"cloud.json\"));\n if (!isRecord(link) || link.mode === \"direct\" || typeof link.apiUrl !== \"string\") return undefined;\n const bare = (u: string) => u.trim().replace(/\\/+$/, \"\");\n if (bare(link.apiUrl) !== bare(url)) return undefined;\n if (typeof link.slug === \"string\" && link.slug) return link.slug;\n return typeof link.projectId === \"string\" && link.projectId ? link.projectId : undefined;\n}\n\n/**\n * What to say before sending a request to the address of a cloud project\n * `.env` names: it goes there, and that project does not take this\n * project's local service key.\n */\nexport function cloudTargetNote(address: BackendAddress): string | undefined {\n if (address.url === null || !address.cloudProject) return undefined;\n return `Sending this to ${address.url}: REBASE_BASE_URL in .env is the address of cloud project ${address.cloudProject} `\n + \"(`rebase cloud init --claim` writes it there for the app, the SDK and the MCP server), and that project does not \"\n + \"take this project's local service key. To reach it with your Cloud login, pass --project \"\n + `${address.cloudProject}; to reach the local backend, run the command with REBASE_BASE_URL set to it in the shell, `\n + \"e.g. REBASE_BASE_URL=http://localhost:3001.\";\n}\n\nfunction readJsonFile(file: string): unknown {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf-8\"));\n } catch {\n return null;\n }\n}\n\n/** What `.rebase/state.json` says about the backend that wrote it, or null. */\nfunction readBackendState(projectRoot: string): { url: string; pid: number } | null {\n const parsed = readJsonFile(path.join(projectRoot, \".rebase\", \"state.json\"));\n if (!isRecord(parsed) || typeof parsed.pid !== \"number\" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return null;\n const url = typeof parsed.baseUrl === \"string\" && parsed.baseUrl.trim()\n ? parsed.baseUrl.trim()\n : typeof parsed.port === \"number\" ? `http://localhost:${parsed.port}` : null;\n return url ? { url, pid: parsed.pid } : null;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Person sessions (`rebase auth login`)\n ═══════════════════════════════════════════════════════════════ */\n\n/** One person's session on one server, as `rebase auth login` stores it. */\nexport interface StoredSession {\n accessToken: string;\n refreshToken?: string;\n /** Epoch milliseconds. */\n expiresAt: number;\n email?: string;\n uid?: string;\n}\n\ninterface SessionsFile {\n sessions: Record<string, StoredSession>;\n}\n\n/**\n * `~/.rebase/sessions.json`: the person sessions `rebase auth login` keeps,\n * keyed by server origin. Never the project directory — a token there is one\n * `git add .` from a repository — and never the cloud credentials file, which\n * holds control-plane sessions a different command family manages.\n * `REBASE_SESSIONS_FILE` moves it, for tests.\n */\nexport function sessionsPath(): string {\n return process.env.REBASE_SESSIONS_FILE || path.join(os.homedir(), \".rebase\", \"sessions.json\");\n}\n\nfunction readSessions(): SessionsFile {\n const parsed = readJsonFile(sessionsPath());\n if (!isRecord(parsed) || !isRecord(parsed.sessions)) return { sessions: {} };\n const sessions: Record<string, StoredSession> = {};\n for (const [origin, value] of Object.entries(parsed.sessions)) {\n if (isRecord(value) && typeof value.accessToken === \"string\" && typeof value.expiresAt === \"number\") {\n sessions[origin] = {\n accessToken: value.accessToken,\n expiresAt: value.expiresAt,\n ...(typeof value.refreshToken === \"string\" ? { refreshToken: value.refreshToken } : {}),\n ...(typeof value.email === \"string\" ? { email: value.email } : {}),\n ...(typeof value.uid === \"string\" ? { uid: value.uid } : {})\n };\n }\n }\n return { sessions };\n}\n\n/** Write the file beside itself, then rename it over: a concurrent reader sees the old file or the new one. */\nfunction writeSessions(data: SessionsFile): void {\n const file = sessionsPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(temporary, JSON.stringify(data, null, 2), { mode: 0o600 });\n try {\n fs.chmodSync(temporary, 0o600);\n } catch {\n // best effort on platforms without chmod semantics\n }\n fs.renameSync(temporary, file);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\n/** The origin a session is filed under: scheme, host and port, no path. */\nexport function sessionKey(baseUrl: string): string {\n try {\n return new URL(baseUrl).origin;\n } catch {\n return baseUrl.replace(/\\/+$/, \"\");\n }\n}\n\nexport function storedSession(baseUrl: string): StoredSession | undefined {\n return readSessions().sessions[sessionKey(baseUrl)];\n}\n\nexport function saveSession(baseUrl: string, session: StoredSession): void {\n const data = readSessions();\n data.sessions[sessionKey(baseUrl)] = session;\n writeSessions(data);\n}\n\n/** Forget a server's session. Returns whether there was one. */\nexport function forgetSession(baseUrl: string): boolean {\n const data = readSessions();\n const key = sessionKey(baseUrl);\n if (!data.sessions[key]) return false;\n delete data.sessions[key];\n writeSessions(data);\n return true;\n}\n\n/** Two minutes of head-room before an access token is treated as expired. */\nconst SESSION_EXPIRY_BUFFER_MS = 120_000;\n\n/**\n * The session's access token, refreshed first when it is close to expiry —\n * through the server's own `POST /api/auth/refresh`, which rotates the refresh\n * token, so the new pair is written back.\n */\nasync function freshSessionToken(baseUrl: string): Promise<string> {\n const session = storedSession(baseUrl);\n if (!session) {\n throw new TargetError(\n `No session is stored for ${sessionKey(baseUrl)}.`,\n \"Sign in first with `rebase auth login` (it takes the same --url / --project flags).\",\n \"not_logged_in\"\n );\n }\n if (session.expiresAt > Date.now() + SESSION_EXPIRY_BUFFER_MS) return session.accessToken;\n if (!session.refreshToken) {\n throw new TargetError(`Your session for ${sessionKey(baseUrl)} has expired.`, \"Run `rebase auth login` again.\", \"session_expired\");\n }\n let res: Response;\n try {\n res = await fetch(`${baseUrl.replace(/\\/+$/, \"\")}/api/auth/refresh`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"User-Agent\": cliUserAgent() },\n body: JSON.stringify({ refreshToken: session.refreshToken })\n });\n } catch (e) {\n throw new TargetError(`Could not reach ${sessionKey(baseUrl)} to refresh your session: ${errorText(e)}`, undefined, \"network_error\");\n }\n const body: unknown = await res.json().catch(() => null);\n const tokens = sessionTokensOf(body);\n if (!res.ok || !tokens) {\n forgetSession(baseUrl);\n throw new TargetError(`Your session for ${sessionKey(baseUrl)} has expired.`, \"Run `rebase auth login` again.\", \"session_expired\");\n }\n saveSession(baseUrl, { ...session, ...tokens });\n return tokens.accessToken;\n}\n\n/**\n * The token pair out of an auth response — `{ tokens: { accessToken,\n * refreshToken, accessTokenExpiresAt } }`, the shape login, refresh and the\n * device grant all answer.\n */\nexport function sessionTokensOf(body: unknown): Pick<StoredSession, \"accessToken\" | \"refreshToken\" | \"expiresAt\"> | undefined {\n if (!isRecord(body)) return undefined;\n const tokens = isRecord(body.tokens) ? body.tokens : body;\n if (typeof tokens.accessToken !== \"string\" || !tokens.accessToken) return undefined;\n const expiresRaw = tokens.accessTokenExpiresAt ?? tokens.expiresAt;\n const expiresAt = typeof expiresRaw === \"number\"\n ? (expiresRaw < 1e12 ? expiresRaw * 1000 : expiresRaw)\n : typeof expiresRaw === \"string\" ? Date.parse(expiresRaw) : Date.now() + 15 * 60_000;\n return {\n accessToken: tokens.accessToken,\n ...(typeof tokens.refreshToken === \"string\" ? { refreshToken: tokens.refreshToken } : {}),\n expiresAt: Number.isFinite(expiresAt) ? expiresAt : Date.now() + 15 * 60_000\n };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n The target\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * A refusal while resolving or reaching a target: what happened, what to do\n * about it, and a stable code. Commands report it through the shared `fail`,\n * so it is one JSON value when piped.\n */\nexport class TargetError extends Error {\n constructor(message: string, readonly hint?: string, readonly code: string = \"error\") {\n super(message);\n this.name = \"TargetError\";\n }\n}\n\n/** How a request reaches the app, and as whom — for messages and `--json` output. */\nexport type TargetCredential =\n | \"service-key\"\n | \"token\"\n | \"session\"\n | \"none\"\n | \"studio-proxy\"\n | \"platform-token\";\n\nexport interface RequestOptions {\n method?: string;\n /** Query parameters. Repeated values (`string[]`) become repeated keys. */\n query?: Record<string, string | number | boolean | readonly string[] | undefined>;\n /** A JSON body, stringified here. */\n json?: unknown;\n /** A raw body, sent as it is. */\n body?: BodyInit;\n headers?: Record<string, string>;\n /** Abort after this many milliseconds; unset means no limit (a stream, an upload). */\n timeoutMs?: number;\n}\n\nexport interface ProjectTarget {\n kind: \"server\" | \"cloud\";\n /** Where requests go, for messages: `http://localhost:3001 (rebase dev)`, `cloud project acme`. */\n label: string;\n credential: TargetCredential;\n /** The app's own origin when it is reached directly; for the Studio proxy, the proxy's base. */\n baseUrl: string;\n /** The cloud project id, on a cloud target. */\n projectId?: string;\n /** Send a request to `path` on the app (`/api/admin/users`), with the credential. */\n request(path: string, options?: RequestOptions): Promise<Response>;\n /**\n * The bearer a request carries, for the clients that open their own\n * connection (the SDK's realtime socket). On the Studio proxy this is the\n * control-plane session, which only the proxy accepts.\n */\n bearer(): Promise<string | undefined>;\n}\n\nexport interface ProjectTargetOptions {\n /** Names the command in messages: `data query`. */\n command: string;\n /**\n * On a cloud target, ask the control plane for a platform token holding\n * these scopes and call the app directly, instead of the Studio proxy.\n * Only scopes the control plane issues (`cron:read`, `cron:write`), and\n * only when no credential flag was given.\n */\n platformScopes?: readonly string[];\n /**\n * The credential the command needs when the line names none. `person`:\n * the session `rebase auth login` stored (the RLS simulator and personal\n * keys refuse machines). Default: the service key on a server target.\n */\n defaultCredential?: \"service-key\" | \"person\";\n}\n\n/** One line of query string out of {@link RequestOptions.query}. */\nexport function queryString(query: RequestOptions[\"query\"]): string {\n if (!query) return \"\";\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) for (const item of value) params.append(key, String(item));\n else params.append(key, String(value));\n }\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nfunction errorText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * A `fetch` that sends one request with a bearer, refusing redirects: a 3xx\n * that crosses origins drops `Authorization` in some runtimes and keeps it in\n * others, and neither is what the caller meant.\n */\nasync function send(url: string, bearer: string | undefined, options: RequestOptions, label: string): Promise<Response> {\n const headers: Record<string, string> = {\n \"User-Agent\": cliUserAgent(),\n Accept: \"application/json\",\n ...(options.headers ?? {})\n };\n if (bearer) headers.Authorization = `Bearer ${bearer}`;\n let body = options.body;\n if (options.json !== undefined) {\n body = JSON.stringify(options.json);\n headers[\"Content-Type\"] = \"application/json\";\n }\n const controller = options.timeoutMs ? new AbortController() : undefined;\n const timer = controller ? setTimeout(() => controller.abort(), options.timeoutMs) : undefined;\n // `duplex` is required by undici for a streamed request body, and is not\n // in the DOM lib's RequestInit yet.\n const init: RequestInit & { duplex?: \"half\" } = {\n method: options.method ?? \"GET\",\n headers,\n body,\n redirect: \"manual\",\n signal: controller?.signal\n };\n if (body instanceof ReadableStream) init.duplex = \"half\";\n try {\n return await fetch(url, init);\n } catch (e) {\n if (controller?.signal.aborted) {\n throw new TargetError(`${label} did not answer within ${Math.round((options.timeoutMs ?? 0) / 1000)}s.`, undefined, \"timeout\");\n }\n throw new TargetError(`Could not reach ${label}: ${errorText(e)}`, undefined, \"network_error\");\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * The service key this project's `.env` holds, and the variable it came from.\n * The shell's `REBASE_SERVICE_KEY` wins over the file.\n */\nexport function projectServiceKey(projectRoot: string | null): { key: string; variable: string } | undefined {\n const shell = process.env.REBASE_SERVICE_KEY?.trim();\n if (shell) return { key: shell, variable: \"REBASE_SERVICE_KEY\" };\n if (!projectRoot) return undefined;\n const env = readEnvFile(projectRoot);\n if (env.SERVICE_KEY) return { key: env.SERVICE_KEY, variable: \"SERVICE_KEY\" };\n if (env.REBASE_SERVICE_KEY) return { key: env.REBASE_SERVICE_KEY, variable: \"REBASE_SERVICE_KEY\" };\n return undefined;\n}\n\n/** At most one of these may be on a line. */\nfunction chosenCredential(flags: ProjectTargetFlags): \"token\" | \"session\" | \"anon\" | undefined {\n const picked = [\n flags[\"--token\"] !== undefined ? \"token\" : undefined,\n flags[\"--session\"] ? \"session\" : undefined,\n flags[\"--anon\"] ? \"anon\" : undefined\n ].filter((c): c is \"token\" | \"session\" | \"anon\" => c !== undefined);\n if (picked.length > 1) {\n throw new TargetError(\"--token, --session and --anon each pick the credential; give one of them.\", undefined, \"usage\");\n }\n return picked[0];\n}\n\n/**\n * Resolve a project command's target from its parsed flags.\n *\n * @throws TargetError with a hint and a code; the caller reports it.\n */\nexport async function resolveProjectTarget(flags: ProjectTargetFlags, options: ProjectTargetOptions): Promise<ProjectTarget> {\n const cloudRef = flags[\"--project\"]?.trim() || (flags[\"--cloud\"] ? \"\" : undefined);\n if (cloudRef !== undefined && flags[\"--url\"]) {\n throw new TargetError(\"--url names a server and --project/--cloud a Rebase Cloud project; give one of them.\", undefined, \"usage\");\n }\n const credential = chosenCredential(flags);\n if (cloudRef !== undefined) return resolveCloudTarget(cloudRef, credential, flags, options);\n return resolveServerTarget(credential, flags, options);\n}\n\nasync function resolveServerTarget(\n credential: \"token\" | \"session\" | \"anon\" | undefined,\n flags: ProjectTargetFlags,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n const projectRoot = findProjectRoot();\n let baseUrl: string;\n let label: string;\n if (flags[\"--url\"]) {\n baseUrl = normalizeOrigin(flags[\"--url\"]);\n label = baseUrl;\n } else {\n if (!projectRoot) {\n throw new TargetError(\n \"No server to send the request to: this is not a Rebase project, and the line names none.\",\n \"Pass --url <server> or --project <slug>, or run this inside a project.\",\n \"no_target\"\n );\n }\n const address = resolveBackendAddress(readEnvFile(projectRoot), projectRoot);\n if (address.url === null) throw new TargetError(\"No server to send the request to.\", address.reason, \"no_target\");\n const note = cloudTargetNote(address);\n if (note) process.stderr.write(chalk.yellow(` ⚠ ${note}\\n`));\n baseUrl = normalizeOrigin(address.url);\n label = address.source === \"running\" ? `${baseUrl} (rebase dev)` : baseUrl;\n }\n\n const wantsPerson = options.defaultCredential === \"person\";\n let bearer: () => Promise<string | undefined>;\n let used: TargetCredential;\n if (credential === \"anon\") {\n bearer = async () => undefined;\n used = \"none\";\n } else if (credential === \"token\") {\n const token = flags[\"--token\"] ?? \"\";\n if (!token.trim()) throw new TargetError(\"--token was given an empty value.\", undefined, \"usage\");\n bearer = async () => token;\n used = \"token\";\n } else if (credential === \"session\" || wantsPerson) {\n bearer = () => freshSessionToken(baseUrl);\n used = \"session\";\n } else {\n const found = projectServiceKey(projectRoot);\n if (!found) {\n throw new TargetError(\n `No credential for ${label}: REBASE_SERVICE_KEY is not in .env or the shell.`,\n \"`rebase \" + options.command + \"` sends the project's service key by default. Pass --token <bearer>, \"\n + \"--session (after `rebase auth login`) or --anon instead.\",\n \"no_credential\"\n );\n }\n bearer = async () => found.key;\n used = \"service-key\";\n }\n\n return {\n kind: \"server\",\n label,\n credential: used,\n baseUrl,\n bearer,\n async request(requestPath, requestOptions = {}) {\n return send(`${baseUrl}${requestPath}${queryString(requestOptions.query)}`, await bearer(), requestOptions, label);\n }\n };\n}\n\n/** `https://x.example/` and `x.example` both become `https://x.example`; a path is kept. */\nexport function normalizeOrigin(raw: string): string {\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n const local = /^(localhost|127\\.|\\[::1\\]|0\\.0\\.0\\.0)/i.test(trimmed);\n return `${local ? \"http\" : \"https\"}://${trimmed}`;\n}\n\nasync function resolveCloudTarget(\n ref: string,\n credential: \"token\" | \"session\" | \"anon\" | undefined,\n flags: ProjectTargetFlags,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n // Imported here, not at the top: the cloud context pulls in the credential\n // store and inquirer, which a local `rebase data query` never needs.\n const cloud = await import(\"../commands/cloud/context\");\n const link = cloud.readLink();\n const projectRef = ref || link?.projectId;\n if (!projectRef) {\n throw new TargetError(\n \"--cloud acts on the project this directory is linked to, and it is not linked.\",\n \"Pass --project <slug>, or run `rebase cloud link`.\",\n \"no_project\"\n );\n }\n // The control plane the cloud family would use here: REBASE_CLOUD_URL, the\n // link, the current context. `--url` is this command's server flag, so it\n // is never read as the control plane's.\n const cloudArgs = [\"node\", \"rebase\", \"--project\", projectRef];\n const { client, url } = await cloud.requireClient(cloudArgs);\n let projectId: string;\n try {\n projectId = await cloud.resolveProjectRef(projectRef, client);\n } catch (e) {\n throw new TargetError(`Rebase Cloud project ${projectRef} not found: ${errorText(e)}`, \"`rebase cloud projects list` shows the projects you can reach.\", \"not_found\");\n }\n const label = `cloud project ${projectRef}`;\n\n // Direct to the app's public address: with a bearer the line names, with\n // none, or with a platform token for the scopes the command needs.\n const direct = credential !== undefined || (options.platformScopes !== undefined && options.platformScopes.length > 0);\n if (direct) {\n const { resolveOrigin } = await import(\"../commands/cloud/debug\");\n const origin = await resolveOrigin(cloudArgs, client, url, projectId);\n let bearer: () => Promise<string | undefined>;\n let used: TargetCredential;\n if (credential === \"anon\") {\n bearer = async () => undefined;\n used = \"none\";\n } else if (credential === \"token\") {\n const token = flags[\"--token\"] ?? \"\";\n bearer = async () => token;\n used = \"token\";\n } else if (credential === \"session\") {\n bearer = () => freshSessionToken(origin);\n used = \"session\";\n } else {\n const { mintRuntimeToken } = await import(\"../commands/cloud/cron\");\n const minted = await mintRuntimeToken(client, projectId, [...(options.platformScopes ?? [])]);\n bearer = async () => minted.token;\n used = \"platform-token\";\n }\n return {\n kind: \"cloud\",\n label: `${label} (${origin})`,\n credential: used,\n baseUrl: origin,\n projectId,\n bearer,\n async request(requestPath, requestOptions = {}) {\n return send(`${origin}${requestPath}${queryString(requestOptions.query)}`, await bearer(), requestOptions, label);\n }\n };\n }\n\n const proxyBase = `${url.replace(/\\/+$/, \"\")}/api/functions/studio/${encodeURIComponent(projectId)}/proxy`;\n return {\n kind: \"cloud\",\n label,\n credential: \"studio-proxy\",\n baseUrl: proxyBase,\n projectId,\n bearer: () => cloud.freshAccessToken(client),\n async request(requestPath, requestOptions = {}) {\n const bearer = await cloud.freshAccessToken(client);\n const res = await send(`${proxyBase}${requestPath}${queryString(requestOptions.query)}`, bearer, requestOptions, label);\n await explainProxyRefusal(res, projectRef);\n return res;\n }\n };\n}\n\n/**\n * The Studio proxy's own refusals, in the words of what to do about them.\n *\n * The proxy answers 401/403 itself — before the app sees anything — when the\n * caller is not an owner or admin, when the token holds no `project:studio`,\n * or when the project's Studio switch is off; the app's own refusals come back\n * in its error envelope and are left to the caller. Read from a clone so the\n * caller still has the body.\n */\nasync function explainProxyRefusal(res: Response, projectRef: string): Promise<void> {\n if (res.status !== 401 && res.status !== 403) return;\n const body: unknown = await res.clone().json().catch(() => null);\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const message = typeof error?.message === \"string\" ? error.message : \"\";\n if (/Studio access is switched off/i.test(message)) {\n throw new TargetError(\n `Studio access is switched off for ${projectRef}, and this command reaches the app through the console's Studio proxy.`,\n `An organization owner or admin can turn it on: \\`rebase cloud settings set --studio on --project ${projectRef}\\`.`,\n \"studio_disabled\"\n );\n }\n if (error && typeof error.code === \"string\" && /^(forbidden|unauthorized|scope_missing)$/i.test(error.code)) {\n throw new TargetError(\n `The control plane refused the Studio proxy for ${projectRef}: ${message || error.code}`,\n \"It answers organization owners and admins signed in with `rebase cloud login`; a token needs the project:studio scope. \"\n + \"Pass --token <bearer> to call the app's public address with a credential of its own instead.\",\n \"proxy_refused\"\n );\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Reading answers\n ═══════════════════════════════════════════════════════════════ */\n\n/** The app's error envelope: `{ error: { code, message, details } }`. */\nexport interface ApiErrorBody {\n code?: string;\n message?: string;\n details?: unknown;\n}\n\nexport function apiErrorOf(body: unknown): ApiErrorBody | undefined {\n if (!isRecord(body) || !isRecord(body.error)) return undefined;\n const e = body.error;\n return {\n ...(typeof e.code === \"string\" ? { code: e.code } : {}),\n ...(typeof e.message === \"string\" ? { message: e.message } : {}),\n ...(e.details !== undefined ? { details: e.details } : {})\n };\n}\n\n/**\n * Read a JSON answer, or throw a {@link TargetError} carrying the app's own\n * code and message — and, on a 401, which credential was refused, since that\n * is the question the next command will be about.\n */\nexport async function readJson(res: Response, target: ProjectTarget, action: string): Promise<unknown> {\n const text = await res.text();\n let body: unknown = null;\n if (text) {\n try {\n body = JSON.parse(text);\n } catch {\n body = text;\n }\n }\n if (res.ok) return body;\n throw failureOf(res.status, body, target, action);\n}\n\n/** The refusal a non-2xx answer becomes. Exported for commands that read streams. */\nexport function failureOf(status: number, body: unknown, target: ProjectTarget, action: string): TargetError {\n const error = apiErrorOf(body);\n const what = error?.message ?? (typeof body === \"string\" && body.trim() ? body.trim().slice(0, 300) : `HTTP ${status}`);\n const code = error?.code ?? (status === 404 ? \"not_found\" : status === 401 ? \"unauthenticated\" : status === 403 ? \"forbidden\" : \"error\");\n let hint: string | undefined;\n if (status === 401) {\n hint = target.credential === \"service-key\"\n ? `${target.label} did not accept REBASE_SERVICE_KEY — is it this project's server?`\n : target.credential === \"session\"\n ? \"The stored session was refused; run `rebase auth login` again.\"\n : target.credential === \"none\" ? \"This route needs a credential; drop --anon.\" : undefined;\n } else if (status === 501 && error?.code) {\n hint = \"The server does not offer this here (see the message); a newer @rebasepro/server may.\";\n }\n return new TargetError(`${action} — ${code} (${status}): ${what}`, hint, code);\n}\n\n/** Lines that say why a server could not be reached — `rebase dev` not running, and where it would be. */\nexport function unreachableHint(target: ProjectTarget): string | undefined {\n if (target.kind !== \"server\") return undefined;\n return serverUnreachableHint(target.baseUrl).map(line => line.trim()).join(\" \");\n}\n","/**\n * What every project command shares besides its target: the output mode, the\n * help page, the parse refusal and the way a failed request is reported.\n *\n * The output contract is the cloud family's (`commands/cloud/context.ts`),\n * reused rather than copied: one JSON value on stdout when `--json` is given,\n * `REBASE_JSON=1` is set or stdout is not a terminal; everything else on\n * stderr; a refusal is `{ \"error\": { message, code, hint } }` and exit 1; a\n * destructive action refuses rather than prompts when nobody can answer.\n *\n * Help is the one difference: a project command's `--help` is the page a\n * person reads even when piped (`rebase data --help | less`), and JSON only\n * when `--json` asks for it.\n */\nimport {\n emit,\n fail,\n initOutputMode,\n isJsonMode,\n printGroupHelp,\n type GroupHelp,\n type HelpAction\n} from \"../commands/cloud/context\";\nimport { wantsHelp } from \"./args\";\nimport {\n PROJECT_TARGET_HELP,\n TargetError,\n readJson,\n resolveProjectTarget,\n unreachableHint,\n type ProjectTarget,\n type ProjectTargetFlags,\n type ProjectTargetOptions,\n type RequestOptions\n} from \"./project-target\";\n\nexport { emit, fail, isJsonMode, type HelpAction };\n\n/** Latch the output mode for this run. Call first, before anything prints. */\nexport function startProjectCommand(rawArgs: string[]): void {\n initOutputMode(rawArgs, { whenPiped: wantsHelp(rawArgs) ? \"human\" : \"json\" });\n}\n\n/** A project group's help page, with the target flags as its global options. */\nexport function printProjectHelp(page: Omit<GroupHelp, \"globalFlags\">): void {\n printGroupHelp({ ...page, globalFlags: PROJECT_TARGET_HELP });\n}\n\n/**\n * Run a parse, and report its refusal through {@link fail} — one JSON value\n * when piped — rather than as a throw, which `bin/rebase.js` prints as text.\n */\nexport function parsedLine<T>(parse: () => T): T {\n try {\n return parse();\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e), undefined, \"usage\");\n }\n}\n\n/** Report a {@link TargetError} through {@link fail}; rethrow anything else. */\nexport function reportTargetError(e: unknown, target?: ProjectTarget): never {\n if (e instanceof TargetError) {\n const hint = e.code === \"network_error\" && target ? (unreachableHint(target) ?? e.hint) : e.hint;\n fail(e.message, hint, e.code);\n }\n throw e;\n}\n\n/** Resolve the target, or end the command with why not. */\nexport async function projectTarget(\n flags: Readonly<Record<string, unknown>>,\n options: ProjectTargetOptions\n): Promise<ProjectTarget> {\n try {\n return await resolveProjectTarget(targetFlagsOf(flags), options);\n } catch (e) {\n reportTargetError(e);\n }\n}\n\n/** The target flags out of a command's parsed flags, whatever else its spec declares. */\nfunction targetFlagsOf(flags: Record<string, unknown>): ProjectTargetFlags {\n const str = (key: string): string | undefined => (typeof flags[key] === \"string\" ? String(flags[key]) : undefined);\n const bool = (key: string): boolean | undefined => (flags[key] === true ? true : undefined);\n return {\n \"--project\": str(\"--project\"),\n \"--cloud\": bool(\"--cloud\"),\n \"--url\": str(\"--url\"),\n \"--token\": str(\"--token\"),\n \"--session\": bool(\"--session\"),\n \"--anon\": bool(\"--anon\")\n };\n}\n\n/** Send one request and read its JSON answer, or end the command with the app's own refusal. */\nexport async function requestJson(\n target: ProjectTarget,\n path: string,\n action: string,\n options: RequestOptions = {}\n): Promise<unknown> {\n try {\n const res = await target.request(path, { timeoutMs: 60_000, ...options });\n return await readJson(res, target, action);\n } catch (e) {\n reportTargetError(e, target);\n }\n}\n\n/** Narrowing helpers for the answers commands read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function recordsOf(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nexport function stringOf(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : undefined;\n}\n\n/** A cell's text for a table: strings as they are, everything else as compact JSON. */\nexport function cellText(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,IAAa,uBAAuB;CAChC,aAAa;CACb,MAAM;CACN,WAAW;CACX,SAAS;CACT,WAAW;CACX,aAAa;CACb,UAAU;CACV,UAAU;CACV,SAAS;CACT,MAAM;AACV;;AAGA,IAAa,sBAA+C;CACxD,CAAC,wBAAwB,mEAAmE;CAC5F,CAAC,WAAW,6DAA6D;CACzE,CAAC,kBAAkB,6EAA6E;CAChG,CAAC,oBAAoB,0EAA0E;CAC/F,CAAC,aAAa,6DAA6D;CAC3E,CAAC,UAAU,2BAA2B;CACtC,CAAC,UAAU,6DAA6D;CACxE,CAAC,aAAa,2BAA2B;AAC7C;;AAuCA,SAAS,QAAQ,KAAsB;CACnC,IAAI;EACA,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACX,QAAQ;EAEJ,OAAO;CACX;AACJ;AAEA,SAAS,WAAS,OAAkD;CAChE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E;;;;;;;;;;;AAYA,SAAgB,sBAAsB,KAA6B,aAAqC;CACpG,MAAM,YAAY,QAAQ,IAAI,iBAAiB,KAAK;CACpD,MAAM,aAAa,aAAa,IAAI,iBAAiB,KAAK;CAC1D,IAAI,YAAY;EACZ,MAAM,eAAe,YAAY,KAAA,IAAY,qBAAqB,aAAa,UAAU;EACzF,OAAO,eAAe;GAAE,KAAK;GAAY,QAAQ;GAAc;EAAa,IAAI;GAAE,KAAK;GAAY,QAAQ;EAAa;CAC5H;CAEA,MAAM,QAAQ,iBAAiB,WAAW;CAC1C,IAAI,SAAS,QAAQ,MAAM,GAAG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,KAAK,QAAQ;CAC3B;AACJ;;AAGA,eAAsB,YAClB,QACA,MACA,QACA,UAA0B,CAAC,GACX;CAChB,IAAI;EAEA,OAAO,MAAM,SAAS,MADJ,OAAO,QAAQ,MAAM;GAAE,WAAW;GAAQ,GAAG;EAAQ,CAAC,GAC7C,QAAQ,MAAM;CAC7C,SAAS,GAAG;EACR,kBAAkB,GAAG,MAAM;CAC/B;AACJ;;AAGA,SAAgB,SAAS,OAAkD;CACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E;AAEA,SAAgB,UAAU,OAA2C;CACjE,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,OAAO,QAAQ,IAAI,CAAC;AAC5D;AAEA,SAAgB,SAAS,OAAoC;CACzD,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI,KAAA;AAC3F;;AAGA,SAAgB,SAAS,OAAwB;CAC7C,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO,OAAO,KAAK;CAChF,OAAO,KAAK,UAAU,KAAK;AAC/B"}
@@ -1,5 +1,7 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
1
2
  import { t as createSchemaModuleImporter } from "./import-schema-module-Df67TIWj.js";
2
3
  //#region src/utils/project-schema.ts
4
+ var project_schema_exports = /* @__PURE__ */ __exportAll({ loadProjectSchema: () => loadProjectSchema });
3
5
  /**
4
6
  * Import and compile a project's schema directory.
5
7
  *
@@ -25,6 +27,6 @@ async function loadProjectSchema(projectRoot, schemaDir, aliases = {}) {
25
27
  };
26
28
  }
27
29
  //#endregion
28
- export { loadProjectSchema as t };
30
+ export { project_schema_exports as n, loadProjectSchema as t };
29
31
 
30
- //# sourceMappingURL=project-schema-CsSOG2gE.js.map
32
+ //# sourceMappingURL=project-schema-Dm6Jk0Y_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"project-schema-CsSOG2gE.js","names":[],"sources":["../src/utils/project-schema.ts"],"sourcesContent":["/**\n * The project's `backend/schema`, imported in this process — for the commands\n * that read the tables themselves rather than through the driver: `rebase\n * verify`, `rebase build`, `rebase resources`, `rebase generate-sdk`.\n *\n * Through `loadBackendSchema` from `@rebasepro/server`, the one definition of\n * \"the tables\" that boot, the runtime and the driver also read, so a command\n * here can never accept a schema the server refuses (or the reverse): a table\n * with no `rls`, an index that does not export a sibling's table, a project\n * still on the collections layout — each is the loader's error, word for word.\n * Modules are imported with the CLI's one importer\n * (`createSchemaModuleImporter`), so a file written earlier in the same\n * process is read as it is now.\n */\nimport type { CompiledSchema, LoadedSchema } from \"@rebasepro/server\";\nimport { createSchemaModuleImporter } from \"./import-schema-module\";\n\n/** The project's schema, as the loader read it and as it compiles. */\nexport interface ProjectSchema {\n loaded: LoadedSchema;\n compiled: CompiledSchema;\n}\n\n/**\n * Module specifiers mapped to files, for the importer. A user's project\n * resolves through its own `node_modules` and passes none; tests and in-repo\n * runs point `@rebasepro/*` at the workspace's source.\n */\nexport type ModuleAliases = Record<string, string>;\n\n/**\n * Import and compile a project's schema directory.\n *\n * Throws what the loader throws: `SchemaLoadError` (a module that does not\n * import, the legacy layout, a definition the index does not export) or\n * `SchemaDefinitionError` from `@rebasepro/common` (every problem with every\n * definition, one per line). A directory that does not exist, or has no\n * index, declares no tables: `descriptors` is empty.\n *\n * @param projectRoot the project root — where a leftover legacy collections\n * directory would be, and what the importer is rooted at.\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectSchema(\n projectRoot: string,\n schemaDir: string,\n aliases: ModuleAliases = {}\n): Promise<ProjectSchema> {\n const { loadBackendSchema, compileLoadedSchema } = await import(\"@rebasepro/server\");\n const importModule = await createSchemaModuleImporter(projectRoot, aliases);\n const loaded = await loadBackendSchema(schemaDir, { projectRoot, importModule });\n return { loaded, compiled: compileLoadedSchema(loaded) };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2CA,eAAsB,kBAClB,aACA,WACA,UAAyB,CAAC,GACJ;CACtB,MAAM,EAAE,mBAAmB,wBAAwB,MAAM,OAAO;CAEhE,MAAM,SAAS,MAAM,kBAAkB,WAAW;EAAE;EAAa,cAAA,MADtC,2BAA2B,aAAa,OAAO;CACI,CAAC;CAC/E,OAAO;EAAE;EAAQ,UAAU,oBAAoB,MAAM;CAAE;AAC3D"}
1
+ {"version":3,"file":"project-schema-Dm6Jk0Y_.js","names":[],"sources":["../src/utils/project-schema.ts"],"sourcesContent":["/**\n * The project's `backend/schema`, imported in this process — for the commands\n * that read the tables themselves rather than through the driver: `rebase\n * verify`, `rebase build`, `rebase resources`, `rebase generate-sdk`.\n *\n * Through `loadBackendSchema` from `@rebasepro/server`, the one definition of\n * \"the tables\" that boot, the runtime and the driver also read, so a command\n * here can never accept a schema the server refuses (or the reverse): a table\n * with no `rls`, an index that does not export a sibling's table, a project\n * still on the collections layout — each is the loader's error, word for word.\n * Modules are imported with the CLI's one importer\n * (`createSchemaModuleImporter`), so a file written earlier in the same\n * process is read as it is now.\n */\nimport type { CompiledSchema, LoadedSchema } from \"@rebasepro/server\";\nimport { createSchemaModuleImporter } from \"./import-schema-module\";\n\n/** The project's schema, as the loader read it and as it compiles. */\nexport interface ProjectSchema {\n loaded: LoadedSchema;\n compiled: CompiledSchema;\n}\n\n/**\n * Module specifiers mapped to files, for the importer. A user's project\n * resolves through its own `node_modules` and passes none; tests and in-repo\n * runs point `@rebasepro/*` at the workspace's source.\n */\nexport type ModuleAliases = Record<string, string>;\n\n/**\n * Import and compile a project's schema directory.\n *\n * Throws what the loader throws: `SchemaLoadError` (a module that does not\n * import, the legacy layout, a definition the index does not export) or\n * `SchemaDefinitionError` from `@rebasepro/common` (every problem with every\n * definition, one per line). A directory that does not exist, or has no\n * index, declares no tables: `descriptors` is empty.\n *\n * @param projectRoot the project root — where a leftover legacy collections\n * directory would be, and what the importer is rooted at.\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectSchema(\n projectRoot: string,\n schemaDir: string,\n aliases: ModuleAliases = {}\n): Promise<ProjectSchema> {\n const { loadBackendSchema, compileLoadedSchema } = await import(\"@rebasepro/server\");\n const importModule = await createSchemaModuleImporter(projectRoot, aliases);\n const loaded = await loadBackendSchema(schemaDir, { projectRoot, importModule });\n return { loaded, compiled: compileLoadedSchema(loaded) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2CA,eAAsB,kBAClB,aACA,WACA,UAAyB,CAAC,GACJ;CACtB,MAAM,EAAE,mBAAmB,wBAAwB,MAAM,OAAO;CAEhE,MAAM,SAAS,MAAM,kBAAkB,WAAW;EAAE;EAAa,cAAA,MADtC,2BAA2B,aAAa,OAAO;CACI,CAAC;CAC/E,OAAO;EAAE;EAAQ,UAAU,oBAAoB,MAAM;CAAE;AAC3D"}
@@ -853,6 +853,11 @@ async function findPgTool(tool) {
853
853
  function engineOf(version) {
854
854
  return /\bPGlite\b/i.test(version) ? "pglite" : "postgres";
855
855
  }
856
+ /** The major version `version()` names: 15 for `PostgreSQL 15.19 on aarch64-…`. Null when it names none. */
857
+ function majorVersionOf(version) {
858
+ const major = /\bPostgreSQL (\d+)/.exec(version)?.[1];
859
+ return major === void 0 ? null : Number(major);
860
+ }
856
861
  var NOTHING_CHANGED = "Nothing was changed: the local database is as it was.";
857
862
  /** What the target database runs on, or why it could not be asked. */
858
863
  async function readTargetEngine(target) {
@@ -1006,8 +1011,15 @@ function describeDumpFailure(source, run) {
1006
1011
  * means the local pg_dump is older than the source server and the dump could
1007
1012
  * not be edited to drop the key (`attver`, what {@link stripAttverFromArchive}
1008
1013
  * said, tells why).
1014
+ *
1015
+ * One error is known to cost the copy nothing, and does not fail it: a target
1016
+ * older than PostgreSQL 17 (`targetMajor`, read from its `version()`) refusing
1017
+ * the `SET transaction_timeout` a pg_dump 17 or newer writes at the top of
1018
+ * every dump — see {@link onlyTransactionTimeoutRefused}. Only when it is the
1019
+ * one kind of error in the run; the copy is then complete, and the outcome
1020
+ * carries a notice saying why pg_restore's error was harmless.
1009
1021
  */
1010
- function restoreOutcome(run, engine = "postgres", attver = null) {
1022
+ function restoreOutcome(run, engine = "postgres", attver = null, targetMajor = null) {
1011
1023
  if (run.signal) return {
1012
1024
  started: true,
1013
1025
  failure: `pg_restore was stopped by ${run.signal} before it finished.`,
@@ -1023,6 +1035,15 @@ function restoreOutcome(run, engine = "postgres", attver = null) {
1023
1035
  failure: null,
1024
1036
  advice: null
1025
1037
  };
1038
+ if (run.exitCode === 1 && targetMajor !== null && targetMajor < TRANSACTION_TIMEOUT_SINCE) {
1039
+ const refused = onlyTransactionTimeoutRefused(run.stderr ?? "");
1040
+ if (refused !== null) return {
1041
+ started: true,
1042
+ failure: null,
1043
+ advice: null,
1044
+ notice: transactionTimeoutNotice(targetMajor, refused)
1045
+ };
1046
+ }
1026
1047
  const ignored = /errors ignored on restore: (\d+)/.exec(run.stderr ?? "");
1027
1048
  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).";
1028
1049
  return {
@@ -1050,6 +1071,42 @@ function attverNotice(attver) {
1050
1071
  const atLeast = attver.serverVersion ? `at least ${attver.serverVersion}` : "at least the server's minor version";
1051
1072
  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.`;
1052
1073
  }
1074
+ /** The PostgreSQL major that added `transaction_timeout`, and whose pg_dump began writing `SET transaction_timeout = 0;`. */
1075
+ var TRANSACTION_TIMEOUT_SINCE = 17;
1076
+ /** pg_restore's line for an error, whatever caused it. */
1077
+ var RESTORE_ERROR_LINE = /^pg_restore: error: /;
1078
+ /** What a server older than 17 answers `SET transaction_timeout`: pg_restore's line for it, word for word. */
1079
+ var TRANSACTION_TIMEOUT_REFUSED_LINE = /^pg_restore: error: could not execute query: ERROR: {2}unrecognized configuration parameter "transaction_timeout"$/;
1080
+ /** The statement pg_restore names after that error. */
1081
+ var TRANSACTION_TIMEOUT_COMMAND_LINE = /^Command was: SET transaction_timeout = \d+;$/;
1082
+ /**
1083
+ * How many errors pg_restore reported when every one of them was the target
1084
+ * refusing the dump's `SET transaction_timeout`, or null when any was
1085
+ * anything else.
1086
+ *
1087
+ * Strict on purpose, because whatever it accepts is reported as a complete
1088
+ * copy: its summary ("errors ignored on restore: N") must be there, and N must
1089
+ * be exactly the number of errors it printed, each of them that refusal and
1090
+ * each naming that statement. An error it cannot read is never called harmless.
1091
+ */
1092
+ function onlyTransactionTimeoutRefused(stderr) {
1093
+ const ignored = /errors ignored on restore: (\d+)/.exec(stderr);
1094
+ if (!ignored) return null;
1095
+ const count = Number(ignored[1]);
1096
+ const lines = stderr.split(/\r?\n/).map((line) => line.trimEnd());
1097
+ const errors = lines.filter((line) => RESTORE_ERROR_LINE.test(line));
1098
+ const commands = lines.filter((line) => line.startsWith("Command was: "));
1099
+ if (count === 0 || errors.length !== count || commands.length !== count) return null;
1100
+ return errors.every((line) => TRANSACTION_TIMEOUT_REFUSED_LINE.test(line)) && commands.every((line) => TRANSACTION_TIMEOUT_COMMAND_LINE.test(line)) ? count : null;
1101
+ }
1102
+ /**
1103
+ * The line a pull prints when the only errors pg_restore reported were the
1104
+ * target refusing `SET transaction_timeout`: pg_restore has already printed
1105
+ * them, and this says they cost nothing.
1106
+ */
1107
+ function transactionTimeoutNotice(targetMajor, errors) {
1108
+ return `${errors === 1 ? "The error above is" : `The ${errors} errors above are`} the local PostgreSQL ${targetMajor} refusing the \`SET transaction_timeout = 0\` a pg_dump ${TRANSACTION_TIMEOUT_SINCE} or newer writes at the top of every dump: that setting does not exist before PostgreSQL ${TRANSACTION_TIMEOUT_SINCE}, nothing else failed, and the copy is complete.`;
1109
+ }
1053
1110
  /**
1054
1111
  * The local schemas a pull empties before it restores: every one of the local
1055
1112
  * database's own for a whole-database pull, and those it copies for a
@@ -1162,10 +1219,13 @@ async function restoreCopy(plan, dumpFile) {
1162
1219
  });
1163
1220
  client.on("error", () => void 0);
1164
1221
  let engine;
1222
+ let targetMajor;
1165
1223
  let begun = false;
1166
1224
  try {
1167
1225
  await client.connect();
1168
- engine = engineOf((await client.query("SELECT version() AS version")).rows[0]?.version ?? "");
1226
+ const version = (await client.query("SELECT version() AS version")).rows[0]?.version ?? "";
1227
+ engine = engineOf(version);
1228
+ targetMajor = majorVersionOf(version);
1169
1229
  if (engine === "pglite" && plan.targetEngine !== "pglite") return {
1170
1230
  cleared: false,
1171
1231
  started: false,
@@ -1195,10 +1255,11 @@ async function restoreCopy(plan, dumpFile) {
1195
1255
  reject: false
1196
1256
  });
1197
1257
  if (engine === "pglite") await resetSharedSession(plan.target);
1198
- const notice = attverNotice(attver);
1258
+ const outcome = restoreOutcome(run, engine, attver, targetMajor);
1259
+ const notice = [attverNotice(attver), outcome.notice].filter((line) => line).join(" ");
1199
1260
  return {
1200
1261
  cleared: true,
1201
- ...restoreOutcome(run, engine, attver),
1262
+ ...outcome,
1202
1263
  ...notice ? { notice } : {}
1203
1264
  };
1204
1265
  }
@@ -1242,4 +1303,4 @@ function describeRestoreFailure(outcome, source) {
1242
1303
  //#endregion
1243
1304
  export { anonymizeCopy, describeRestoreFailure, describeTarget, dumpSource, findPgTool, provisionableSchemas, restoreCopy, sourceProblem };
1244
1305
 
1245
- //# sourceMappingURL=pull-BMuiUyjb.js.map
1306
+ //# sourceMappingURL=pull-CTIsST6T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull-CTIsST6T.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 *\n * The same read of the TOC also answers which encoding a dump is written in\n * ({@link archiveEncoding}). A pull into the managed database asks that before\n * it empties anything.\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\n/** What the archive's header and ENCODING entry say, as far as it was read; null for what was not. */\ninterface ArchiveFacts {\n serverVersion: string | null;\n dumpVersion: string | null;\n encoding: string | null;\n}\n\ntype Plan =\n | ({ ok: true; patches: Patch[] } & ArchiveFacts)\n | ({ ok: false; reason: string } & ArchiveFacts);\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 let encoding: string | null = null;\n const refuse = (reason: string): Plan => ({ ok: false, reason, serverVersion, dumpVersion, encoding });\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 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, encoding };\n}\n\n/** Reads every definition as it is: what {@link archiveEncoding} walks the TOC with. */\nfunction unchanged(definition: Buffer): Buffer {\n return definition;\n}\n\n/**\n * The encoding a custom-format dump is written in, as its ENCODING entry\n * names it (`LATIN1`, `UTF8`, …), or null when this cannot read the file as\n * an archive.\n *\n * That entry is the `SET client_encoding` pg_restore starts every restore\n * with: the source database's encoding, unless pg_dump ran with\n * `PGCLIENTENCODING` naming another. The file is opened read-only and nothing\n * in it changes.\n */\nexport function archiveEncoding(dumpFile: string): string | null {\n const fd = fs.openSync(dumpFile, \"r\");\n try {\n return planPatches(fd, fs.fstatSync(fd).size, unchanged).encoding;\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n return null;\n } finally {\n fs.closeSync(fd);\n }\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, encoding: 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 { archiveEncoding, type AttverStrip, stripAttverFromArchive } from \"./attver\";\nimport { banner, connectionErrorText, hostOf } from \"./connection-banner\";\nimport { PGLITE_EXTENSIONS } from \"./constraints\";\nimport { LOCAL_CONNECT_TIMEOUT_MS, LOCAL_QUERY_TIMEOUT_MS } from \"./local-timeouts\";\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. Three things a restore relies on are not there. The server\n * runs each protocol message on its own, so the `CopyData` that follows a\n * `COPY … FROM stdin` never reaches the backend waiting for it: the COPY fails\n * on \"unexpected EOF\", and the session stops answering anyone until the daemon\n * is killed. It cannot convert between encodings, so a dump in any encoding\n * but UTF8 does the same at its first statement (see {@link encodingRefusal}).\n * And every connection shares that one session, so what pg_restore `SET`s for\n * 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\n/** The major version `version()` names: 15 for `PostgreSQL 15.19 on aarch64-…`. Null when it names none. */\nfunction majorVersionOf(version: string): number | null {\n const major = /\\bPostgreSQL (\\d+)/.exec(version)?.[1];\n return major === undefined ? null : Number(major);\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({\n connectionString: target,\n connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,\n query_timeout: LOCAL_QUERY_TIMEOUT_MS\n });\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 * Something the copy did that is worth one line, whether or not it\n * succeeded — see {@link attverNotice} and {@link transactionTimeoutNotice}.\n */\n notice?: string;\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 *\n * One error is known to cost the copy nothing, and does not fail it: a target\n * older than PostgreSQL 17 (`targetMajor`, read from its `version()`) refusing\n * the `SET transaction_timeout` a pg_dump 17 or newer writes at the top of\n * every dump — see {@link onlyTransactionTimeoutRefused}. Only when it is the\n * one kind of error in the run; the copy is then complete, and the outcome\n * carries a notice saying why pg_restore's error was harmless.\n */\nexport function restoreOutcome(\n run: RestoreRun,\n engine: PullTargetEngine = \"postgres\",\n attver: AttverStrip | null = null,\n targetMajor: number | 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 if (run.exitCode === 1 && targetMajor !== null && targetMajor < TRANSACTION_TIMEOUT_SINCE) {\n const refused = onlyTransactionTimeoutRefused(run.stderr ?? \"\");\n if (refused !== null) {\n return { started: true, failure: null, advice: null, notice: transactionTimeoutNotice(targetMajor, refused) };\n }\n }\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/** The PostgreSQL major that added `transaction_timeout`, and whose pg_dump began writing `SET transaction_timeout = 0;`. */\nconst TRANSACTION_TIMEOUT_SINCE = 17;\n\n/** pg_restore's line for an error, whatever caused it. */\nconst RESTORE_ERROR_LINE = /^pg_restore: error: /;\n\n/** What a server older than 17 answers `SET transaction_timeout`: pg_restore's line for it, word for word. */\nconst TRANSACTION_TIMEOUT_REFUSED_LINE =\n /^pg_restore: error: could not execute query: ERROR: {2}unrecognized configuration parameter \"transaction_timeout\"$/;\n\n/** The statement pg_restore names after that error. */\nconst TRANSACTION_TIMEOUT_COMMAND_LINE = /^Command was: SET transaction_timeout = \\d+;$/;\n\n/**\n * How many errors pg_restore reported when every one of them was the target\n * refusing the dump's `SET transaction_timeout`, or null when any was\n * anything else.\n *\n * Strict on purpose, because whatever it accepts is reported as a complete\n * copy: its summary (\"errors ignored on restore: N\") must be there, and N must\n * be exactly the number of errors it printed, each of them that refusal and\n * each naming that statement. An error it cannot read is never called harmless.\n */\nfunction onlyTransactionTimeoutRefused(stderr: string): number | null {\n const ignored = /errors ignored on restore: (\\d+)/.exec(stderr);\n if (!ignored) return null;\n const count = Number(ignored[1]);\n const lines = stderr.split(/\\r?\\n/).map((line) => line.trimEnd());\n const errors = lines.filter((line) => RESTORE_ERROR_LINE.test(line));\n const commands = lines.filter((line) => line.startsWith(\"Command was: \"));\n if (count === 0 || errors.length !== count || commands.length !== count) return null;\n const allRefusals = errors.every((line) => TRANSACTION_TIMEOUT_REFUSED_LINE.test(line))\n && commands.every((line) => TRANSACTION_TIMEOUT_COMMAND_LINE.test(line));\n\n return allRefusals ? count : null;\n}\n\n/**\n * The line a pull prints when the only errors pg_restore reported were the\n * target refusing `SET transaction_timeout`: pg_restore has already printed\n * them, and this says they cost nothing.\n */\nfunction transactionTimeoutNotice(targetMajor: number, errors: number): string {\n const which = errors === 1 ? \"The error above is\" : `The ${errors} errors above are`;\n\n return `${which} the local PostgreSQL ${targetMajor} refusing the \\`SET transaction_timeout = 0\\` a pg_dump `\n + `${TRANSACTION_TIMEOUT_SINCE} or newer writes at the top of every dump: that setting does not exist before `\n + `PostgreSQL ${TRANSACTION_TIMEOUT_SINCE}, nothing else failed, and the copy is complete.`;\n}\n\n/** How {@link restoreCopy} ended. */\nexport interface RestoreOutcome extends RestoreRunOutcome {\n /** Whether the local database was emptied first. False means it is exactly as it was. */\n cleared: boolean;\n}\n\n/**\n * The local schemas a pull empties before it restores: every one of the local\n * database's own for a whole-database pull, and those it copies for a\n * `--schema` pull. `pg_catalog`, `information_schema` and the `pg_*` internals\n * never — see {@link provisionableSchemas}.\n */\nexport function schemasToClear(present: readonly { schema: string }[], planned: readonly string[]): string[] {\n const local = provisionableSchemas(present);\n\n return planned.length === 0 ? local : local.filter((schema) => planned.includes(schema));\n}\n\n/**\n * The statements that empty those schemas, in one transaction.\n *\n * `CASCADE`, which `pg_restore --clean` never uses: a table the source lacks —\n * `rebase.atlas_schema_revisions` from `rebase db migrate`, a collection added\n * locally that references a pulled table — is exactly what blocked its plain\n * `DROP SCHEMA` and `DROP TABLE`. `public` is put back empty, with the access\n * every role has to it by default, because a dump does not create a default\n * `public` and every table in it would otherwise have nowhere to go.\n */\nexport function clearStatements(schemas: readonly string[]): string[] {\n const statements = schemas.map((schema) => `DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`);\n if (schemas.includes(\"public\")) statements.push(\"CREATE SCHEMA public\", \"GRANT USAGE ON SCHEMA public TO PUBLIC\");\n\n return statements;\n}\n\n/**\n * How long emptying the local database waits for a lock before giving up.\n *\n * A `rebase dev` serving from the database holds connections, and one inside\n * a transaction would otherwise make the pull hang without a word.\n */\nconst CLEAR_LOCK_TIMEOUT = \"15s\";\n\n/**\n * How long one statement of {@link restoreCopy}'s may take before the pull\n * stops waiting on the database: twice the short bound, 30s. It has to stay\n * above {@link CLEAR_LOCK_TIMEOUT}, so that a lock the clear waits on is\n * reported as the lock it is (`55P03`, \"stop `rebase dev`\"). This bound is for\n * a database that answers nothing at all.\n */\nconst CLEAR_QUERY_TIMEOUT_MS = 2 * LOCAL_QUERY_TIMEOUT_MS;\n\n/**\n * The one encoding the managed database restores a dump in.\n *\n * pg_restore starts every restore with the dump's own `SET client_encoding`.\n * PGlite cannot convert. Sent `SET client_encoding = 'LATIN1'`, its daemon\n * closed the connection and then answered nobody, on that connection or any\n * later one, until `rebase db stop`. A pull from a LATIN1 database had\n * already emptied the local one by then. Every statement after the SET failed\n * on \"no connection to the server\".\n */\nconst MANAGED_ENCODING = \"UTF8\";\n\n/**\n * Why the local database cannot take a dump written in `encoding`, or null\n * when it can.\n *\n * Only the managed database refuses one. A Postgres target converts any\n * encoding to its own as pg_restore writes, which is how a LATIN1 source has\n * always pulled into Postgres in Docker. `encoding` is what\n * {@link archiveEncoding} read from the dump's ENCODING entry. Null means the\n * dump could not be read, and pg_restore is left to say what it makes of it,\n * as before. {@link restoreCopy} asks this before it empties anything, so the\n * outcome says the database is as it was.\n */\nexport function encodingRefusal(engine: PullTargetEngine, encoding: string | null): RestoreOutcome | null {\n if (engine !== \"pglite\" || encoding === null) return null;\n if (encoding.replace(/[-_]/g, \"\").toUpperCase() === MANAGED_ENCODING) return null;\n\n return {\n cleared: false,\n started: false,\n failure: `The managed development database cannot take this dump: pg_dump wrote it in the ${encoding} encoding `\n + \"(the source database's, unless PGCLIENTENCODING named another), and PGlite restores UTF8 only. \"\n + `The \\`SET client_encoding = '${encoding}'\\` a restore starts with leaves it answering nobody.`,\n advice: \"Pull into Postgres in Docker instead, which converts it: `rebase db pull --docker` with the same --from. \"\n + \"Or set DATABASE_URL in .env to a Postgres you run, and pull into that.\"\n };\n}\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, and written in UTF8: a COPY, or any other\n * encoding, would leave the daemon answering nobody, so either is refused\n * 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 // Read from the dump, which is not the database: an encoding the managed\n // database cannot take is refused while the database is still as it was.\n const encoding = archiveEncoding(dumpFile);\n const { Client } = await import(\"pg\");\n // Bounded, because a wedged managed database accepts the socket and then\n // never answers (see local-timeouts.ts).\n const client = new Client({\n connectionString: plan.target,\n connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,\n query_timeout: CLEAR_QUERY_TIMEOUT_MS\n });\n client.on(\"error\", () => undefined);\n let engine: PullTargetEngine;\n let targetMajor: number | null;\n // ROLLBACK only once BEGIN has been sent. Before that there is nothing to\n // roll back, and after a statement that timed out a ROLLBACK only waits\n // out a second bound.\n let begun = false;\n try {\n await client.connect();\n const version = (await client.query<{ version: string }>(\"SELECT version() AS version\")).rows[0]?.version ?? \"\";\n engine = engineOf(version);\n targetMajor = majorVersionOf(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 refused = encodingRefusal(engine, encoding);\n if (refused) return refused;\n const { rows } = await client.query<{ schema: string }>(\"SELECT nspname AS \\\"schema\\\" FROM pg_namespace\");\n begun = true;\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 if (begun) 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 outcome = restoreOutcome(run, engine, attver, targetMajor);\n const notice = [attverNotice(attver), outcome.notice].filter((line) => line).join(\" \");\n\n return { cleared: true, ...outcome, ...(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({\n connectionString: target,\n connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,\n query_timeout: LOCAL_QUERY_TIMEOUT_MS\n });\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,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,c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AS,IAAI,OAAO;EACtB,kBAAkB;EAClB,yBAAyB;EACzB,eAAe;CACnB,CAAC;CACD,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-BaJe0Zik.js";
2
+ export { resolveDevDatabase };
@@ -1,7 +1,7 @@
1
- import { a as wantsHelp, n as parseCommandArgs } from "./args-CaCcrYE1.js";
2
- import { i as failAsJson, p as requireProjectRoot } from "./project-CLcF5i8c.js";
3
- import { _ as findBackendApp, b as loadManifest, l as ManifestError } from "./manifest-C3uLDrrJ.js";
4
- import { a as projectResourceGraph, l as writeResourceGraphFile, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-C3ezmY-p.js";
1
+ import { a as wantsHelp, n as parseCommandArgs } from "./args-DHyrshtI.js";
2
+ import { i as failAsJson, p as requireProjectRoot } from "./project-DALmhb5R.js";
3
+ import { _ as findBackendApp, b as loadManifest, l as ManifestError } from "./manifest-RjqxfCpb.js";
4
+ import { a as projectResourceGraph, l as writeResourceGraphFile, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-Mky_u59_.js";
5
5
  import chalk from "chalk";
6
6
  import path from "path";
7
7
  import { declaredSubscriptions } from "@rebasepro/types";
@@ -180,4 +180,4 @@ async function resourcesCommand(rawArgs) {
180
180
  //#endregion
181
181
  export { resourcesCommand };
182
182
 
183
- //# sourceMappingURL=resources-Dpfs2y8P.js.map
183
+ //# sourceMappingURL=resources-Db3USuPO.js.map