@rebasepro/cli 0.31.0-canary.g902a0ce → 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.
- package/dist/{agent-setup-DqAcoDcn.js → agent-setup-Cg_zBWoW.js} +3 -3
- package/dist/{agent-setup-DqAcoDcn.js.map → agent-setup-Cg_zBWoW.js.map} +1 -1
- package/dist/api-TbmW33D7.js +275 -0
- package/dist/api-TbmW33D7.js.map +1 -0
- package/dist/{api-keys-eIUjMqWn.js → api-keys-fPQ55DCm.js} +151 -158
- package/dist/api-keys-fPQ55DCm.js.map +1 -0
- package/dist/{apps-DExO4PEl.js → apps-DBTRoOeP.js} +18 -13
- package/dist/apps-DBTRoOeP.js.map +1 -0
- package/dist/{args-CaCcrYE1.js → args-DHyrshtI.js} +3 -132
- package/dist/args-DHyrshtI.js.map +1 -0
- package/dist/{atlas-dev-database-DOCKk6ht.js → atlas-dev-database-D6h65f2x.js} +3 -3
- package/dist/{atlas-dev-database-DOCKk6ht.js.map → atlas-dev-database-D6h65f2x.js.map} +1 -1
- package/dist/{auth-CyADghFQ.js → auth-BpyYLEFY.js} +93 -12
- package/dist/auth-BpyYLEFY.js.map +1 -0
- package/dist/auth-session-B6aT0Dyj.js +371 -0
- package/dist/auth-session-B6aT0Dyj.js.map +1 -0
- package/dist/{backend-guard-C0mVkXBw.js → backend-guard-Cf8eMK_f.js} +2 -2
- package/dist/{backend-guard-C0mVkXBw.js.map → backend-guard-Cf8eMK_f.js.map} +1 -1
- package/dist/{branch-pointer-DMPyvZoK.js → branch-pointer-BJOF2Ubv.js} +1 -1
- package/dist/{build-CA5R07tw.js → build-BfdT-AUR.js} +12 -10
- package/dist/{build-CA5R07tw.js.map → build-BfdT-AUR.js.map} +1 -1
- package/dist/{bundle-DgILeA5b.js → bundle-CIiKGrte.js} +78 -12
- package/dist/bundle-CIiKGrte.js.map +1 -0
- package/dist/bundle.d.ts +31 -1
- package/dist/{cloud-CYMk92iG.js → cloud-MqnyPnmX.js} +1540 -1531
- package/dist/cloud-MqnyPnmX.js.map +1 -0
- package/dist/{cms-directories-BK3vcswg.js → cms-directories-BaV-Is9a.js} +2 -2
- package/dist/{cms-directories-BK3vcswg.js.map → cms-directories-BaV-Is9a.js.map} +1 -1
- package/dist/codemod/collections-to-tables/backend.d.ts +0 -2
- package/dist/codemod/collections-to-tables/customization.d.ts +2 -1
- package/dist/codemod/collections-to-tables/modules.d.ts +32 -0
- package/dist/codemod/collections-to-tables/plan-context.d.ts +7 -1
- package/dist/{command-D5lhW_-B.js → command-D9g46gg9.js} +68 -42
- package/dist/command-D9g46gg9.js.map +1 -0
- package/dist/commands/api-keys.d.ts +89 -52
- package/dist/commands/api.d.ts +114 -0
- package/dist/commands/auth-session.d.ts +94 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/cloud/alerts.d.ts +29 -0
- package/dist/commands/cloud/context.d.ts +8 -0
- package/dist/commands/cloud/debug.d.ts +16 -1
- package/dist/commands/cloud/deploy-hooks.d.ts +19 -0
- package/dist/commands/cloud/deploy.d.ts +25 -0
- package/dist/commands/cloud/env.d.ts +1 -0
- package/dist/commands/cloud/index.d.ts +5 -0
- package/dist/commands/cloud/maintenance.d.ts +26 -1
- package/dist/commands/cloud/not-served.d.ts +27 -0
- package/dist/commands/cloud/orgs.d.ts +5 -0
- package/dist/commands/cloud/resources.d.ts +82 -2
- package/dist/commands/cloud/runtime-logs.d.ts +57 -0
- package/dist/commands/cloud/settings.d.ts +3 -0
- package/dist/commands/cron.d.ts +68 -0
- package/dist/commands/data.d.ts +197 -0
- package/dist/commands/functions.d.ts +38 -0
- package/dist/commands/logs.d.ts +22 -0
- package/dist/commands/rls.d.ts +31 -0
- package/dist/commands/schema-reconcile.d.ts +2 -1
- package/dist/commands/schema-show.d.ts +38 -0
- package/dist/commands/storage-objects.d.ts +88 -0
- package/dist/commands/storage.d.ts +18 -2
- package/dist/commands/users.d.ts +147 -0
- package/dist/{consent-BXLIrMl8.js → consent-UV6ObCME.js} +2 -2
- package/dist/{consent-BXLIrMl8.js.map → consent-UV6ObCME.js.map} +1 -1
- package/dist/{console-CMjhgMUE.js → console-BVoYOLAO.js} +6 -6
- package/dist/{console-CMjhgMUE.js.map → console-BVoYOLAO.js.map} +1 -1
- package/dist/{context--JwaHaZp.js → context-BOMEoKxn.js} +80 -9
- package/dist/{context--JwaHaZp.js.map → context-BOMEoKxn.js.map} +1 -1
- package/dist/cron-CpUsQ739.js +298 -0
- package/dist/cron-CpUsQ739.js.map +1 -0
- package/dist/cron-ZRXsla0v.js +259 -0
- package/dist/cron-ZRXsla0v.js.map +1 -0
- package/dist/{daemon-w30PsdwV.js → daemon-D5gdG7gx.js} +3 -3
- package/dist/{daemon-w30PsdwV.js.map → daemon-D5gdG7gx.js.map} +1 -1
- package/dist/{daemon-entry-zOC1revO.js → daemon-entry--ummUJnk.js} +2 -2
- package/dist/{daemon-entry-zOC1revO.js.map → daemon-entry--ummUJnk.js.map} +1 -1
- package/dist/data-BJ9AZFUC.js +947 -0
- package/dist/data-BJ9AZFUC.js.map +1 -0
- package/dist/{db-A7XDCIIO.js → db-D_iF4E-v.js} +60 -36
- package/dist/db-D_iF4E-v.js.map +1 -0
- package/dist/debug-nNbbxAeo.js +1114 -0
- package/dist/debug-nNbbxAeo.js.map +1 -0
- package/dist/{derive-C3ezmY-p.js → derive-Mky_u59_.js} +3 -3
- package/dist/{derive-C3ezmY-p.js.map → derive-Mky_u59_.js.map} +1 -1
- package/dist/{dev-tWwPyWkQ.js → dev-bj6dEeSQ.js} +13 -13
- package/dist/{dev-tWwPyWkQ.js.map → dev-bj6dEeSQ.js.map} +1 -1
- package/dist/dev-db/__fixtures__/unanswering-postgres.d.ts +11 -0
- package/dist/dev-db/attver.d.ts +38 -6
- package/dist/dev-db/local-timeouts.d.ts +25 -0
- package/dist/dev-db/pull.d.ts +49 -9
- package/dist/{dev-preflight-DjvcV6SK.js → dev-preflight-BMOf2N6r.js} +2 -2
- package/dist/{dev-preflight-DjvcV6SK.js.map → dev-preflight-BMOf2N6r.js.map} +1 -1
- package/dist/{dev-server-BLxCbQEP.js → dev-server-2XHSHM_q.js} +2 -2
- package/dist/{dev-server-BLxCbQEP.js.map → dev-server-2XHSHM_q.js.map} +1 -1
- package/dist/{doctor-BBM0dWvZ.js → doctor-2Jlau0Rm.js} +9 -8
- package/dist/{doctor-BBM0dWvZ.js.map → doctor-2Jlau0Rm.js.map} +1 -1
- package/dist/{eject-Bhzd6hgb.js → eject-DK_M9kor.js} +4 -4
- package/dist/{eject-Bhzd6hgb.js.map → eject-DK_M9kor.js.map} +1 -1
- package/dist/{fold-static-CKewnAPX.js → fold-static-2t3UUX4z.js} +10 -6
- package/dist/fold-static-2t3UUX4z.js.map +1 -0
- package/dist/fold-static.d.ts +7 -0
- package/dist/functions-B4JR6EZL.js +120 -0
- package/dist/functions-B4JR6EZL.js.map +1 -0
- package/dist/{generate-view-CTOluXvH.js → generate-view-BMaLQm8H.js} +5 -5
- package/dist/{generate-view-CTOluXvH.js.map → generate-view-BMaLQm8H.js.map} +1 -1
- package/dist/{generate_sdk-De-aLC1L.js → generate_sdk-ByD-gTsK.js} +7 -7
- package/dist/{generate_sdk-De-aLC1L.js.map → generate_sdk-ByD-gTsK.js.map} +1 -1
- package/dist/index.es.js +123 -47
- package/dist/index.es.js.map +1 -1
- package/dist/{init-Dtl-IcXf.js → init-DHCe5mJ5.js} +59 -11
- package/dist/init-DHCe5mJ5.js.map +1 -0
- package/dist/{invoked-command-CG_rIa_o.js → invoked-command-FBeIBS8o.js} +2 -2
- package/dist/{invoked-command-CG_rIa_o.js.map → invoked-command-FBeIBS8o.js.map} +1 -1
- package/dist/last-dev-database-CBVkEUEl.js +2 -0
- package/dist/local-timeouts-B1Kwligw.js +30 -0
- package/dist/local-timeouts-B1Kwligw.js.map +1 -0
- package/dist/logs-CIgfLBsu.js +192 -0
- package/dist/logs-CIgfLBsu.js.map +1 -0
- package/dist/{manifest-C3uLDrrJ.js → manifest-RjqxfCpb.js} +114 -5
- package/dist/manifest-RjqxfCpb.js.map +1 -0
- package/dist/{migrate-VrKoi3nB.js → migrate-Cx8-Y4TG.js} +5 -4
- package/dist/{migrate-VrKoi3nB.js.map → migrate-Cx8-Y4TG.js.map} +1 -1
- package/dist/{normalize-imports-DwxqEMYq.js → normalize-imports-P86NVfpo.js} +3 -3
- package/dist/{normalize-imports-DwxqEMYq.js.map → normalize-imports-P86NVfpo.js.map} +1 -1
- package/dist/{path-flags-7O5uPBcQ.js → path-flags-ekLdkbra.js} +3 -3
- package/dist/{path-flags-7O5uPBcQ.js.map → path-flags-ekLdkbra.js.map} +1 -1
- package/dist/{prepare-Ccxspoj-.js → prepare-BaJe0Zik.js} +4 -4
- package/dist/{prepare-Ccxspoj-.js.map → prepare-BaJe0Zik.js.map} +1 -1
- package/dist/{project-CLcF5i8c.js → project-DALmhb5R.js} +2 -2
- package/dist/{project-CLcF5i8c.js.map → project-DALmhb5R.js.map} +1 -1
- package/dist/project-command-Cl9EZzjr.js +662 -0
- package/dist/project-command-Cl9EZzjr.js.map +1 -0
- package/dist/{project-schema-CsSOG2gE.js → project-schema-Dm6Jk0Y_.js} +4 -2
- package/dist/{project-schema-CsSOG2gE.js.map → project-schema-Dm6Jk0Y_.js.map} +1 -1
- package/dist/{pull-D9WvpDYY.js → pull-CTIsST6T.js} +336 -55
- package/dist/pull-CTIsST6T.js.map +1 -0
- package/dist/resolve-C36px9tR.js +2 -0
- package/dist/{resources-Dpfs2y8P.js → resources-Db3USuPO.js} +5 -5
- package/dist/{resources-Dpfs2y8P.js.map → resources-Db3USuPO.js.map} +1 -1
- package/dist/rls-BxrQ0P50.js +133 -0
- package/dist/rls-BxrQ0P50.js.map +1 -0
- package/dist/{schema-DwFDI1iU.js → schema-_FzZEoB8.js} +54 -40
- package/dist/schema-_FzZEoB8.js.map +1 -0
- package/dist/{schema-dir-Cd1kvYbf.js → schema-dir-ChcYfWjP.js} +2 -2
- package/dist/{schema-dir-Cd1kvYbf.js.map → schema-dir-ChcYfWjP.js.map} +1 -1
- package/dist/schema-reconcile-DV14XY4o.js +2 -0
- package/dist/schema-show-h72UJ9zH.js +127 -0
- package/dist/schema-show-h72UJ9zH.js.map +1 -0
- package/dist/{skills-CXjA9TWw.js → skills-DQ2bZGkj.js} +6 -5
- package/dist/{skills-CXjA9TWw.js.map → skills-DQ2bZGkj.js.map} +1 -1
- package/dist/star-nudge.d.ts +28 -0
- package/dist/{start-Bwbtt2W5.js → start-Cjx4W0bJ.js} +7 -7
- package/dist/{start-Bwbtt2W5.js.map → start-Cjx4W0bJ.js.map} +1 -1
- package/dist/{status-DQ_PPz4C.js → status-CDBk25VO.js} +9 -9
- package/dist/{status-DQ_PPz4C.js.map → status-CDBk25VO.js.map} +1 -1
- package/dist/{storage-iTqj5-Av.js → storage-Clc8dLG8.js} +79 -36
- package/dist/storage-Clc8dLG8.js.map +1 -0
- package/dist/storage-objects-CfRKlTDe.js +279 -0
- package/dist/storage-objects-CfRKlTDe.js.map +1 -0
- package/dist/{telemetry-BP_1Cl9r.js → telemetry-DZU2-NCm.js} +5 -4
- package/dist/{telemetry-BP_1Cl9r.js.map → telemetry-DZU2-NCm.js.map} +1 -1
- package/dist/{telemetry-M3HjlyhZ.js → telemetry-EVtASbKb.js} +2 -2
- package/dist/{telemetry-M3HjlyhZ.js.map → telemetry-EVtASbKb.js.map} +1 -1
- package/dist/unknown-command-DnZ2uhGs.js +139 -0
- package/dist/unknown-command-DnZ2uhGs.js.map +1 -0
- package/dist/{upgrade-oZzJ13jM.js → upgrade-DhpUFb6p.js} +5 -5
- package/dist/{upgrade-oZzJ13jM.js.map → upgrade-DhpUFb6p.js.map} +1 -1
- package/dist/users-5PkqBY6R.js +561 -0
- package/dist/users-5PkqBY6R.js.map +1 -0
- package/dist/utils/project-command.d.ts +38 -0
- package/dist/utils/project-target.d.ts +193 -0
- package/dist/{verify-DkJqhYPI.js → verify-BdeqNb-V.js} +138 -12
- package/dist/verify-BdeqNb-V.js.map +1 -0
- package/dist/{version-Buyyo1ut.js → version-ONIeo7jl.js} +7 -2
- package/dist/{version-Buyyo1ut.js.map → version-ONIeo7jl.js.map} +1 -1
- package/package.json +10 -10
- package/dist/api-keys-eIUjMqWn.js.map +0 -1
- package/dist/apps-DExO4PEl.js.map +0 -1
- package/dist/args-CaCcrYE1.js.map +0 -1
- package/dist/auth-CyADghFQ.js.map +0 -1
- package/dist/bundle-DgILeA5b.js.map +0 -1
- package/dist/cloud-CYMk92iG.js.map +0 -1
- package/dist/command-D5lhW_-B.js.map +0 -1
- package/dist/db-A7XDCIIO.js.map +0 -1
- package/dist/fold-static-CKewnAPX.js.map +0 -1
- package/dist/init-Dtl-IcXf.js.map +0 -1
- package/dist/last-dev-database-Dc8cP01o.js +0 -2
- package/dist/manifest-C3uLDrrJ.js.map +0 -1
- package/dist/pull-D9WvpDYY.js.map +0 -1
- package/dist/resolve-BY7bSFRT.js +0 -2
- package/dist/schema-DwFDI1iU.js.map +0 -1
- package/dist/schema-reconcile-Tto54Qbv.js +0 -2
- package/dist/storage-iTqj5-Av.js.map +0 -1
- package/dist/verify-DkJqhYPI.js.map +0 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** One of the servers {@link unansweringPostgres} starts. */
|
|
2
|
+
export interface UnansweringPostgres {
|
|
3
|
+
/** A connection string for it. */
|
|
4
|
+
url: string;
|
|
5
|
+
/** How many connections it has accepted, which shows a client really reached it. */
|
|
6
|
+
connections(): number;
|
|
7
|
+
/** Drop every connection and stop listening. */
|
|
8
|
+
close(): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
/** Start a server that answers as `mode` says, on a free port. */
|
|
11
|
+
export declare function unansweringPostgres(mode: "silent" | "after-handshake"): Promise<UnansweringPostgres>;
|
package/dist/dev-db/attver.d.ts
CHANGED
|
@@ -1,11 +1,43 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A TOC entry's definition
|
|
3
|
-
*
|
|
2
|
+
* A TOC entry's definition, as the bytes pg_dump wrote, without its
|
|
3
|
+
* `pg_attver` options: what was taken out is spaces, and every other byte is
|
|
4
|
+
* as it was. Matched one character per byte (`latin1`), which finds the ASCII
|
|
5
|
+
* statement in any ASCII-safe encoding without decoding anything else.
|
|
4
6
|
*/
|
|
5
|
-
export declare function blankAttverOptions(definition:
|
|
7
|
+
export declare function blankAttverOptions(definition: Buffer): Buffer;
|
|
8
|
+
/** What {@link stripAttverFromArchive} did to a dump. */
|
|
9
|
+
export interface AttverStrip {
|
|
10
|
+
/** How many TOC entries had their `pg_attver` options blanked. */
|
|
11
|
+
entries: number;
|
|
12
|
+
/**
|
|
13
|
+
* Why the dump was left exactly as it was, when it could not be read or
|
|
14
|
+
* edited safely; null when it was read through. A skipped dump that holds
|
|
15
|
+
* `pg_attver` options fails to restore on a server without the change.
|
|
16
|
+
*/
|
|
17
|
+
skipped: string | null;
|
|
18
|
+
/** The source server's version, as the archive's header records it; null when it was not read. */
|
|
19
|
+
serverVersion: string | null;
|
|
20
|
+
/** The version of the pg_dump that wrote the archive, from its header; null when it was not read. */
|
|
21
|
+
dumpVersion: string | null;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The encoding a custom-format dump is written in, as its ENCODING entry
|
|
25
|
+
* names it (`LATIN1`, `UTF8`, …), or null when this cannot read the file as
|
|
26
|
+
* an archive.
|
|
27
|
+
*
|
|
28
|
+
* That entry is the `SET client_encoding` pg_restore starts every restore
|
|
29
|
+
* with: the source database's encoding, unless pg_dump ran with
|
|
30
|
+
* `PGCLIENTENCODING` naming another. The file is opened read-only and nothing
|
|
31
|
+
* in it changes.
|
|
32
|
+
*/
|
|
33
|
+
export declare function archiveEncoding(dumpFile: string): string | null;
|
|
6
34
|
/**
|
|
7
35
|
* Blank every `pg_attver` attribute option in a custom-format dump, in place.
|
|
8
|
-
*
|
|
9
|
-
* recognise,
|
|
36
|
+
*
|
|
37
|
+
* A file this does not recognise, or cannot edit safely, is left byte for
|
|
38
|
+
* byte as it was — pg_restore then reads it as it is — and the result says
|
|
39
|
+
* why. `blank` is the edit made to each table's definition: the pull always
|
|
40
|
+
* uses the default, {@link blankAttverOptions}; it is a parameter so that the
|
|
41
|
+
* guard against an edit that changes a definition's length can be tested.
|
|
10
42
|
*/
|
|
11
|
-
export declare function stripAttverFromArchive(dumpFile: string):
|
|
43
|
+
export declare function stripAttverFromArchive(dumpFile: string, blank?: (definition: Buffer) => Buffer): AttverStrip;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How long `rebase db pull` waits on the local database before it stops
|
|
3
|
+
* waiting and says so.
|
|
4
|
+
*
|
|
5
|
+
* The managed database can stop answering without refusing anything. Its
|
|
6
|
+
* daemon accepts the socket and never finishes the start-up handshake, or
|
|
7
|
+
* finishes it and never answers a query. A pull from a LATIN1 database did
|
|
8
|
+
* exactly that: pg_restore's `SET client_encoding = 'LATIN1'` left the daemon
|
|
9
|
+
* answering nobody, and the re-grant that followed opened a connection with
|
|
10
|
+
* no bound. The pull then hung for good, after it had already emptied the local
|
|
11
|
+
* database and before it printed the failure it had already computed.
|
|
12
|
+
*
|
|
13
|
+
* Every connection a pull opens to the local database takes
|
|
14
|
+
* {@link LOCAL_CONNECT_TIMEOUT_MS}. A connection whose statements are all short
|
|
15
|
+
* also takes {@link LOCAL_QUERY_TIMEOUT_MS}: catalog reads, `RESET`, grants.
|
|
16
|
+
* A connection that rewrites whole tables does not take it, because those
|
|
17
|
+
* statements run as long as the tables are big.
|
|
18
|
+
*
|
|
19
|
+
* These live in their own module so that a test can shorten them for every
|
|
20
|
+
* caller at once.
|
|
21
|
+
*/
|
|
22
|
+
/** The connection, start-up handshake included: a wedged daemon accepts the socket and never answers. */
|
|
23
|
+
export declare const LOCAL_CONNECT_TIMEOUT_MS = 10000;
|
|
24
|
+
/** One short statement: a catalog read, a `RESET`, a `GRANT`. */
|
|
25
|
+
export declare const LOCAL_QUERY_TIMEOUT_MS = 15000;
|
package/dist/dev-db/pull.d.ts
CHANGED
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
* tables it would have rewritten rather than leave their real values behind.
|
|
35
35
|
*/
|
|
36
36
|
import type { Client } from "pg";
|
|
37
|
+
import { type AttverStrip } from "./attver.js";
|
|
37
38
|
/**
|
|
38
39
|
* How one kind of personal-looking column is overwritten.
|
|
39
40
|
*
|
|
@@ -209,12 +210,14 @@ export declare function describeTarget(connectionString: string): string;
|
|
|
209
210
|
* What the local database runs on.
|
|
210
211
|
*
|
|
211
212
|
* `pglite` is the managed development database: one PGlite session behind a
|
|
212
|
-
* socket server.
|
|
213
|
-
* each protocol message on its own, so the `CopyData` that follows a
|
|
214
|
-
* FROM stdin` never reaches the backend waiting for it: the COPY fails
|
|
215
|
-
* "unexpected EOF", and the session stops answering anyone until the daemon
|
|
216
|
-
* is killed.
|
|
217
|
-
*
|
|
213
|
+
* socket server. Three things a restore relies on are not there. The server
|
|
214
|
+
* runs each protocol message on its own, so the `CopyData` that follows a
|
|
215
|
+
* `COPY … FROM stdin` never reaches the backend waiting for it: the COPY fails
|
|
216
|
+
* on "unexpected EOF", and the session stops answering anyone until the daemon
|
|
217
|
+
* is killed. It cannot convert between encodings, so a dump in any encoding
|
|
218
|
+
* but UTF8 does the same at its first statement (see {@link encodingRefusal}).
|
|
219
|
+
* And every connection shares that one session, so what pg_restore `SET`s for
|
|
220
|
+
* itself stays set for everyone after it disconnects.
|
|
218
221
|
*/
|
|
219
222
|
export type PullTargetEngine = "postgres" | "pglite";
|
|
220
223
|
export interface PullPlan {
|
|
@@ -315,6 +318,11 @@ export interface RestoreRunOutcome {
|
|
|
315
318
|
* what finishes the job: everything else repeats until its cause is fixed.
|
|
316
319
|
*/
|
|
317
320
|
advice: string | null;
|
|
321
|
+
/**
|
|
322
|
+
* Something the copy did that is worth one line, whether or not it
|
|
323
|
+
* succeeded — see {@link attverNotice} and {@link transactionTimeoutNotice}.
|
|
324
|
+
*/
|
|
325
|
+
notice?: string;
|
|
318
326
|
}
|
|
319
327
|
/**
|
|
320
328
|
* What a finished `pg_restore` says about the copy.
|
|
@@ -331,8 +339,26 @@ export interface RestoreRunOutcome {
|
|
|
331
339
|
* advice names that, rather than "pull again", which sent people in a loop.
|
|
332
340
|
* On the managed database an extension cannot be installed at all, so the
|
|
333
341
|
* advice there is Postgres in Docker.
|
|
342
|
+
*
|
|
343
|
+
* One cause is named for what it is: a target refusing `pg_attver`, which
|
|
344
|
+
* means the local pg_dump is older than the source server and the dump could
|
|
345
|
+
* not be edited to drop the key (`attver`, what {@link stripAttverFromArchive}
|
|
346
|
+
* said, tells why).
|
|
347
|
+
*
|
|
348
|
+
* One error is known to cost the copy nothing, and does not fail it: a target
|
|
349
|
+
* older than PostgreSQL 17 (`targetMajor`, read from its `version()`) refusing
|
|
350
|
+
* the `SET transaction_timeout` a pg_dump 17 or newer writes at the top of
|
|
351
|
+
* every dump — see {@link onlyTransactionTimeoutRefused}. Only when it is the
|
|
352
|
+
* one kind of error in the run; the copy is then complete, and the outcome
|
|
353
|
+
* carries a notice saying why pg_restore's error was harmless.
|
|
334
354
|
*/
|
|
335
|
-
export declare function restoreOutcome(run: RestoreRun, engine?: PullTargetEngine): RestoreRunOutcome;
|
|
355
|
+
export declare function restoreOutcome(run: RestoreRun, engine?: PullTargetEngine, attver?: AttverStrip | null, targetMajor?: number | null): RestoreRunOutcome;
|
|
356
|
+
/**
|
|
357
|
+
* The line a pull prints when it took `pg_attver` out of the dump: the copy is
|
|
358
|
+
* whole, but the local pg_dump is older than the source server, which is what
|
|
359
|
+
* to fix. Null when nothing was taken out.
|
|
360
|
+
*/
|
|
361
|
+
export declare function attverNotice(attver: AttverStrip): string | null;
|
|
336
362
|
/** How {@link restoreCopy} ended. */
|
|
337
363
|
export interface RestoreOutcome extends RestoreRunOutcome {
|
|
338
364
|
/** Whether the local database was emptied first. False means it is exactly as it was. */
|
|
@@ -358,6 +384,19 @@ export declare function schemasToClear(present: readonly {
|
|
|
358
384
|
* `public` and every table in it would otherwise have nowhere to go.
|
|
359
385
|
*/
|
|
360
386
|
export declare function clearStatements(schemas: readonly string[]): string[];
|
|
387
|
+
/**
|
|
388
|
+
* Why the local database cannot take a dump written in `encoding`, or null
|
|
389
|
+
* when it can.
|
|
390
|
+
*
|
|
391
|
+
* Only the managed database refuses one. A Postgres target converts any
|
|
392
|
+
* encoding to its own as pg_restore writes, which is how a LATIN1 source has
|
|
393
|
+
* always pulled into Postgres in Docker. `encoding` is what
|
|
394
|
+
* {@link archiveEncoding} read from the dump's ENCODING entry. Null means the
|
|
395
|
+
* dump could not be read, and pg_restore is left to say what it makes of it,
|
|
396
|
+
* as before. {@link restoreCopy} asks this before it empties anything, so the
|
|
397
|
+
* outcome says the database is as it was.
|
|
398
|
+
*/
|
|
399
|
+
export declare function encodingRefusal(engine: PullTargetEngine, encoding: string | null): RestoreOutcome | null;
|
|
361
400
|
/**
|
|
362
401
|
* Replace the local database's contents with a dump: empty the schemas it
|
|
363
402
|
* holds, then `pg_restore` into them.
|
|
@@ -368,8 +407,9 @@ export declare function clearStatements(schemas: readonly string[]): string[];
|
|
|
368
407
|
* restored, and the database is as it was.
|
|
369
408
|
*
|
|
370
409
|
* On the managed database the dump must be one {@link dumpSource} took for it,
|
|
371
|
-
* with its rows as INSERTs
|
|
372
|
-
*
|
|
410
|
+
* with its rows as INSERTs, and written in UTF8: a COPY, or any other
|
|
411
|
+
* encoding, would leave the daemon answering nobody, so either is refused
|
|
412
|
+
* before anything is emptied. And afterwards its one session —
|
|
373
413
|
* every connection's — is given back its own settings: pg_restore leaves
|
|
374
414
|
* `search_path` empty and `row_security` off behind it, which a running
|
|
375
415
|
* `rebase dev` would otherwise query under.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import { d as readEnvFile } from "./project-
|
|
2
|
+
import { d as readEnvFile } from "./project-DALmhb5R.js";
|
|
3
3
|
import { t as Refusal } from "./refusal-ReeeGP8a.js";
|
|
4
4
|
import chalk from "chalk";
|
|
5
5
|
import fs from "fs";
|
|
@@ -726,4 +726,4 @@ async function ensureDevDatabase(options) {
|
|
|
726
726
|
//#endregion
|
|
727
727
|
export { parseLoopbackDsn as a, ensureDevDatabase as i, dev_preflight_exports as n, probeTcp as o, dockerClaimedPorts as r, composeDatabaseUrl as t };
|
|
728
728
|
|
|
729
|
-
//# sourceMappingURL=dev-preflight-
|
|
729
|
+
//# sourceMappingURL=dev-preflight-BMOf2N6r.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-preflight-DjvcV6SK.js","names":[],"sources":["../src/utils/dev-preflight.ts"],"sourcesContent":["/**\n * Make `rebase dev` the only command a new project needs.\n *\n * The scaffolded project prints three steps — start the database container,\n * push the schema, start the dev server — and a first-time reader has to\n * perform all three correctly before anything works. Two of them are\n * mechanical, and both fail in ways that do not name themselves: skipping the\n * container gives `ECONNREFUSED` from a stack the reader has never seen, and\n * skipping the push gives a server that starts cleanly and then 500s on the\n * first request because the tables are not there.\n *\n * So `dev` does them. Not always, and not silently — under four conditions that\n * together mean \"this is a throwaway development database on this laptop, and\n * it is not running\":\n *\n * 1. The DSN resolves to a loopback address. A remote database is somebody's\n * real data and is never touched here, whatever else is true.\n * 2. Nothing is listening on it. A database that answers is left completely\n * alone — no push, no inspection, no connection.\n * 3. The project has a `docker-compose.yml` declaring a `db` service, i.e.\n * the one `rebase init` wrote. Without it there is nothing to start and\n * the backend's own error is the better message.\n * 4. Docker is available. If it is not, the manual steps are printed and dev\n * continues — a preflight must never be the reason the command fails.\n *\n * The schema push happens only when this function actually started the\n * container, which is the one moment a local database is known to be new or\n * stale relative to the tables. A `dev` against an already-running\n * database never mutates its schema.\n *\n * One case stops the command instead of stepping aside: the URL is this\n * project's compose database, and Docker says what answers on its port is\n * somebody else's. Carrying on would connect this project to that database,\n * and the best case is a failed login whose advice (\"ALTER USER …\") is for the\n * wrong one. See {@link classifyPortPublishers}.\n */\nimport fs from \"fs\";\nimport net from \"net\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { execa, ExecaError } from \"execa\";\n\nimport { readEnvFile } from \"./project\";\nimport { Refusal } from \"./refusal\";\n\n/** Where the preflight stopped, and why. Returned so tests can assert it. */\nexport type PreflightOutcome =\n | { action: \"disabled\" }\n | { action: \"no-dsn\" }\n | { action: \"remote-dsn\"; host: string }\n | { action: \"already-running\"; host: string; port: number }\n | { action: \"no-compose\" }\n | { action: \"no-docker\"; hint: string }\n | { action: \"start-failed\"; hint: string }\n | { action: \"wrong-port\"; hint: string; port: number; composePort: number }\n | { action: \"started\"; port: number; pushed: boolean };\n\n/**\n * Hosts that mean \"this machine\", and so may be provisioned automatically.\n *\n * An exact-match set, never a prefix or substring test: `localhost.example.com`\n * is a perfectly resolvable name that somebody else controls.\n */\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"::1\", \"0.0.0.0\"]);\n\n/**\n * The host and port of a Postgres DSN, but only when it points at this machine.\n *\n * Returns null for anything else — a remote host, an unparseable string, a\n * non-postgres scheme. Callers treat null as \"do nothing\", so every parse\n * failure fails closed onto the safe behaviour rather than onto a guess.\n */\nexport function parseLoopbackDsn(dsn: string | undefined): { host: string; port: number } | null {\n if (!dsn) return null;\n\n let url: URL;\n try {\n url = new URL(dsn);\n } catch {\n return null;\n }\n\n if (!/^postgres(ql)?:$/.test(url.protocol)) return null;\n\n // `url.hostname` KEEPS the brackets an IPv6 literal carries in a URL, and\n // `net.connect` rejects them. Normalising here rather than at each use is\n // what stops the two representations diverging: everything downstream gets\n // a host it can dial.\n const host = url.hostname.replace(/^\\[(.+)\\]$/, \"$1\");\n if (!LOOPBACK.has(host)) return null;\n\n const port = url.port ? Number(url.port) : 5432;\n if (!Number.isInteger(port) || port <= 0 || port > 65535) return null;\n\n return { host, port };\n}\n\n/**\n * Whether a compose file declares a `db` service.\n *\n * Deliberately a text scan and not a YAML parse: the CLI has no YAML\n * dependency, and the question is only ever asked of a file this tool wrote.\n * A false negative costs the automation and nothing else — the reader gets the\n * manual steps, which are correct.\n */\nexport function composeDeclaresDbService(yamlText: string): boolean {\n let inServices = false;\n for (const rawLine of yamlText.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\t/g, \" \");\n if (/^\\s*#/.test(line) || line.trim() === \"\") continue;\n\n if (/^services:\\s*$/.test(line)) {\n inServices = true;\n continue;\n }\n // Any other zero-indent key ends the services block.\n if (inServices && /^\\S/.test(line)) {\n inServices = false;\n continue;\n }\n if (inServices && /^\\s{2,}db:\\s*$/.test(line)) return true;\n }\n return false;\n}\n\n/**\n * The connection string the compose file's `db` service will answer on.\n *\n * `--docker` used to be a flag that changed a banner and nothing else: it\n * resolved to `kind: \"docker\"`, and every caller then had no URL to reach the\n * container with, so the backend booted with no `DATABASE_URL` at all and died\n * on the message a project with no database gets. The container it had just\n * been asked for was never started, because the preflight that starts it needs\n * a DSN to decide the database is local and not running.\n *\n * So the URL is derived rather than required: the compose file names the user,\n * the database and the published host port, and `.env` holds the password\n * compose itself interpolates. That is the same string `rebase init` writes as\n * the commented-out `DATABASE_URL`, which is what makes uncommenting that line\n * and passing `--docker` reach the same database.\n *\n * Returns null when the file declares no `db` service, or declares one this\n * scan cannot read — a `--docker` that cannot be honoured has to say so, and\n * a guess would point at somebody else's Postgres on 5432.\n *\n * Same text scan as {@link composeDeclaresDbService}, for the same reason.\n */\nexport function composeDatabaseUrl(\n yamlText: string,\n env: Record<string, string | undefined> = {}\n): string | null {\n const found = scanComposeDbService(yamlText);\n\n const user = expandComposeValue(found.POSTGRES_USER, env);\n const password = expandComposeValue(found.POSTGRES_PASSWORD, env);\n const database = expandComposeValue(found.POSTGRES_DB, env);\n if (!user || !password || !database || !found.hostPort) return null;\n\n return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}` +\n `@127.0.0.1:${found.hostPort}/${database}?options=-c%20search_path%3Dpublic&sslmode=disable`;\n}\n\n/**\n * The host port the compose `db` service publishes, or null.\n *\n * Separate from {@link composeDatabaseUrl} because the port is answerable on\n * its own: the URL needs the user, the password and the database name too, and\n * a compose file missing any of them still says which port a container would\n * listen on. That is the question \"would starting this container answer the\n * DSN in `.env`?\" — see the `wrong-port` branch of {@link ensureDevDatabase},\n * where getting it wrong meant starting a container nobody asked for.\n */\nexport function composeHostPort(yamlText: string): number | null {\n const port = scanComposeDbService(yamlText).hostPort;\n\n return port ? Number(port) : null;\n}\n\n/** The raw values of the compose `db` service, before any expansion. */\nfunction scanComposeDbService(yamlText: string): Record<string, string> & { hostPort?: string } {\n let inServices = false;\n let inDb = false;\n let dbIndent = 0;\n let section: \"environment\" | \"ports\" | null = null;\n const found: Record<string, string> = {};\n let hostPort: string | null = null;\n\n for (const rawLine of yamlText.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\t/g, \" \");\n if (/^\\s*#/.test(line) || line.trim() === \"\") continue;\n\n if (/^services:\\s*$/.test(line)) { inServices = true; continue; }\n if (inServices && /^\\S/.test(line)) { inServices = false; inDb = false; continue; }\n if (!inServices) continue;\n\n const indent = line.length - line.trimStart().length;\n const dbHeader = line.match(/^(\\s{2,})db:\\s*$/);\n if (dbHeader) { inDb = true; dbIndent = dbHeader[1].length; section = null; continue; }\n // A sibling service at the same indent as `db:` ends it.\n if (inDb && indent <= dbIndent) { inDb = false; section = null; continue; }\n if (!inDb) continue;\n\n const key = line.match(/^\\s+(environment|ports):\\s*$/);\n if (key) { section = key[1] as \"environment\" | \"ports\"; continue; }\n // Any other key of the service ends the block we were reading.\n if (/^\\s+[A-Za-z_][\\w-]*:\\s*\\S/.test(line) && !/^\\s+POSTGRES_/.test(line)) {\n if (!/^\\s*-\\s/.test(line.trimStart())) section = null;\n }\n\n if (section === \"environment\") {\n const pair = line.match(/^\\s+(POSTGRES_(?:USER|PASSWORD|DB)):\\s*(.+?)\\s*$/);\n if (pair) found[pair[1]] = pair[2].replace(/^[\"']|[\"']$/g, \"\");\n continue;\n }\n\n if (section === \"ports\" && hostPort === null) {\n // `- \"5435:5432\"`. Only a mapping whose container side is Postgres's\n // own port is the one to dial; anything else is a different service.\n const mapping = line.match(/^\\s*-\\s*[\"']?(?:[\\d.]+:)?(\\d+):5432(?:\\/tcp)?[\"']?\\s*$/);\n if (mapping) hostPort = mapping[1];\n }\n }\n\n return hostPort === null ? found : { ...found, hostPort };\n}\n\n/**\n * `${VAR:-default}`, `${VAR}` and a literal, resolved the way compose resolves\n * them — against the project's `.env`, which is the file compose itself reads.\n */\nfunction expandComposeValue(\n raw: string | undefined,\n env: Record<string, string | undefined>\n): string | null {\n if (!raw) return null;\n const interpolated = raw.replace(/\\$\\{([A-Za-z_][\\w]*)(?::?-([^}]*))?\\}/g, (_all, name, fallback) => {\n const value = env[name];\n if (value !== undefined && value !== \"\") return value;\n return fallback ?? \"\";\n });\n const trimmed = interpolated.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\n/**\n * Is something accepting connections there right now?\n *\n * A reset counts as yes: a refused connection means nothing listens, a reset\n * means something accepted it and dropped it — Docker's port proxy, while the\n * Postgres behind it is still starting. On macOS that reset arrives after\n * `connect`; on Linux it can arrive instead of it, and read as \"not listening\"\n * the port wait spun for its whole minute before readiness was ever asked.\n */\nexport function probeTcp(host: string, port: number, timeoutMs = 700): Promise<boolean> {\n return new Promise(resolve => {\n const socket = new net.Socket();\n let settled = false;\n\n const done = (open: boolean): void => {\n if (settled) return;\n settled = true;\n socket.destroy();\n resolve(open);\n };\n\n socket.setTimeout(timeoutMs);\n socket.once(\"connect\", () => done(true));\n socket.once(\"timeout\", () => done(false));\n socket.once(\"error\", (error: Error) => done(\"code\" in error && error.code === \"ECONNRESET\"));\n socket.connect(port, host);\n });\n}\n\n/**\n * Poll until the port answers, or give up.\n *\n * This only answers \"has the container got as far as listening\". It is not\n * readiness: Docker's port proxy accepts on the host port while Postgres inside\n * the container is still running initdb, and resets every connection it cannot\n * forward. {@link waitForQueryable} is the check that a query will work.\n */\nexport async function waitForPort(\n host: string,\n port: number,\n timeoutMs = 60_000,\n intervalMs = 500\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await probeTcp(host, port, 700)) return true;\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n }\n return false;\n}\n\n/**\n * Whether a database answered a query, and if not, the last reason it gave —\n * and, for a database closed to new connections, its name.\n */\nexport type QueryReadiness = { ready: true } | { ready: false; error: string; closedDatabase?: string };\n\n/** What opening a closed database again did, and what to say about it. */\nexport interface ClosedDatabaseHeal {\n /** It accepts connections again. */\n reopened: boolean;\n /** The driver's own lines about it (`reopenedDatabasesNotice`). */\n notice: string[];\n}\n\n/**\n * The database a connection was refused by because it is closed to new\n * connections (`ALLOW_CONNECTIONS false`), or null.\n *\n * The driver's `closedDatabaseName`, for the error a bare `pg` connect gives:\n * the sentence is matched, not SQLSTATE 55000, which also covers failures that\n * have nothing to do with connecting.\n */\nexport function closedDatabaseName(error: unknown): string | null {\n if (!error || typeof error !== \"object\") return null;\n if (\"message\" in error && typeof error.message === \"string\") {\n const named = /database \"(.+)\" is not currently accepting connections/.exec(error.message);\n if (named) return named[1];\n }\n return \"cause\" in error ? closedDatabaseName(error.cause) : null;\n}\n\n/** Open `databaseUrl`'s database again with the driver, as every `rebase db branch` command does first. */\nasync function reopenWithDriver(databaseUrl: string): Promise<ClosedDatabaseHeal> {\n const { reopenClosedDatabases, reopenedDatabasesNotice } = await import(\"@rebasepro/server-postgres\");\n const result = await reopenClosedDatabases(databaseUrl);\n return { reopened: result.reopened.length > 0, notice: reopenedDatabasesNotice(result) };\n}\n\n/**\n * Poll until `SELECT 1` succeeds on this connection string, or the bound runs out.\n *\n * The readiness that matters to everything after it. A fresh compose volume\n * answers the TCP probe seconds before it answers a query — the official image\n * runs initdb on a socket-only server, then restarts on TCP — and the schema\n * push that ran in that gap failed on `read ECONNRESET`, three runs out of\n * three. Every error is retried: a reset, \"the database system is starting up\"\n * and a refused connection all mean \"not yet\", and the bound is what turns\n * \"not yet\" into an answer.\n *\n * Except one, which is not \"not yet\": a database closed to new connections\n * (`closedDatabaseName`), which is what a `rebase db branch create --force`\n * killed mid-copy leaves its source as. Waiting cannot open it, and it was\n * waited on for the whole minute. It is opened again with the driver's\n * `reopenClosedDatabases`, once, and then either answers or the wait ends at\n * once, naming it.\n */\nexport async function waitForQueryable(\n databaseUrl: string,\n options: {\n timeoutMs?: number;\n intervalMs?: number;\n /** Opens a closed database again. The driver's `reopenClosedDatabases` by default; injected for tests. */\n reopenClosed?: (databaseUrl: string) => Promise<ClosedDatabaseHeal>;\n /** Where the driver's lines about a database it opened go. */\n onNotice?: (line: string) => void;\n } = {}\n): Promise<QueryReadiness> {\n const { timeoutMs = 60_000, intervalMs = 500 } = options;\n const { Client } = await import(\"pg\");\n const deadline = Date.now() + timeoutMs;\n let lastError = \"no attempt was made\";\n let healed = false;\n\n do {\n const client = new Client({\n connectionString: databaseUrl,\n connectionTimeoutMillis: Math.max(250, Math.min(2_000, deadline - Date.now()))\n });\n // A reset can arrive after `connect` settles; unhandled, it would take\n // the process down rather than count as one more \"not yet\".\n client.on(\"error\", () => undefined);\n let closed: string | null = null;\n try {\n await client.connect();\n await client.query(\"SELECT 1\");\n return { ready: true };\n } catch (error) {\n lastError = error instanceof Error && error.message ? error.message : String(error);\n closed = closedDatabaseName(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n if (closed !== null) {\n if (healed) return { ready: false, error: lastError, closedDatabase: closed };\n healed = true;\n const heal = await (options.reopenClosed ?? reopenWithDriver)(databaseUrl).catch(() => ({ reopened: false, notice: [] }));\n for (const line of heal.notice) options.onNotice?.(line);\n if (!heal.reopened) return { ready: false, error: lastError, closedDatabase: closed };\n // Open again: ask straight away rather than after the interval.\n continue;\n }\n if (Date.now() + intervalMs >= deadline) break;\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n } while (Date.now() < deadline);\n\n return { ready: false, error: lastError };\n}\n\n/**\n * What a failed schema push printed, as lines to show.\n *\n * `rebase dev` runs the push with its output captured, so a successful start\n * stays quiet. On a failure that captured output is the diagnosis, and it was\n * being dropped: the warning said \"fix the error above\" over nothing at all.\n * The child's stdout and stderr are what is shown — not execa's own message,\n * which leads with the command line, and that carries the database password.\n */\nexport function pushFailureOutput(error: unknown): string[] {\n if (error instanceof ExecaError) {\n const captured = [streamText(error.stdout), streamText(error.stderr)]\n .map(stream => stream.trim())\n .filter(stream => stream.length > 0);\n if (captured.length > 0) return captured.join(\"\\n\").split(/\\r?\\n/);\n return [error.originalMessage || `The push exited with code ${error.exitCode ?? \"unknown\"}.`];\n }\n return [error instanceof Error ? error.message : String(error)];\n}\n\n/** A captured stream as text, whichever form execa's options gave it. */\nfunction streamText(stream: unknown): string {\n if (typeof stream === \"string\") return stream;\n if (stream instanceof Uint8Array) return Buffer.from(stream).toString(\"utf8\");\n if (Array.isArray(stream)) return stream.map(String).join(\"\\n\");\n return \"\";\n}\n\n/** The user and password the compose `db` service creates, expanded against `.env`. */\nfunction composeCredentials(\n yamlText: string,\n env: Record<string, string | undefined>\n): { user: string; password: string } | null {\n const found = scanComposeDbService(yamlText);\n const user = expandComposeValue(found.POSTGRES_USER, env);\n const password = expandComposeValue(found.POSTGRES_PASSWORD, env);\n return user && password ? { user, password } : null;\n}\n\n/**\n * The compose project a file belongs to, named the way `docker compose` names\n * it: the file's top-level `name:`, else the directory, lowercased with\n * everything but `[a-z0-9_-]` dropped.\n *\n * A project name set with `-p` or in the environment is not read: a container\n * started from this directory is recognised by its working directory anyway,\n * and the name is only the fallback for a project that has moved since.\n */\nexport function composeProjectName(yamlText: string, projectRoot: string): string {\n const named = /^name:\\s*[\"']?([^\"'#\\s]+)[\"']?\\s*(?:#.*)?$/m.exec(yamlText)?.[1];\n const raw = named || path.basename(projectRoot);\n return raw.toLowerCase().replace(/[^a-z0-9_-]/g, \"\");\n}\n\n/** Who answers on a host port, as far as Docker can say. */\nexport type PortHolder =\n | { kind: \"this-project\" }\n | { kind: \"container\"; name: string; project?: string; directory?: string }\n | { kind: \"outside-docker\" }\n | { kind: \"unknown\" };\n\n/** One `docker ps` row per container publishing the port: name, then its compose labels. */\nconst PUBLISHER_FORMAT = [\n \"{{.Names}}\",\n \"{{.Label \\\"com.docker.compose.project\\\"}}\",\n \"{{.Label \\\"com.docker.compose.project.working_dir\\\"}}\",\n \"{{.Label \\\"com.docker.compose.service\\\"}}\"\n].join(\"\\t\");\n\n/**\n * Whose container `docker ps --filter publish=<port>` listed, from its rows.\n *\n * This project's when one of them is a `db` service of this compose project:\n * started from this directory, or carrying the project's name (compose treats\n * two directories with one `name:` as one project, so this does too). Any other\n * container is named. No rows at all, from a Docker that answered, means the\n * listener is not a container: a Postgres installed on this machine, say.\n */\nexport function classifyPortPublishers(output: string, projectRoot: string, composeProject: string | null): PortHolder {\n const rows = output.split(/\\r?\\n/)\n .map(line => line.split(\"\\t\").map(field => field.trim()))\n .filter(([name]) => Boolean(name));\n if (rows.length === 0) return { kind: \"outside-docker\" };\n\n const here = canonicalPath(projectRoot);\n for (const [, project, directory, service] of rows) {\n if (service !== \"db\") continue;\n if ((directory && canonicalPath(directory) === here) || (composeProject && project === composeProject)) {\n return { kind: \"this-project\" };\n }\n }\n const [name, project, directory] = rows[0];\n return { kind: \"container\", name, ...(project ? { project } : {}), ...(directory ? { directory } : {}) };\n}\n\nfunction canonicalPath(dir: string): string {\n try {\n return fs.realpathSync(dir);\n } catch {\n return path.resolve(dir);\n }\n}\n\n/** Ask Docker who publishes `port`. `unknown` when Docker cannot be asked. */\nexport async function dockerPortHolder(projectRoot: string, composeProject: string | null, port: number): Promise<PortHolder> {\n try {\n const { stdout } = await execa(\"docker\", [\"ps\", \"--filter\", `publish=${port}`, \"--format\", PUBLISHER_FORMAT], {\n stdio: \"pipe\",\n timeout: 5_000\n });\n return classifyPortPublishers(stdout, projectRoot, composeProject);\n } catch {\n return { kind: \"unknown\" };\n }\n}\n\n/**\n * Every host port in a list of `docker inspect --format '{{json .HostConfig.PortBindings}}'` lines.\n *\n * The configured bindings, which a stopped container keeps: it takes its port\n * back the moment it starts, so the port is not free to give to a new project.\n * `HostPort: \"0\"` asks for any free port and claims none.\n */\nexport function parsePortBindings(output: string): Set<number> {\n const ports = new Set<number>();\n for (const line of output.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n continue;\n }\n if (!parsed || typeof parsed !== \"object\") continue;\n const bindingLists: unknown[] = Object.values(parsed);\n for (const bindings of bindingLists) {\n if (!Array.isArray(bindings)) continue;\n for (const binding of bindings) {\n if (!binding || typeof binding !== \"object\" || !(\"HostPort\" in binding)) continue;\n const hostPort = Number(binding.HostPort);\n if (Number.isInteger(hostPort) && hostPort > 0 && hostPort < 65536) ports.add(hostPort);\n }\n }\n }\n return ports;\n}\n\n/**\n * The host ports every container on this machine is bound to, running or\n * stopped — `null` when Docker cannot be asked.\n *\n * A TCP probe sees only what is listening now, and a stopped project's `db`\n * container is not; `docker ps` shows a stopped container's ports only\n * sometimes. The bindings in its config are what it will take back.\n */\nexport async function dockerClaimedPorts(): Promise<Set<number> | null> {\n try {\n const { stdout: ids } = await execa(\"docker\", [\"ps\", \"-aq\"], { stdio: \"pipe\", timeout: 5_000 });\n const containers = ids.split(/\\s+/).filter(Boolean);\n if (containers.length === 0) return new Set();\n // `reject: false`: a container removed since `ps` fails its own entry and\n // exits 1, and every other container's bindings are still on stdout.\n const { stdout } = await execa(\"docker\", [\"inspect\", \"--format\", \"{{json .HostConfig.PortBindings}}\", ...containers], {\n stdio: \"pipe\",\n timeout: 10_000,\n reject: false\n });\n return parsePortBindings(stdout);\n } catch {\n return null;\n }\n}\n\n/**\n * Whether `databaseUrl` is this project's compose database: the port the `db`\n * service publishes, with the user and password it creates.\n *\n * The credentials matter. One Postgres container shared by several projects is\n * an ordinary setup, and such a URL names that container's password — a\n * database somebody chose, which is theirs to point at.\n */\nfunction isComposeDatabaseUrl(databaseUrl: string, port: number, composeText: string, env: Record<string, string | undefined>): boolean {\n if (composeHostPort(composeText) !== port) return false;\n const credentials = composeCredentials(composeText, env);\n if (!credentials) return false;\n try {\n const url = new URL(databaseUrl);\n return decodeURIComponent(url.username) === credentials.user\n && decodeURIComponent(url.password) === credentials.password;\n } catch {\n return false;\n }\n}\n\n/** The first port after `port` that nothing on loopback answers on, for a suggestion. */\nasync function nextQuietPort(port: number): Promise<number | null> {\n for (let candidate = port + 1; candidate < Math.min(port + 50, 65536); candidate++) {\n if (!(await probeTcp(\"127.0.0.1\", candidate, 300))) return candidate;\n }\n return null;\n}\n\n/**\n * Said, then thrown: the compose port answers, and not with this project's\n * database. Returns quietly when the listener is ours, or when Docker cannot\n * say — the behaviour from before this check.\n */\nasync function refuseForeignListener(options: {\n projectRoot: string;\n databaseUrl: string;\n port: number;\n composeText: string;\n whoHoldsPort?: (port: number) => Promise<PortHolder>;\n log: (message: string) => void;\n}): Promise<void> {\n const { projectRoot, databaseUrl, port, composeText, log } = options;\n const env = readEnvFile(projectRoot);\n if (!isComposeDatabaseUrl(databaseUrl, port, composeText, env)) return;\n\n const whoHoldsPort = options.whoHoldsPort\n ?? ((p: number) => dockerPortHolder(projectRoot, composeProjectName(composeText, projectRoot), p));\n const holder = await whoHoldsPort(port);\n if (holder.kind === \"this-project\" || holder.kind === \"unknown\") return;\n\n const who = holder.kind === \"container\"\n ? `another container is listening there: ${holder.name}`\n + (holder.project || holder.directory\n ? ` (${[holder.project ? `compose project ${holder.project}` : \"\", holder.directory ? `in ${holder.directory}` : \"\"]\n .filter(Boolean).join(\", \")})`\n : \"\")\n : \"something outside Docker is listening there, such as a Postgres installed on this machine\";\n const suggestion = await nextQuietPort(port);\n const envSetsUrl = Boolean(env.DATABASE_URL?.trim());\n\n log(\"\");\n log(` ${chalk.yellow(\"⚠\")} ${chalk.bold(`Port ${port} is not this project's database.`)}`);\n for (const line of [\n `docker-compose.yml publishes this project's db service on ${port}, and ${who}.`,\n \"Nothing was started and nothing connected: a login there fails on this project's password, and the fix that failure suggests is for that database.\",\n `Give this project its own port: change \"${port}:5432\" under db: in docker-compose.yml`\n + ` to ${suggestion ? `a free one, such as \"${suggestion}:5432\"` : \"one nothing else uses\"}`\n + (envSetsUrl ? \", and the port in DATABASE_URL in .env.\" : \".\"),\n holder.kind === \"container\"\n ? `Or stop ${holder.name} first: docker stop ${holder.name}`\n : \"Or stop what is listening on it.\"\n ]) {\n log(` ${chalk.gray(line)}`);\n }\n\n // Said in full above, so a `Refusal`: `bin/rebase.js` adds no stack hint.\n throw new Refusal(\n holder.kind === \"container\"\n ? `Port ${port} belongs to ${holder.name}, not to this project's db service. Nothing was started.`\n : `Port ${port} belongs to a server outside Docker, not to this project's db service. Nothing was started.`\n );\n}\n\nexport interface EnsureDevDatabaseOptions {\n projectRoot: string;\n /** The DSN from the project's env file, if it has one. */\n databaseUrl: string | undefined;\n /** Set by `--no-db` or REBASE_DEV_NO_DB. */\n disabled: boolean;\n /** Whether the project declares tables worth pushing (`backend/schema/index.ts`). */\n hasTables: boolean;\n /** Runs `rebase db push` for this project. Injected so tests need no database. */\n pushSchema: () => Promise<void>;\n /**\n * Brings the compose `db` service up. Injected for the same reason\n * `pushSchema` is: what happens *after* a start — a push that fails without\n * taking the dev server with it — is the part worth asserting, and it was\n * untestable while the only way in was a real `docker compose up`.\n */\n startDatabase?: (projectRoot: string) => Promise<void>;\n /** How long a started database has to answer `SELECT 1`. Defaults to 60s. */\n readyTimeoutMs?: number;\n /** Opens a database closed to new connections again; see `waitForQueryable`. Injected for tests. */\n reopenClosed?: (databaseUrl: string) => Promise<ClosedDatabaseHeal>;\n /**\n * Who answers on the compose port. Asks Docker by default; injected for the\n * same reason `startDatabase` is.\n */\n whoHoldsPort?: (port: number) => Promise<PortHolder>;\n log?: (message: string) => void;\n}\n\n/**\n * Start the project's development database if it is not running, and give it a\n * schema if this call is what started it.\n */\nexport async function ensureDevDatabase(options: EnsureDevDatabaseOptions): Promise<PreflightOutcome> {\n const { projectRoot, databaseUrl, disabled, hasTables, pushSchema } = options;\n const log = options.log ?? ((message: string) => console.log(message));\n\n if (disabled) return { action: \"disabled\" };\n\n const target = parseLoopbackDsn(databaseUrl);\n if (!databaseUrl) return { action: \"no-dsn\" };\n if (!target) {\n // Not an error, and not worth a warning either: pointing DATABASE_URL at\n // a real database is a completely ordinary thing to do, and the only\n // correct response is to keep away from it.\n let host = \"the configured host\";\n try {\n host = new URL(databaseUrl).hostname || host;\n } catch { /* keep the placeholder */ }\n return { action: \"remote-dsn\", host };\n }\n\n const composePath = path.join(projectRoot, \"docker-compose.yml\");\n const composeText = fs.existsSync(composePath) ? fs.readFileSync(composePath, \"utf8\") : null;\n\n if (await probeTcp(target.host, target.port)) {\n // Something answers. Whatever it is stays untouched; but if this URL is\n // the compose database, it has to be the compose container.\n if (composeText !== null) {\n await refuseForeignListener({\n projectRoot,\n databaseUrl,\n port: target.port,\n composeText,\n whoHoldsPort: options.whoHoldsPort,\n log\n });\n }\n return { action: \"already-running\", host: target.host, port: target.port };\n }\n\n if (composeText === null || !composeDeclaresDbService(composeText)) return { action: \"no-compose\" };\n\n const manualSteps =\n `${chalk.cyan(\"docker compose up -d db\")} then ${chalk.cyan(\"rebase db push\")}`;\n\n // Would starting that container answer *this* DSN? A `.env` naming a port\n // the compose file does not publish is the commonest way to get here, and\n // starting the container then told the reader the exact opposite of the\n // truth: `⚠ The database container did not begin listening on port 3139.\n // Run docker compose up -d db then rebase db push to see why.` The\n // container was up and healthy on 5436; the port in `.env` was what was\n // wrong. And a container nobody asked for was left running.\n const composePort = composeHostPort(composeText);\n if (composePort !== null && composePort !== target.port) {\n const hint =\n `DATABASE_URL points at ${target.host}:${target.port} and nothing listens there. `\n + `The compose file's db service publishes ${composePort}, so starting it would not `\n + `answer that URL — nothing was started. Either correct the port in .env, or point `\n + `DATABASE_URL at 127.0.0.1:${composePort}.`;\n log(\"\");\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"wrong-port\", hint, port: target.port, composePort };\n }\n\n log(\"\");\n log(` ${chalk.gray(\"Database not running — starting it…\")}`);\n\n const startDatabase = options.startDatabase ?? (async (root: string) => {\n await execa(\"docker\", [\"compose\", \"up\", \"-d\", \"db\"], { cwd: root, stdio: \"pipe\" });\n });\n\n try {\n await startDatabase(projectRoot);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n // Two very different failures land here and the reader needs to know\n // which: Docker not being installed at all, and Docker being installed\n // but unable to start this container.\n if (/ENOENT|not found|command not found/i.test(message)) {\n const hint = `Docker was not found. Start a Postgres yourself, then run ${manualSteps}.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"no-docker\", hint };\n }\n const hint = `Could not start the database container. Run ${manualSteps} to see why.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n\n if (!(await waitForPort(target.host, target.port))) {\n const hint = `The database container did not begin listening on port ${target.port}. Run ${manualSteps} to see why.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n\n // Listening is not ready. Nothing is pushed into a database that has not\n // yet answered a query; see `waitForQueryable`.\n const readiness = await waitForQueryable(databaseUrl, {\n timeoutMs: options.readyTimeoutMs,\n reopenClosed: options.reopenClosed,\n onNotice: line => log(` ${chalk.yellow(line)}`)\n });\n if (!readiness.ready && readiness.closedDatabase !== undefined) {\n const name = readiness.closedDatabase;\n const hint = `Database \"${name}\" on port ${target.port} is closed to new connections (ALLOW_CONNECTIONS false), `\n + \"and could not be opened again. `rebase db branch create --force` closes its source for the copy, and one \"\n + \"stopped before it finished leaves it closed; nothing in it is lost. Open it with \"\n + `${chalk.cyan(\"rebase db branch list\")} (every rebase db branch command opens it first), or run, connected `\n + `to the server's postgres database: ALTER DATABASE \"${name.replace(/\"/g, '\"\"')}\" ALLOW_CONNECTIONS true;`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n if (!readiness.ready) {\n const seconds = Math.round((options.readyTimeoutMs ?? 60_000) / 1000);\n const hint = `The database container is listening on port ${target.port} but did not answer a query `\n + `within ${seconds}s (${readiness.error}). Run ${chalk.cyan(\"docker compose logs db\")} to see why, `\n + `then ${chalk.cyan(\"rebase db push\")}.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n\n log(` ${chalk.green(\"✓\")} ${chalk.gray(`Database ready on port ${target.port}`)}`);\n\n if (!hasTables) return { action: \"started\", port: target.port, pushed: false };\n\n log(` ${chalk.gray(\"Pushing the schema…\")}`);\n try {\n await pushSchema();\n log(` ${chalk.green(\"✓\")} ${chalk.gray(\"Schema pushed\")}`);\n return { action: \"started\", port: target.port, pushed: true };\n } catch (error) {\n // The push runs with its output captured, so what it printed is shown\n // here, before the line that refers to it. Then the one thing the\n // reader needs next: the server is still starting, and against what.\n for (const line of pushFailureOutput(error)) log(` ${chalk.gray(line)}`);\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(`Schema push failed. The database is running; fix the error above and run ${chalk.cyan(\"rebase db push\")}.`)}`);\n return { action: \"started\", port: target.port, pushed: false };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAa;CAAO;AAAS,CAAC;;;;;;;;AASrE,SAAgB,iBAAiB,KAAgE;CAC7F,IAAI,CAAC,KAAK,OAAO;CAEjB,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,IAAI,GAAG;CACrB,QAAQ;EACJ,OAAO;CACX;CAEA,IAAI,CAAC,mBAAmB,KAAK,IAAI,QAAQ,GAAG,OAAO;CAMnD,MAAM,OAAO,IAAI,SAAS,QAAQ,cAAc,IAAI;CACpD,IAAI,CAAC,SAAS,IAAI,IAAI,GAAG,OAAO;CAEhC,MAAM,OAAO,IAAI,OAAO,OAAO,IAAI,IAAI,IAAI;CA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AK,MAAM,OAAO,GAAG,EAAE,GAAG,MAAM,KAAK,4EAA4E,MAAM,KAAK,gBAAgB,EAAE,EAAE,GAAG;EACvJ,OAAO;GAAE,QAAQ;GAAW,MAAM,OAAO;GAAM,QAAQ;EAAM;CACjE;AACJ"}
|
|
1
|
+
{"version":3,"file":"dev-preflight-BMOf2N6r.js","names":[],"sources":["../src/utils/dev-preflight.ts"],"sourcesContent":["/**\n * Make `rebase dev` the only command a new project needs.\n *\n * The scaffolded project prints three steps — start the database container,\n * push the schema, start the dev server — and a first-time reader has to\n * perform all three correctly before anything works. Two of them are\n * mechanical, and both fail in ways that do not name themselves: skipping the\n * container gives `ECONNREFUSED` from a stack the reader has never seen, and\n * skipping the push gives a server that starts cleanly and then 500s on the\n * first request because the tables are not there.\n *\n * So `dev` does them. Not always, and not silently — under four conditions that\n * together mean \"this is a throwaway development database on this laptop, and\n * it is not running\":\n *\n * 1. The DSN resolves to a loopback address. A remote database is somebody's\n * real data and is never touched here, whatever else is true.\n * 2. Nothing is listening on it. A database that answers is left completely\n * alone — no push, no inspection, no connection.\n * 3. The project has a `docker-compose.yml` declaring a `db` service, i.e.\n * the one `rebase init` wrote. Without it there is nothing to start and\n * the backend's own error is the better message.\n * 4. Docker is available. If it is not, the manual steps are printed and dev\n * continues — a preflight must never be the reason the command fails.\n *\n * The schema push happens only when this function actually started the\n * container, which is the one moment a local database is known to be new or\n * stale relative to the tables. A `dev` against an already-running\n * database never mutates its schema.\n *\n * One case stops the command instead of stepping aside: the URL is this\n * project's compose database, and Docker says what answers on its port is\n * somebody else's. Carrying on would connect this project to that database,\n * and the best case is a failed login whose advice (\"ALTER USER …\") is for the\n * wrong one. See {@link classifyPortPublishers}.\n */\nimport fs from \"fs\";\nimport net from \"net\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { execa, ExecaError } from \"execa\";\n\nimport { readEnvFile } from \"./project\";\nimport { Refusal } from \"./refusal\";\n\n/** Where the preflight stopped, and why. Returned so tests can assert it. */\nexport type PreflightOutcome =\n | { action: \"disabled\" }\n | { action: \"no-dsn\" }\n | { action: \"remote-dsn\"; host: string }\n | { action: \"already-running\"; host: string; port: number }\n | { action: \"no-compose\" }\n | { action: \"no-docker\"; hint: string }\n | { action: \"start-failed\"; hint: string }\n | { action: \"wrong-port\"; hint: string; port: number; composePort: number }\n | { action: \"started\"; port: number; pushed: boolean };\n\n/**\n * Hosts that mean \"this machine\", and so may be provisioned automatically.\n *\n * An exact-match set, never a prefix or substring test: `localhost.example.com`\n * is a perfectly resolvable name that somebody else controls.\n */\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"::1\", \"0.0.0.0\"]);\n\n/**\n * The host and port of a Postgres DSN, but only when it points at this machine.\n *\n * Returns null for anything else — a remote host, an unparseable string, a\n * non-postgres scheme. Callers treat null as \"do nothing\", so every parse\n * failure fails closed onto the safe behaviour rather than onto a guess.\n */\nexport function parseLoopbackDsn(dsn: string | undefined): { host: string; port: number } | null {\n if (!dsn) return null;\n\n let url: URL;\n try {\n url = new URL(dsn);\n } catch {\n return null;\n }\n\n if (!/^postgres(ql)?:$/.test(url.protocol)) return null;\n\n // `url.hostname` KEEPS the brackets an IPv6 literal carries in a URL, and\n // `net.connect` rejects them. Normalising here rather than at each use is\n // what stops the two representations diverging: everything downstream gets\n // a host it can dial.\n const host = url.hostname.replace(/^\\[(.+)\\]$/, \"$1\");\n if (!LOOPBACK.has(host)) return null;\n\n const port = url.port ? Number(url.port) : 5432;\n if (!Number.isInteger(port) || port <= 0 || port > 65535) return null;\n\n return { host, port };\n}\n\n/**\n * Whether a compose file declares a `db` service.\n *\n * Deliberately a text scan and not a YAML parse: the CLI has no YAML\n * dependency, and the question is only ever asked of a file this tool wrote.\n * A false negative costs the automation and nothing else — the reader gets the\n * manual steps, which are correct.\n */\nexport function composeDeclaresDbService(yamlText: string): boolean {\n let inServices = false;\n for (const rawLine of yamlText.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\t/g, \" \");\n if (/^\\s*#/.test(line) || line.trim() === \"\") continue;\n\n if (/^services:\\s*$/.test(line)) {\n inServices = true;\n continue;\n }\n // Any other zero-indent key ends the services block.\n if (inServices && /^\\S/.test(line)) {\n inServices = false;\n continue;\n }\n if (inServices && /^\\s{2,}db:\\s*$/.test(line)) return true;\n }\n return false;\n}\n\n/**\n * The connection string the compose file's `db` service will answer on.\n *\n * `--docker` used to be a flag that changed a banner and nothing else: it\n * resolved to `kind: \"docker\"`, and every caller then had no URL to reach the\n * container with, so the backend booted with no `DATABASE_URL` at all and died\n * on the message a project with no database gets. The container it had just\n * been asked for was never started, because the preflight that starts it needs\n * a DSN to decide the database is local and not running.\n *\n * So the URL is derived rather than required: the compose file names the user,\n * the database and the published host port, and `.env` holds the password\n * compose itself interpolates. That is the same string `rebase init` writes as\n * the commented-out `DATABASE_URL`, which is what makes uncommenting that line\n * and passing `--docker` reach the same database.\n *\n * Returns null when the file declares no `db` service, or declares one this\n * scan cannot read — a `--docker` that cannot be honoured has to say so, and\n * a guess would point at somebody else's Postgres on 5432.\n *\n * Same text scan as {@link composeDeclaresDbService}, for the same reason.\n */\nexport function composeDatabaseUrl(\n yamlText: string,\n env: Record<string, string | undefined> = {}\n): string | null {\n const found = scanComposeDbService(yamlText);\n\n const user = expandComposeValue(found.POSTGRES_USER, env);\n const password = expandComposeValue(found.POSTGRES_PASSWORD, env);\n const database = expandComposeValue(found.POSTGRES_DB, env);\n if (!user || !password || !database || !found.hostPort) return null;\n\n return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}` +\n `@127.0.0.1:${found.hostPort}/${database}?options=-c%20search_path%3Dpublic&sslmode=disable`;\n}\n\n/**\n * The host port the compose `db` service publishes, or null.\n *\n * Separate from {@link composeDatabaseUrl} because the port is answerable on\n * its own: the URL needs the user, the password and the database name too, and\n * a compose file missing any of them still says which port a container would\n * listen on. That is the question \"would starting this container answer the\n * DSN in `.env`?\" — see the `wrong-port` branch of {@link ensureDevDatabase},\n * where getting it wrong meant starting a container nobody asked for.\n */\nexport function composeHostPort(yamlText: string): number | null {\n const port = scanComposeDbService(yamlText).hostPort;\n\n return port ? Number(port) : null;\n}\n\n/** The raw values of the compose `db` service, before any expansion. */\nfunction scanComposeDbService(yamlText: string): Record<string, string> & { hostPort?: string } {\n let inServices = false;\n let inDb = false;\n let dbIndent = 0;\n let section: \"environment\" | \"ports\" | null = null;\n const found: Record<string, string> = {};\n let hostPort: string | null = null;\n\n for (const rawLine of yamlText.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\t/g, \" \");\n if (/^\\s*#/.test(line) || line.trim() === \"\") continue;\n\n if (/^services:\\s*$/.test(line)) { inServices = true; continue; }\n if (inServices && /^\\S/.test(line)) { inServices = false; inDb = false; continue; }\n if (!inServices) continue;\n\n const indent = line.length - line.trimStart().length;\n const dbHeader = line.match(/^(\\s{2,})db:\\s*$/);\n if (dbHeader) { inDb = true; dbIndent = dbHeader[1].length; section = null; continue; }\n // A sibling service at the same indent as `db:` ends it.\n if (inDb && indent <= dbIndent) { inDb = false; section = null; continue; }\n if (!inDb) continue;\n\n const key = line.match(/^\\s+(environment|ports):\\s*$/);\n if (key) { section = key[1] as \"environment\" | \"ports\"; continue; }\n // Any other key of the service ends the block we were reading.\n if (/^\\s+[A-Za-z_][\\w-]*:\\s*\\S/.test(line) && !/^\\s+POSTGRES_/.test(line)) {\n if (!/^\\s*-\\s/.test(line.trimStart())) section = null;\n }\n\n if (section === \"environment\") {\n const pair = line.match(/^\\s+(POSTGRES_(?:USER|PASSWORD|DB)):\\s*(.+?)\\s*$/);\n if (pair) found[pair[1]] = pair[2].replace(/^[\"']|[\"']$/g, \"\");\n continue;\n }\n\n if (section === \"ports\" && hostPort === null) {\n // `- \"5435:5432\"`. Only a mapping whose container side is Postgres's\n // own port is the one to dial; anything else is a different service.\n const mapping = line.match(/^\\s*-\\s*[\"']?(?:[\\d.]+:)?(\\d+):5432(?:\\/tcp)?[\"']?\\s*$/);\n if (mapping) hostPort = mapping[1];\n }\n }\n\n return hostPort === null ? found : { ...found, hostPort };\n}\n\n/**\n * `${VAR:-default}`, `${VAR}` and a literal, resolved the way compose resolves\n * them — against the project's `.env`, which is the file compose itself reads.\n */\nfunction expandComposeValue(\n raw: string | undefined,\n env: Record<string, string | undefined>\n): string | null {\n if (!raw) return null;\n const interpolated = raw.replace(/\\$\\{([A-Za-z_][\\w]*)(?::?-([^}]*))?\\}/g, (_all, name, fallback) => {\n const value = env[name];\n if (value !== undefined && value !== \"\") return value;\n return fallback ?? \"\";\n });\n const trimmed = interpolated.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\n/**\n * Is something accepting connections there right now?\n *\n * A reset counts as yes: a refused connection means nothing listens, a reset\n * means something accepted it and dropped it — Docker's port proxy, while the\n * Postgres behind it is still starting. On macOS that reset arrives after\n * `connect`; on Linux it can arrive instead of it, and read as \"not listening\"\n * the port wait spun for its whole minute before readiness was ever asked.\n */\nexport function probeTcp(host: string, port: number, timeoutMs = 700): Promise<boolean> {\n return new Promise(resolve => {\n const socket = new net.Socket();\n let settled = false;\n\n const done = (open: boolean): void => {\n if (settled) return;\n settled = true;\n socket.destroy();\n resolve(open);\n };\n\n socket.setTimeout(timeoutMs);\n socket.once(\"connect\", () => done(true));\n socket.once(\"timeout\", () => done(false));\n socket.once(\"error\", (error: Error) => done(\"code\" in error && error.code === \"ECONNRESET\"));\n socket.connect(port, host);\n });\n}\n\n/**\n * Poll until the port answers, or give up.\n *\n * This only answers \"has the container got as far as listening\". It is not\n * readiness: Docker's port proxy accepts on the host port while Postgres inside\n * the container is still running initdb, and resets every connection it cannot\n * forward. {@link waitForQueryable} is the check that a query will work.\n */\nexport async function waitForPort(\n host: string,\n port: number,\n timeoutMs = 60_000,\n intervalMs = 500\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await probeTcp(host, port, 700)) return true;\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n }\n return false;\n}\n\n/**\n * Whether a database answered a query, and if not, the last reason it gave —\n * and, for a database closed to new connections, its name.\n */\nexport type QueryReadiness = { ready: true } | { ready: false; error: string; closedDatabase?: string };\n\n/** What opening a closed database again did, and what to say about it. */\nexport interface ClosedDatabaseHeal {\n /** It accepts connections again. */\n reopened: boolean;\n /** The driver's own lines about it (`reopenedDatabasesNotice`). */\n notice: string[];\n}\n\n/**\n * The database a connection was refused by because it is closed to new\n * connections (`ALLOW_CONNECTIONS false`), or null.\n *\n * The driver's `closedDatabaseName`, for the error a bare `pg` connect gives:\n * the sentence is matched, not SQLSTATE 55000, which also covers failures that\n * have nothing to do with connecting.\n */\nexport function closedDatabaseName(error: unknown): string | null {\n if (!error || typeof error !== \"object\") return null;\n if (\"message\" in error && typeof error.message === \"string\") {\n const named = /database \"(.+)\" is not currently accepting connections/.exec(error.message);\n if (named) return named[1];\n }\n return \"cause\" in error ? closedDatabaseName(error.cause) : null;\n}\n\n/** Open `databaseUrl`'s database again with the driver, as every `rebase db branch` command does first. */\nasync function reopenWithDriver(databaseUrl: string): Promise<ClosedDatabaseHeal> {\n const { reopenClosedDatabases, reopenedDatabasesNotice } = await import(\"@rebasepro/server-postgres\");\n const result = await reopenClosedDatabases(databaseUrl);\n return { reopened: result.reopened.length > 0, notice: reopenedDatabasesNotice(result) };\n}\n\n/**\n * Poll until `SELECT 1` succeeds on this connection string, or the bound runs out.\n *\n * The readiness that matters to everything after it. A fresh compose volume\n * answers the TCP probe seconds before it answers a query — the official image\n * runs initdb on a socket-only server, then restarts on TCP — and the schema\n * push that ran in that gap failed on `read ECONNRESET`, three runs out of\n * three. Every error is retried: a reset, \"the database system is starting up\"\n * and a refused connection all mean \"not yet\", and the bound is what turns\n * \"not yet\" into an answer.\n *\n * Except one, which is not \"not yet\": a database closed to new connections\n * (`closedDatabaseName`), which is what a `rebase db branch create --force`\n * killed mid-copy leaves its source as. Waiting cannot open it, and it was\n * waited on for the whole minute. It is opened again with the driver's\n * `reopenClosedDatabases`, once, and then either answers or the wait ends at\n * once, naming it.\n */\nexport async function waitForQueryable(\n databaseUrl: string,\n options: {\n timeoutMs?: number;\n intervalMs?: number;\n /** Opens a closed database again. The driver's `reopenClosedDatabases` by default; injected for tests. */\n reopenClosed?: (databaseUrl: string) => Promise<ClosedDatabaseHeal>;\n /** Where the driver's lines about a database it opened go. */\n onNotice?: (line: string) => void;\n } = {}\n): Promise<QueryReadiness> {\n const { timeoutMs = 60_000, intervalMs = 500 } = options;\n const { Client } = await import(\"pg\");\n const deadline = Date.now() + timeoutMs;\n let lastError = \"no attempt was made\";\n let healed = false;\n\n do {\n const client = new Client({\n connectionString: databaseUrl,\n connectionTimeoutMillis: Math.max(250, Math.min(2_000, deadline - Date.now()))\n });\n // A reset can arrive after `connect` settles; unhandled, it would take\n // the process down rather than count as one more \"not yet\".\n client.on(\"error\", () => undefined);\n let closed: string | null = null;\n try {\n await client.connect();\n await client.query(\"SELECT 1\");\n return { ready: true };\n } catch (error) {\n lastError = error instanceof Error && error.message ? error.message : String(error);\n closed = closedDatabaseName(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n if (closed !== null) {\n if (healed) return { ready: false, error: lastError, closedDatabase: closed };\n healed = true;\n const heal = await (options.reopenClosed ?? reopenWithDriver)(databaseUrl).catch(() => ({ reopened: false, notice: [] }));\n for (const line of heal.notice) options.onNotice?.(line);\n if (!heal.reopened) return { ready: false, error: lastError, closedDatabase: closed };\n // Open again: ask straight away rather than after the interval.\n continue;\n }\n if (Date.now() + intervalMs >= deadline) break;\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n } while (Date.now() < deadline);\n\n return { ready: false, error: lastError };\n}\n\n/**\n * What a failed schema push printed, as lines to show.\n *\n * `rebase dev` runs the push with its output captured, so a successful start\n * stays quiet. On a failure that captured output is the diagnosis, and it was\n * being dropped: the warning said \"fix the error above\" over nothing at all.\n * The child's stdout and stderr are what is shown — not execa's own message,\n * which leads with the command line, and that carries the database password.\n */\nexport function pushFailureOutput(error: unknown): string[] {\n if (error instanceof ExecaError) {\n const captured = [streamText(error.stdout), streamText(error.stderr)]\n .map(stream => stream.trim())\n .filter(stream => stream.length > 0);\n if (captured.length > 0) return captured.join(\"\\n\").split(/\\r?\\n/);\n return [error.originalMessage || `The push exited with code ${error.exitCode ?? \"unknown\"}.`];\n }\n return [error instanceof Error ? error.message : String(error)];\n}\n\n/** A captured stream as text, whichever form execa's options gave it. */\nfunction streamText(stream: unknown): string {\n if (typeof stream === \"string\") return stream;\n if (stream instanceof Uint8Array) return Buffer.from(stream).toString(\"utf8\");\n if (Array.isArray(stream)) return stream.map(String).join(\"\\n\");\n return \"\";\n}\n\n/** The user and password the compose `db` service creates, expanded against `.env`. */\nfunction composeCredentials(\n yamlText: string,\n env: Record<string, string | undefined>\n): { user: string; password: string } | null {\n const found = scanComposeDbService(yamlText);\n const user = expandComposeValue(found.POSTGRES_USER, env);\n const password = expandComposeValue(found.POSTGRES_PASSWORD, env);\n return user && password ? { user, password } : null;\n}\n\n/**\n * The compose project a file belongs to, named the way `docker compose` names\n * it: the file's top-level `name:`, else the directory, lowercased with\n * everything but `[a-z0-9_-]` dropped.\n *\n * A project name set with `-p` or in the environment is not read: a container\n * started from this directory is recognised by its working directory anyway,\n * and the name is only the fallback for a project that has moved since.\n */\nexport function composeProjectName(yamlText: string, projectRoot: string): string {\n const named = /^name:\\s*[\"']?([^\"'#\\s]+)[\"']?\\s*(?:#.*)?$/m.exec(yamlText)?.[1];\n const raw = named || path.basename(projectRoot);\n return raw.toLowerCase().replace(/[^a-z0-9_-]/g, \"\");\n}\n\n/** Who answers on a host port, as far as Docker can say. */\nexport type PortHolder =\n | { kind: \"this-project\" }\n | { kind: \"container\"; name: string; project?: string; directory?: string }\n | { kind: \"outside-docker\" }\n | { kind: \"unknown\" };\n\n/** One `docker ps` row per container publishing the port: name, then its compose labels. */\nconst PUBLISHER_FORMAT = [\n \"{{.Names}}\",\n \"{{.Label \\\"com.docker.compose.project\\\"}}\",\n \"{{.Label \\\"com.docker.compose.project.working_dir\\\"}}\",\n \"{{.Label \\\"com.docker.compose.service\\\"}}\"\n].join(\"\\t\");\n\n/**\n * Whose container `docker ps --filter publish=<port>` listed, from its rows.\n *\n * This project's when one of them is a `db` service of this compose project:\n * started from this directory, or carrying the project's name (compose treats\n * two directories with one `name:` as one project, so this does too). Any other\n * container is named. No rows at all, from a Docker that answered, means the\n * listener is not a container: a Postgres installed on this machine, say.\n */\nexport function classifyPortPublishers(output: string, projectRoot: string, composeProject: string | null): PortHolder {\n const rows = output.split(/\\r?\\n/)\n .map(line => line.split(\"\\t\").map(field => field.trim()))\n .filter(([name]) => Boolean(name));\n if (rows.length === 0) return { kind: \"outside-docker\" };\n\n const here = canonicalPath(projectRoot);\n for (const [, project, directory, service] of rows) {\n if (service !== \"db\") continue;\n if ((directory && canonicalPath(directory) === here) || (composeProject && project === composeProject)) {\n return { kind: \"this-project\" };\n }\n }\n const [name, project, directory] = rows[0];\n return { kind: \"container\", name, ...(project ? { project } : {}), ...(directory ? { directory } : {}) };\n}\n\nfunction canonicalPath(dir: string): string {\n try {\n return fs.realpathSync(dir);\n } catch {\n return path.resolve(dir);\n }\n}\n\n/** Ask Docker who publishes `port`. `unknown` when Docker cannot be asked. */\nexport async function dockerPortHolder(projectRoot: string, composeProject: string | null, port: number): Promise<PortHolder> {\n try {\n const { stdout } = await execa(\"docker\", [\"ps\", \"--filter\", `publish=${port}`, \"--format\", PUBLISHER_FORMAT], {\n stdio: \"pipe\",\n timeout: 5_000\n });\n return classifyPortPublishers(stdout, projectRoot, composeProject);\n } catch {\n return { kind: \"unknown\" };\n }\n}\n\n/**\n * Every host port in a list of `docker inspect --format '{{json .HostConfig.PortBindings}}'` lines.\n *\n * The configured bindings, which a stopped container keeps: it takes its port\n * back the moment it starts, so the port is not free to give to a new project.\n * `HostPort: \"0\"` asks for any free port and claims none.\n */\nexport function parsePortBindings(output: string): Set<number> {\n const ports = new Set<number>();\n for (const line of output.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n continue;\n }\n if (!parsed || typeof parsed !== \"object\") continue;\n const bindingLists: unknown[] = Object.values(parsed);\n for (const bindings of bindingLists) {\n if (!Array.isArray(bindings)) continue;\n for (const binding of bindings) {\n if (!binding || typeof binding !== \"object\" || !(\"HostPort\" in binding)) continue;\n const hostPort = Number(binding.HostPort);\n if (Number.isInteger(hostPort) && hostPort > 0 && hostPort < 65536) ports.add(hostPort);\n }\n }\n }\n return ports;\n}\n\n/**\n * The host ports every container on this machine is bound to, running or\n * stopped — `null` when Docker cannot be asked.\n *\n * A TCP probe sees only what is listening now, and a stopped project's `db`\n * container is not; `docker ps` shows a stopped container's ports only\n * sometimes. The bindings in its config are what it will take back.\n */\nexport async function dockerClaimedPorts(): Promise<Set<number> | null> {\n try {\n const { stdout: ids } = await execa(\"docker\", [\"ps\", \"-aq\"], { stdio: \"pipe\", timeout: 5_000 });\n const containers = ids.split(/\\s+/).filter(Boolean);\n if (containers.length === 0) return new Set();\n // `reject: false`: a container removed since `ps` fails its own entry and\n // exits 1, and every other container's bindings are still on stdout.\n const { stdout } = await execa(\"docker\", [\"inspect\", \"--format\", \"{{json .HostConfig.PortBindings}}\", ...containers], {\n stdio: \"pipe\",\n timeout: 10_000,\n reject: false\n });\n return parsePortBindings(stdout);\n } catch {\n return null;\n }\n}\n\n/**\n * Whether `databaseUrl` is this project's compose database: the port the `db`\n * service publishes, with the user and password it creates.\n *\n * The credentials matter. One Postgres container shared by several projects is\n * an ordinary setup, and such a URL names that container's password — a\n * database somebody chose, which is theirs to point at.\n */\nfunction isComposeDatabaseUrl(databaseUrl: string, port: number, composeText: string, env: Record<string, string | undefined>): boolean {\n if (composeHostPort(composeText) !== port) return false;\n const credentials = composeCredentials(composeText, env);\n if (!credentials) return false;\n try {\n const url = new URL(databaseUrl);\n return decodeURIComponent(url.username) === credentials.user\n && decodeURIComponent(url.password) === credentials.password;\n } catch {\n return false;\n }\n}\n\n/** The first port after `port` that nothing on loopback answers on, for a suggestion. */\nasync function nextQuietPort(port: number): Promise<number | null> {\n for (let candidate = port + 1; candidate < Math.min(port + 50, 65536); candidate++) {\n if (!(await probeTcp(\"127.0.0.1\", candidate, 300))) return candidate;\n }\n return null;\n}\n\n/**\n * Said, then thrown: the compose port answers, and not with this project's\n * database. Returns quietly when the listener is ours, or when Docker cannot\n * say — the behaviour from before this check.\n */\nasync function refuseForeignListener(options: {\n projectRoot: string;\n databaseUrl: string;\n port: number;\n composeText: string;\n whoHoldsPort?: (port: number) => Promise<PortHolder>;\n log: (message: string) => void;\n}): Promise<void> {\n const { projectRoot, databaseUrl, port, composeText, log } = options;\n const env = readEnvFile(projectRoot);\n if (!isComposeDatabaseUrl(databaseUrl, port, composeText, env)) return;\n\n const whoHoldsPort = options.whoHoldsPort\n ?? ((p: number) => dockerPortHolder(projectRoot, composeProjectName(composeText, projectRoot), p));\n const holder = await whoHoldsPort(port);\n if (holder.kind === \"this-project\" || holder.kind === \"unknown\") return;\n\n const who = holder.kind === \"container\"\n ? `another container is listening there: ${holder.name}`\n + (holder.project || holder.directory\n ? ` (${[holder.project ? `compose project ${holder.project}` : \"\", holder.directory ? `in ${holder.directory}` : \"\"]\n .filter(Boolean).join(\", \")})`\n : \"\")\n : \"something outside Docker is listening there, such as a Postgres installed on this machine\";\n const suggestion = await nextQuietPort(port);\n const envSetsUrl = Boolean(env.DATABASE_URL?.trim());\n\n log(\"\");\n log(` ${chalk.yellow(\"⚠\")} ${chalk.bold(`Port ${port} is not this project's database.`)}`);\n for (const line of [\n `docker-compose.yml publishes this project's db service on ${port}, and ${who}.`,\n \"Nothing was started and nothing connected: a login there fails on this project's password, and the fix that failure suggests is for that database.\",\n `Give this project its own port: change \"${port}:5432\" under db: in docker-compose.yml`\n + ` to ${suggestion ? `a free one, such as \"${suggestion}:5432\"` : \"one nothing else uses\"}`\n + (envSetsUrl ? \", and the port in DATABASE_URL in .env.\" : \".\"),\n holder.kind === \"container\"\n ? `Or stop ${holder.name} first: docker stop ${holder.name}`\n : \"Or stop what is listening on it.\"\n ]) {\n log(` ${chalk.gray(line)}`);\n }\n\n // Said in full above, so a `Refusal`: `bin/rebase.js` adds no stack hint.\n throw new Refusal(\n holder.kind === \"container\"\n ? `Port ${port} belongs to ${holder.name}, not to this project's db service. Nothing was started.`\n : `Port ${port} belongs to a server outside Docker, not to this project's db service. Nothing was started.`\n );\n}\n\nexport interface EnsureDevDatabaseOptions {\n projectRoot: string;\n /** The DSN from the project's env file, if it has one. */\n databaseUrl: string | undefined;\n /** Set by `--no-db` or REBASE_DEV_NO_DB. */\n disabled: boolean;\n /** Whether the project declares tables worth pushing (`backend/schema/index.ts`). */\n hasTables: boolean;\n /** Runs `rebase db push` for this project. Injected so tests need no database. */\n pushSchema: () => Promise<void>;\n /**\n * Brings the compose `db` service up. Injected for the same reason\n * `pushSchema` is: what happens *after* a start — a push that fails without\n * taking the dev server with it — is the part worth asserting, and it was\n * untestable while the only way in was a real `docker compose up`.\n */\n startDatabase?: (projectRoot: string) => Promise<void>;\n /** How long a started database has to answer `SELECT 1`. Defaults to 60s. */\n readyTimeoutMs?: number;\n /** Opens a database closed to new connections again; see `waitForQueryable`. Injected for tests. */\n reopenClosed?: (databaseUrl: string) => Promise<ClosedDatabaseHeal>;\n /**\n * Who answers on the compose port. Asks Docker by default; injected for the\n * same reason `startDatabase` is.\n */\n whoHoldsPort?: (port: number) => Promise<PortHolder>;\n log?: (message: string) => void;\n}\n\n/**\n * Start the project's development database if it is not running, and give it a\n * schema if this call is what started it.\n */\nexport async function ensureDevDatabase(options: EnsureDevDatabaseOptions): Promise<PreflightOutcome> {\n const { projectRoot, databaseUrl, disabled, hasTables, pushSchema } = options;\n const log = options.log ?? ((message: string) => console.log(message));\n\n if (disabled) return { action: \"disabled\" };\n\n const target = parseLoopbackDsn(databaseUrl);\n if (!databaseUrl) return { action: \"no-dsn\" };\n if (!target) {\n // Not an error, and not worth a warning either: pointing DATABASE_URL at\n // a real database is a completely ordinary thing to do, and the only\n // correct response is to keep away from it.\n let host = \"the configured host\";\n try {\n host = new URL(databaseUrl).hostname || host;\n } catch { /* keep the placeholder */ }\n return { action: \"remote-dsn\", host };\n }\n\n const composePath = path.join(projectRoot, \"docker-compose.yml\");\n const composeText = fs.existsSync(composePath) ? fs.readFileSync(composePath, \"utf8\") : null;\n\n if (await probeTcp(target.host, target.port)) {\n // Something answers. Whatever it is stays untouched; but if this URL is\n // the compose database, it has to be the compose container.\n if (composeText !== null) {\n await refuseForeignListener({\n projectRoot,\n databaseUrl,\n port: target.port,\n composeText,\n whoHoldsPort: options.whoHoldsPort,\n log\n });\n }\n return { action: \"already-running\", host: target.host, port: target.port };\n }\n\n if (composeText === null || !composeDeclaresDbService(composeText)) return { action: \"no-compose\" };\n\n const manualSteps =\n `${chalk.cyan(\"docker compose up -d db\")} then ${chalk.cyan(\"rebase db push\")}`;\n\n // Would starting that container answer *this* DSN? A `.env` naming a port\n // the compose file does not publish is the commonest way to get here, and\n // starting the container then told the reader the exact opposite of the\n // truth: `⚠ The database container did not begin listening on port 3139.\n // Run docker compose up -d db then rebase db push to see why.` The\n // container was up and healthy on 5436; the port in `.env` was what was\n // wrong. And a container nobody asked for was left running.\n const composePort = composeHostPort(composeText);\n if (composePort !== null && composePort !== target.port) {\n const hint =\n `DATABASE_URL points at ${target.host}:${target.port} and nothing listens there. `\n + `The compose file's db service publishes ${composePort}, so starting it would not `\n + `answer that URL — nothing was started. Either correct the port in .env, or point `\n + `DATABASE_URL at 127.0.0.1:${composePort}.`;\n log(\"\");\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"wrong-port\", hint, port: target.port, composePort };\n }\n\n log(\"\");\n log(` ${chalk.gray(\"Database not running — starting it…\")}`);\n\n const startDatabase = options.startDatabase ?? (async (root: string) => {\n await execa(\"docker\", [\"compose\", \"up\", \"-d\", \"db\"], { cwd: root, stdio: \"pipe\" });\n });\n\n try {\n await startDatabase(projectRoot);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n // Two very different failures land here and the reader needs to know\n // which: Docker not being installed at all, and Docker being installed\n // but unable to start this container.\n if (/ENOENT|not found|command not found/i.test(message)) {\n const hint = `Docker was not found. Start a Postgres yourself, then run ${manualSteps}.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"no-docker\", hint };\n }\n const hint = `Could not start the database container. Run ${manualSteps} to see why.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n\n if (!(await waitForPort(target.host, target.port))) {\n const hint = `The database container did not begin listening on port ${target.port}. Run ${manualSteps} to see why.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n\n // Listening is not ready. Nothing is pushed into a database that has not\n // yet answered a query; see `waitForQueryable`.\n const readiness = await waitForQueryable(databaseUrl, {\n timeoutMs: options.readyTimeoutMs,\n reopenClosed: options.reopenClosed,\n onNotice: line => log(` ${chalk.yellow(line)}`)\n });\n if (!readiness.ready && readiness.closedDatabase !== undefined) {\n const name = readiness.closedDatabase;\n const hint = `Database \"${name}\" on port ${target.port} is closed to new connections (ALLOW_CONNECTIONS false), `\n + \"and could not be opened again. `rebase db branch create --force` closes its source for the copy, and one \"\n + \"stopped before it finished leaves it closed; nothing in it is lost. Open it with \"\n + `${chalk.cyan(\"rebase db branch list\")} (every rebase db branch command opens it first), or run, connected `\n + `to the server's postgres database: ALTER DATABASE \"${name.replace(/\"/g, '\"\"')}\" ALLOW_CONNECTIONS true;`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n if (!readiness.ready) {\n const seconds = Math.round((options.readyTimeoutMs ?? 60_000) / 1000);\n const hint = `The database container is listening on port ${target.port} but did not answer a query `\n + `within ${seconds}s (${readiness.error}). Run ${chalk.cyan(\"docker compose logs db\")} to see why, `\n + `then ${chalk.cyan(\"rebase db push\")}.`;\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(hint)}`);\n return { action: \"start-failed\", hint };\n }\n\n log(` ${chalk.green(\"✓\")} ${chalk.gray(`Database ready on port ${target.port}`)}`);\n\n if (!hasTables) return { action: \"started\", port: target.port, pushed: false };\n\n log(` ${chalk.gray(\"Pushing the schema…\")}`);\n try {\n await pushSchema();\n log(` ${chalk.green(\"✓\")} ${chalk.gray(\"Schema pushed\")}`);\n return { action: \"started\", port: target.port, pushed: true };\n } catch (error) {\n // The push runs with its output captured, so what it printed is shown\n // here, before the line that refers to it. Then the one thing the\n // reader needs next: the server is still starting, and against what.\n for (const line of pushFailureOutput(error)) log(` ${chalk.gray(line)}`);\n log(` ${chalk.yellow(\"⚠\")} ${chalk.gray(`Schema push failed. The database is running; fix the error above and run ${chalk.cyan(\"rebase db push\")}.`)}`);\n return { action: \"started\", port: target.port, pushed: false };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAa;CAAO;AAAS,CAAC;;;;;;;;AASrE,SAAgB,iBAAiB,KAAgE;CAC7F,IAAI,CAAC,KAAK,OAAO;CAEjB,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,IAAI,GAAG;CACrB,QAAQ;EACJ,OAAO;CACX;CAEA,IAAI,CAAC,mBAAmB,KAAK,IAAI,QAAQ,GAAG,OAAO;CAMnD,MAAM,OAAO,IAAI,SAAS,QAAQ,cAAc,IAAI;CACpD,IAAI,CAAC,SAAS,IAAI,IAAI,GAAG,OAAO;CAEhC,MAAM,OAAO,IAAI,OAAO,OAAO,IAAI,IAAI,IAAI;CAC3C,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,QAAQ,KAAK,OAAO,OAAO,OAAO;CAEjE,OAAO;EAAE;EAAM;CAAK;AACxB;;;;;;;;;AAUA,SAAgB,yBAAyB,UAA2B;CA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EAAM;CACjE;AACJ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as findProjectRoot } from "./project-
|
|
1
|
+
import { c as findProjectRoot } from "./project-DALmhb5R.js";
|
|
2
2
|
import fs from "fs";
|
|
3
3
|
import path from "path";
|
|
4
4
|
//#region src/utils/dev-server.ts
|
|
@@ -135,4 +135,4 @@ function serverUnreachableHint(baseUrl, projectRoot = findProjectRoot()) {
|
|
|
135
135
|
//#endregion
|
|
136
136
|
export { serverUnreachableHint as a, runningBackendUrl as i, devServerUrl as n, getProjectPort as r, DEV_BACKEND_URL_ENV as t };
|
|
137
137
|
|
|
138
|
-
//# sourceMappingURL=dev-server-
|
|
138
|
+
//# sourceMappingURL=dev-server-2XHSHM_q.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-server-
|
|
1
|
+
{"version":3,"file":"dev-server-2XHSHM_q.js","names":[],"sources":["../src/utils/dev-server.ts"],"sourcesContent":["/**\n * Where `rebase dev` serves a project's backend.\n *\n * Not the `PORT` in `.env`: `rebase dev` overrides it with a port derived from\n * the project's path, so two projects on one machine do not collide, and that\n * `PORT` is what `rebase start` listens on. A command that talks to the backend\n * and gets no answer has to be able to say both — its hint named only `.env`'s\n * 3001, for a project whose dev server had been on 3732.\n */\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { findProjectRoot } from \"./project\";\n\n/**\n * The address `rebase dev` is starting its backend on, handed to the\n * `generate-sdk` child it runs.\n *\n * Dev regenerates the SDK at boot, beside the database start and before the\n * backend binds — so before the backend writes `.rebase/state.json`, which is\n * where `generate-sdk` otherwise reads the address for the README's example.\n * Dev knows the port it hands the backend, and the child's environment is the\n * only channel between them.\n */\nexport const DEV_BACKEND_URL_ENV = \"REBASE_DEV_BACKEND_URL\";\n\n/**\n * The port `rebase dev` derives from the project root path.\n * Range: 3001–3999 (avoids privileged ports and common services).\n * Two different project directories will almost always get different ports.\n */\nexport function getProjectPort(projectRoot: string): number {\n let hash = 0;\n for (let i = 0; i < projectRoot.length; i++) {\n hash = ((hash << 5) - hash + projectRoot.charCodeAt(i)) | 0;\n }\n return 3001 + (Math.abs(hash) % 999);\n}\n\n/** A TCP port out of a string or a number, or null. */\nfunction portOf(raw: unknown): number | null {\n const port = typeof raw === \"number\" ? raw : typeof raw === \"string\" ? Number(raw.trim()) : Number.NaN;\n return Number.isInteger(port) && port > 0 && port < 65536 ? port : null;\n}\n\nfunction readText(file: string): string | null {\n try {\n return fs.readFileSync(file, \"utf-8\").trim();\n } catch {\n return null;\n }\n}\n\n/** Is *some* process with this pid running? EPERM means it is, as someone else. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * The address of this project's backend while it runs, or `null`.\n *\n * From `.rebase/state.json`, which the server writes when it binds — under\n * `rebase dev` and `rebase start` alike — and only while the pid it names is\n * alive: a backend that was killed leaves the file behind.\n */\nexport function runningBackendUrl(projectRoot: string): string | null {\n const state = readText(path.join(projectRoot, \".rebase\", \"state.json\"));\n if (!state) return null;\n try {\n const parsed: unknown = JSON.parse(state);\n if (typeof parsed !== \"object\" || parsed === null || !(\"pid\" in parsed)) return null;\n const pid = parsed.pid;\n if (typeof pid !== \"number\" || !Number.isInteger(pid) || pid <= 0 || !processAlive(pid)) return null;\n if (\"baseUrl\" in parsed && typeof parsed.baseUrl === \"string\" && parsed.baseUrl.trim()) return parsed.baseUrl.trim();\n const port = \"port\" in parsed ? portOf(parsed.port) : null;\n return port !== null ? `http://localhost:${port}` : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The URL `rebase dev` serves this project on, and how that is known:\n *\n * - `running` — the URL a running dev wrote to `.rebase-dev-url`;\n * - `recorded` — the port the last run left in `.rebase/state.json` or\n * `.rebase-dev-port` (both outlive a dev that did not shut down cleanly);\n * - `derived` — nothing is recorded, so the port it derives for this path.\n *\n * Asked only to describe where dev is; a `PORT` in the shell would move the\n * next run, and is not something a stopped dev left behind.\n */\nexport function devServerUrl(projectRoot: string): { url: string; source: \"running\" | \"recorded\" | \"derived\" } {\n const running = readText(path.join(projectRoot, \".rebase-dev-url\"));\n if (running) return { url: running, source: \"running\" };\n\n const state = readText(path.join(projectRoot, \".rebase\", \"state.json\"));\n if (state) {\n try {\n const parsed: unknown = JSON.parse(state);\n const port = typeof parsed === \"object\" && parsed !== null && \"port\" in parsed ? portOf(parsed.port) : null;\n if (port !== null) return { url: `http://localhost:${port}`, source: \"recorded\" };\n } catch { /* fall through to the port file */ }\n }\n\n const portFile = portOf(readText(path.join(projectRoot, \".rebase-dev-port\"))?.split(/\\s+/)[0]);\n if (portFile !== null) return { url: `http://localhost:${portFile}`, source: \"recorded\" };\n\n return { url: `http://localhost:${getProjectPort(projectRoot)}`, source: \"derived\" };\n}\n\n/**\n * What to say when nothing answered at `baseUrl`.\n *\n * The first line is the question it always asked. The second is added when\n * `rebase dev` serves this project somewhere else, because then `baseUrl` is\n * almost always `.env`'s `PORT`, and a reader who just stopped `rebase dev`\n * reads the number as the one it was using.\n */\nexport function serverUnreachableHint(baseUrl: string, projectRoot: string | null = findProjectRoot()): string[] {\n const lines = [` Is the Rebase server running at ${baseUrl}? Start it with \\`rebase dev\\`, or set REBASE_BASE_URL in .env.`];\n if (!projectRoot) return lines;\n\n const dev = devServerUrl(projectRoot);\n let same = false;\n try {\n same = new URL(dev.url).origin === new URL(baseUrl).origin;\n } catch {\n // An unparseable URL on either side is not the same address.\n }\n if (same) return lines;\n\n const why = dev.source === \"derived\" ? \"the port it picks for this project\" : \"the port it last used\";\n lines.push(` \\`rebase dev\\` serves this project at ${dev.url} (${why}), and this command uses that address while it runs.`);\n\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,sBAAsB;;;;;;AAOnC,SAAgB,eAAe,aAA6B;CACxD,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,YAAY,QAAQ,KACpC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Gs.js";
|
|
2
|
+
import { a as wantsHelp, n as parseCommandArgs } from "./args-DHyrshtI.js";
|
|
3
|
+
import { f as requireBackendDir, g as resolveTsx, h as resolvePluginCliScript, l as getActiveBackendPlugin, o as findEnvFile, p as requireProjectRoot, r as exitDependenciesNotInstalled } from "./project-DALmhb5R.js";
|
|
4
|
+
import { C as resolveBackendPaths, _ as findBackendApp, b as loadManifest } from "./manifest-RjqxfCpb.js";
|
|
5
|
+
import { n as resolveSchemaDir, r as schemaDirArgs } from "./schema-dir-ChcYfWjP.js";
|
|
6
|
+
import { a as refuseRemovedCollectionsFlag, i as refuseMissingSchemaDir, n as SCHEMA_DIR_FLAG_HELP } from "./path-flags-ekLdkbra.js";
|
|
6
7
|
import { n as summarisePortability, t as analyseFunctionsDirectory } from "./function-portability-BIvlvR9q.js";
|
|
7
|
-
import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-
|
|
8
|
-
import { DATABASE_SOURCE_ENV, absolutizeLocalPathArgs, n as argsFromCommand, t as reportSpawnFailure } from "./db-
|
|
8
|
+
import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-BaJe0Zik.js";
|
|
9
|
+
import { DATABASE_SOURCE_ENV, absolutizeLocalPathArgs, n as argsFromCommand, t as reportSpawnFailure } from "./db-D_iF4E-v.js";
|
|
9
10
|
import { t as declaredTables } from "./schema-text-CpNrsuMe.js";
|
|
10
11
|
import chalk from "chalk";
|
|
11
12
|
import fs from "fs";
|
|
@@ -796,4 +797,4 @@ async function doctorCommand(rawArgs) {
|
|
|
796
797
|
//#endregion
|
|
797
798
|
export { doctorCommand };
|
|
798
799
|
|
|
799
|
-
//# sourceMappingURL=doctor-
|
|
800
|
+
//# sourceMappingURL=doctor-2Jlau0Rm.js.map
|