@akal/supaforge 0.0.33 → 0.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +67 -14
  2. package/dist/base-command.d.ts +1 -1
  3. package/dist/base-command.js +4 -3
  4. package/dist/{branch-C4ndfoj5.d.ts → branch-BppjQBv_.d.ts} +1 -1
  5. package/dist/{chunk-4IVN7QVY.js → chunk-44UVQJV2.js} +159 -18
  6. package/dist/{chunk-3HGAV5CC.js → chunk-4AGJRRBT.js} +390 -43
  7. package/dist/{chunk-SQPCWGQO.js → chunk-4M6OQLPO.js} +22 -121
  8. package/dist/{chunk-2SELREHW.js → chunk-5Q6LSLA3.js} +56 -9
  9. package/dist/{chunk-7NAZGZPV.js → chunk-7N63OPFN.js} +28 -21
  10. package/dist/chunk-AGONS5JJ.js +242 -0
  11. package/dist/chunk-GQPGH6YR.js +50 -0
  12. package/dist/{chunk-GEHPTPNZ.js → chunk-H2D3YSKM.js} +7 -3
  13. package/dist/{chunk-6Q7MHFBM.js → chunk-HNJ6BNNZ.js} +2 -2
  14. package/dist/{chunk-6WAMNZLO.js → chunk-KNXHLVF7.js} +126 -4
  15. package/dist/{chunk-DMIWAJRB.js → chunk-NEM5AEPQ.js} +172 -22
  16. package/dist/{chunk-6LJERPUN.js → chunk-NX2KKUS7.js} +20 -12
  17. package/dist/{chunk-SC2XHGIS.js → chunk-O5ERC2SE.js} +3 -3
  18. package/dist/{chunk-MIRLB5JM.js → chunk-SM7HP6EP.js} +64 -182
  19. package/dist/{chunk-BUOWHE36.js → chunk-T7GMPGUO.js} +613 -66
  20. package/dist/{chunk-G2DIPIYU.js → chunk-WK5YTINL.js} +29 -2
  21. package/dist/{chunk-UWAVXC57.js → chunk-WNTCZM2J.js} +34 -482
  22. package/dist/{chunk-GZREXCQZ.js → chunk-XLZCX6R2.js} +17 -10
  23. package/dist/{chunk-ORQJVE57.js → chunk-YWERIWFD.js} +18 -17
  24. package/dist/{chunk-NTUASFQ3.js → chunk-YZM76W22.js} +5 -5
  25. package/dist/{chunk-BLKJWDTL.js → chunk-ZI435CAU.js} +2 -2
  26. package/dist/commands/clone.d.ts +2 -2
  27. package/dist/commands/clone.js +14 -13
  28. package/dist/commands/diff.d.ts +37 -23
  29. package/dist/commands/diff.js +20 -17
  30. package/dist/commands/hukam.d.ts +2 -3
  31. package/dist/commands/hukam.js +16 -15
  32. package/dist/commands/init.d.ts +1 -1
  33. package/dist/commands/init.js +5 -1
  34. package/dist/commands/mcp.js +16 -10
  35. package/dist/commands/migrate/baseline.d.ts +1 -1
  36. package/dist/commands/migrate/baseline.js +5 -4
  37. package/dist/commands/migrate/create.d.ts +1 -1
  38. package/dist/commands/migrate/create.js +15 -9
  39. package/dist/commands/migrate/list.d.ts +1 -1
  40. package/dist/commands/migrate/list.js +6 -5
  41. package/dist/commands/migrate/run.d.ts +4 -1
  42. package/dist/commands/migrate/run.js +10 -8
  43. package/dist/commands/report.d.ts +1 -1
  44. package/dist/commands/report.js +5 -4
  45. package/dist/commands/restore.d.ts +1 -1
  46. package/dist/commands/restore.js +14 -13
  47. package/dist/commands/snapshot.d.ts +8 -1
  48. package/dist/commands/snapshot.js +37 -9
  49. package/dist/commands/sync.d.ts +2 -3
  50. package/dist/commands/sync.js +16 -15
  51. package/dist/{config-CTbeRlJk.d.ts → config-l3ggjw9r.d.ts} +2 -0
  52. package/dist/index.d.ts +21 -4
  53. package/dist/index.js +15 -15
  54. package/package.json +2 -2
  55. package/dist/chunk-DQQ5E563.js +0 -64
@@ -7,118 +7,12 @@ import {
7
7
  RUNTIME_DETECT_TIMEOUT_MS,
8
8
  bold,
9
9
  cmd,
10
+ describeFailure,
10
11
  dim,
11
12
  ok,
13
+ redactUrls,
12
14
  warn
13
- } from "./chunk-6WAMNZLO.js";
14
-
15
- // src/utils/error.ts
16
- var DB_URL_RE = /\b((?:postgres(?:ql)?|mysql|mariadb):\/\/)(\S+)/g;
17
- function redactUrls(message) {
18
- return message.replace(DB_URL_RE, (_, scheme, rest) => {
19
- const lastAt = rest.lastIndexOf("@");
20
- if (lastAt === -1) return scheme + rest;
21
- const creds = rest.slice(0, lastAt);
22
- const hostPart = rest.slice(lastAt);
23
- const colonIdx = creds.indexOf(":");
24
- if (colonIdx === -1) return scheme + rest;
25
- return scheme + creds.slice(0, colonIdx) + ":***" + hostPart;
26
- });
27
- }
28
- var UNDESCRIBED_ERROR = "unknown error \u2014 no message reported";
29
- function describeFailure(err) {
30
- if (typeof err === "string") return err.trim() || UNDESCRIBED_ERROR;
31
- const candidate = err;
32
- const message = typeof candidate?.message === "string" ? candidate.message.trim() : "";
33
- if (message) return message;
34
- const code = typeof candidate?.code === "string" ? candidate.code.trim() : "";
35
- if (code) return `${code} (no further detail reported)`;
36
- const name = typeof candidate?.name === "string" ? candidate.name.trim() : "";
37
- if (name && name !== "Error") return `${name} (no further detail reported)`;
38
- if (err !== null && err !== void 0 && !(err instanceof Error)) {
39
- const rendered = String(err).trim();
40
- if (rendered && rendered !== "[object Object]") return rendered;
41
- }
42
- return UNDESCRIBED_ERROR;
43
- }
44
- function errMsg(err) {
45
- return redactUrls(describeFailure(err));
46
- }
47
- var DiagnosticError = class extends Error {
48
- constructor(message) {
49
- super(message);
50
- this.name = "DiagnosticError";
51
- }
52
- };
53
- function isDiagnosticError(err) {
54
- return err instanceof DiagnosticError || err instanceof Error && err.name === "DiagnosticError";
55
- }
56
- var CONNECTION_ERROR_PATTERNS = [
57
- {
58
- test: (m) => /ECONNREFUSED|Connection refused/i.test(m),
59
- build: (host) => `Cannot connect to PostgreSQL at ${host} \u2014 the server does not appear to be running. Start it and try again.`
60
- },
61
- {
62
- test: (m) => /ENOTFOUND|getaddrinfo/i.test(m),
63
- build: (host) => `Cannot resolve hostname ${host} \u2014 check the database URL in your config.`
64
- },
65
- {
66
- // Before the connection timeout: the server answered, and a query ran
67
- // past its statement_timeout. Calling that a connection problem sent
68
- // people to check a host and port that were fine.
69
- test: (m) => /canceling statement due to statement timeout|57014/i.test(m),
70
- build: (host) => `A query on ${host} was cancelled by statement_timeout \u2014 the server is reachable. Raise statement_timeout for this role or connection and try again.`
71
- },
72
- {
73
- // Deliberately narrow. A bare /timeout/i also matches our own remediation
74
- // text — "set SUPAFORGE_DBDIFF_TIMEOUT=600" contains "TIMEOUT" — which is
75
- // how an accurate "Schema diff timed out after Ns" message was being
76
- // rewritten into a wrong "check the host and port" one (issue #29).
77
- // DiagnosticError below is the primary guard; this is defence in depth.
78
- test: (m) => /ETIMEDOUT|connection timed out|timeout expired/i.test(m),
79
- build: (host) => `Connection to ${host} timed out \u2014 verify the host and port are correct and that the server is reachable.`
80
- },
81
- {
82
- test: (m) => /password authentication failed/i.test(m),
83
- build: (host) => `Authentication failed for ${host} \u2014 check the username and password in your database URL.`
84
- },
85
- {
86
- // Must stay anchored to "database ... does not exist" (Postgres SQLSTATE
87
- // 3D000). A bare /does not exist/ is the same trap as the timeout pattern
88
- // above: it matched dbdiff's own CLI complaint — The "--allow-destructive"
89
- // option does not exist — and rewrote it into "Database does not exist on
90
- // 127.0.0.1:5432", sending you off to check a database name that was fine
91
- // while the real cause (an outdated @dbdiff/cli) went unmentioned.
92
- test: (m) => /database\s+"[^"]*"\s+does not exist|3D000/i.test(m),
93
- build: (host) => `Database does not exist on ${host} \u2014 verify the database name in your config.`
94
- },
95
- {
96
- test: (m) => /SSL.*required|no pg_hba.conf entry/i.test(m),
97
- build: (host) => `Connection rejected by ${host} \u2014 the server requires SSL or your IP is not allowed. Check pg_hba.conf and SSL settings.`
98
- }
99
- ];
100
- function extractHost(dbUrl) {
101
- try {
102
- const url = new URL(dbUrl);
103
- return url.port ? `${url.hostname}:${url.port}` : url.hostname;
104
- } catch {
105
- return "the configured host";
106
- }
107
- }
108
- function friendlyDbError(err, dbUrl) {
109
- const raw = errMsg(err);
110
- if (isDiagnosticError(err)) return raw;
111
- const host = dbUrl ? extractHost(dbUrl) : "the configured host";
112
- for (const pattern of CONNECTION_ERROR_PATTERNS) {
113
- try {
114
- if (pattern.test(raw)) {
115
- return pattern.build(host);
116
- }
117
- } catch {
118
- }
119
- }
120
- return raw;
121
- }
15
+ } from "./chunk-KNXHLVF7.js";
122
16
 
123
17
  // src/db.ts
124
18
  import pg from "pg";
@@ -140,17 +34,29 @@ function pgClientConfig(dbUrl, queryTimeoutMs) {
140
34
  }
141
35
  return config;
142
36
  }
37
+ function newPgClient(dbUrl, queryTimeoutMs) {
38
+ const client = new pg.Client(pgClientConfig(dbUrl, queryTimeoutMs));
39
+ client.on("error", () => void 0);
40
+ return client;
41
+ }
42
+ function newPgPool(config) {
43
+ const pool = new pg.Pool(config);
44
+ pool.on("error", () => void 0);
45
+ pool.on("connect", (client) => {
46
+ client.on("error", () => void 0);
47
+ });
48
+ return pool;
49
+ }
143
50
  var pools = /* @__PURE__ */ new Map();
144
51
  var POOL_MAX = 4;
145
52
  function poolFor(dbUrl) {
146
53
  const existing = pools.get(dbUrl);
147
54
  if (existing) return existing;
148
- const pool = new pg.Pool({
55
+ const pool = newPgPool({
149
56
  ...pgClientConfig(dbUrl),
150
57
  max: POOL_MAX,
151
58
  allowExitOnIdle: true
152
59
  });
153
- pool.on("error", () => void 0);
154
60
  pools.set(dbUrl, pool);
155
61
  return pool;
156
62
  }
@@ -175,7 +81,6 @@ async function inRolledBackTransaction(dbUrl, fn) {
175
81
  // src/local-pg.ts
176
82
  import { execFile } from "child_process";
177
83
  import { promisify } from "util";
178
- import pg2 from "pg";
179
84
  var defaultExecFile = promisify(execFile);
180
85
  var PG_IMAGE = "docker.io/library/postgres:17";
181
86
  var DEFAULT_LOCAL_PORT = 5432;
@@ -185,7 +90,7 @@ var LOCAL_PG_PASSWORD = "postgres";
185
90
  var READINESS_RETRIES = 30;
186
91
  var READINESS_INTERVAL_MS = 2e3;
187
92
  async function defaultConnectFn(url) {
188
- const client = new pg2.Client(pgClientConfig(url));
93
+ const client = newPgClient(url);
189
94
  await client.connect();
190
95
  await client.end();
191
96
  }
@@ -294,7 +199,6 @@ function sleep(ms) {
294
199
  }
295
200
 
296
201
  // src/preflight.ts
297
- import pg3 from "pg";
298
202
  var SUPABASE_LOCAL_PORT = "54322";
299
203
  var DEFAULT_PG_PORT = "5432";
300
204
  var CONNECT_TIMEOUT_RE = /timeout expired|connection timeout/i;
@@ -312,7 +216,7 @@ async function checkConnection(dbUrl) {
312
216
  const connectTimeoutMs = resolveConnectTimeoutMs();
313
217
  let client;
314
218
  try {
315
- client = new pg3.Client(pgClientConfig(dbUrl, DB_PROBE_TIMEOUT_MS));
219
+ client = newPgClient(dbUrl, DB_PROBE_TIMEOUT_MS);
316
220
  await client.connect();
317
221
  const { rows } = await client.query("SHOW server_version");
318
222
  const version = rows[0].server_version;
@@ -628,12 +532,9 @@ function markAppliedSql(version, name) {
628
532
  }
629
533
 
630
534
  export {
631
- redactUrls,
632
- describeFailure,
633
- errMsg,
634
- DiagnosticError,
635
- friendlyDbError,
636
535
  pgClientConfig,
536
+ newPgClient,
537
+ newPgPool,
637
538
  pgQuery,
638
539
  inRolledBackTransaction,
639
540
  DEFAULT_LOCAL_PORT,
@@ -654,4 +555,4 @@ export {
654
555
  MigrationsCheck,
655
556
  readLocalMigrations
656
557
  };
657
- //# sourceMappingURL=chunk-SQPCWGQO.js.map
558
+ //# sourceMappingURL=chunk-4M6OQLPO.js.map
@@ -3,29 +3,50 @@ import {
3
3
  getAppliedVersions,
4
4
  getPendingMigrations,
5
5
  runMigration
6
- } from "./chunk-SC2XHGIS.js";
6
+ } from "./chunk-O5ERC2SE.js";
7
+ import {
8
+ comparedSchemas,
9
+ fingerprint
10
+ } from "./chunk-NEM5AEPQ.js";
7
11
  import {
8
12
  isDestructiveSql
9
- } from "./chunk-BUOWHE36.js";
13
+ } from "./chunk-T7GMPGUO.js";
10
14
  import {
11
15
  splitSqlStatements
12
- } from "./chunk-G2DIPIYU.js";
16
+ } from "./chunk-WK5YTINL.js";
13
17
  import {
14
18
  BaseCommand
15
- } from "./chunk-GZREXCQZ.js";
16
- import {
17
- errMsg
18
- } from "./chunk-SQPCWGQO.js";
19
+ } from "./chunk-XLZCX6R2.js";
19
20
  import {
21
+ DEFAULT_IGNORE_SCHEMAS,
20
22
  bold,
21
23
  dim,
24
+ errMsg,
22
25
  ok,
23
26
  warn
24
- } from "./chunk-6WAMNZLO.js";
27
+ } from "./chunk-KNXHLVF7.js";
25
28
 
26
29
  // src/commands/migrate/run.ts
27
30
  import { Flags } from "@oclif/core";
28
31
  import { readFile } from "fs/promises";
32
+
33
+ // src/written-against.ts
34
+ import { createHash } from "crypto";
35
+ var WRITTEN_AGAINST = "-- supaforge:written-against";
36
+ async function targetFingerprint(dbUrl, ignoreSchemas) {
37
+ const schemas = await comparedSchemas(dbUrl, dbUrl, ignoreSchemas);
38
+ return createHash("sha256").update(await fingerprint(dbUrl, schemas)).digest("hex").slice(0, 16);
39
+ }
40
+ function writtenAgainstLine(env, digest) {
41
+ return `${WRITTEN_AGAINST} ${env} ${digest}`;
42
+ }
43
+ function writtenAgainst(sql) {
44
+ const line = sql.split("\n").find((l) => l.startsWith(WRITTEN_AGAINST + " "));
45
+ const [env, digest] = line?.slice(WRITTEN_AGAINST.length + 1).trim().split(/\s+/) ?? [];
46
+ return env && digest ? { env, digest } : void 0;
47
+ }
48
+
49
+ // src/commands/migrate/run.ts
29
50
  var MigrateRun = class _MigrateRun extends BaseCommand {
30
51
  static description = "Execute pending migrations against a Supabase environment";
31
52
  static examples = [
@@ -53,6 +74,10 @@ var MigrateRun = class _MigrateRun extends BaseCommand {
53
74
  "allow-destructive": Flags.boolean({
54
75
  description: "Permit migrations that drop tables or columns, delete rows, or drop policies",
55
76
  default: false
77
+ }),
78
+ force: Flags.boolean({
79
+ description: "Run a migration even though the target has changed since it was written against it",
80
+ default: false
56
81
  })
57
82
  };
58
83
  async run() {
@@ -97,6 +122,17 @@ var MigrateRun = class _MigrateRun extends BaseCommand {
97
122
  this.log(` ${dim(truncateSql(sql))}`);
98
123
  }
99
124
  }
125
+ const stale = await this.changedSinceWritten(pending, envName, env.dbUrl, config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS);
126
+ if (stale) {
127
+ this.log("");
128
+ this.log(warn(`${stale} was written against ${envName} as it was then, and ${envName} has changed since.`));
129
+ this.log(` ${dim("Re-create it with migrate create, or pass --force to run it anyway.")}`);
130
+ if (flags.apply && !flags.force) {
131
+ this.log(`
132
+ ${warn("Nothing was applied.")}`);
133
+ this.exit(1);
134
+ }
135
+ }
100
136
  if (!flags.apply) {
101
137
  this.log(`
102
138
  ${dim("Preview only \u2014 nothing was applied.")} Re-run with ${bold("--apply")} to execute` + (destructive.length > 0 ? `, and ${bold("--allow-destructive")} for the statements above.` : "."));
@@ -124,6 +160,15 @@ ${warn(`Stopped after ${applied_count} migration(s) due to error.`)}`);
124
160
  this.log(`
125
161
  ${ok(`Applied ${applied_count} migration(s) successfully.`)} \u2713`);
126
162
  }
163
+ /** The first pending migration written against `envName`, if the target has changed since. */
164
+ async changedSinceWritten(pending, envName, dbUrl, ignoreSchemas) {
165
+ const [first] = pending;
166
+ if (!first) return void 0;
167
+ const header = writtenAgainst(await readFile(first.path, "utf-8").catch(() => ""));
168
+ if (!header || header.env !== envName) return void 0;
169
+ const now = await targetFingerprint(dbUrl, ignoreSchemas).catch(() => header.digest);
170
+ return now === header.digest ? void 0 : first.filename;
171
+ }
127
172
  };
128
173
  async function findDestructiveStatements(migrations, readFileFn = (path) => readFile(path, "utf-8")) {
129
174
  const found = [];
@@ -149,8 +194,10 @@ function truncateSql(sql) {
149
194
  }
150
195
 
151
196
  export {
197
+ targetFingerprint,
198
+ writtenAgainstLine,
152
199
  MigrateRun,
153
200
  findDestructiveStatements,
154
201
  truncateSql
155
202
  };
156
- //# sourceMappingURL=chunk-2SELREHW.js.map
203
+ //# sourceMappingURL=chunk-5Q6LSLA3.js.map
@@ -1,52 +1,51 @@
1
1
  import {
2
2
  loadMigrations
3
- } from "./chunk-NTUASFQ3.js";
3
+ } from "./chunk-YZM76W22.js";
4
4
  import {
5
5
  ensureMigrationsTable,
6
6
  getAppliedVersions
7
- } from "./chunk-SC2XHGIS.js";
7
+ } from "./chunk-O5ERC2SE.js";
8
+ import {
9
+ PLATFORM_ROLES
10
+ } from "./chunk-WNTCZM2J.js";
8
11
  import {
9
12
  dropUnsupportedSetStatements,
10
13
  knownParameters
11
- } from "./chunk-DMIWAJRB.js";
14
+ } from "./chunk-NEM5AEPQ.js";
12
15
  import {
13
16
  ABSENT_ON_TARGET,
14
17
  EXTENSION_UNAVAILABLE,
15
- PLATFORM_ROLES
16
- } from "./chunk-UWAVXC57.js";
17
- import {
18
18
  rolesNamedBy,
19
19
  sqlSkeleton,
20
20
  statementSubject
21
- } from "./chunk-BUOWHE36.js";
21
+ } from "./chunk-T7GMPGUO.js";
22
22
  import {
23
23
  isCommentOnly,
24
24
  isPsqlMetaCommand,
25
25
  splitSqlStatements,
26
26
  stripPsqlMetaCommands
27
- } from "./chunk-G2DIPIYU.js";
27
+ } from "./chunk-WK5YTINL.js";
28
28
  import {
29
29
  loadSnapshot
30
- } from "./chunk-MIRLB5JM.js";
30
+ } from "./chunk-SM7HP6EP.js";
31
31
  import {
32
- errMsg,
33
- pgClientConfig,
32
+ newPgClient,
34
33
  pgQuery,
35
34
  quoteIdent,
36
35
  quoteLiteral,
37
36
  quoteName
38
- } from "./chunk-SQPCWGQO.js";
37
+ } from "./chunk-4M6OQLPO.js";
39
38
  import {
40
39
  DEFAULT_IGNORE_SCHEMAS,
41
40
  MIGRATIONS_TABLE,
42
- SUPABASE_PLATFORM_SCHEMAS
43
- } from "./chunk-6WAMNZLO.js";
41
+ SUPABASE_PLATFORM_SCHEMAS,
42
+ errMsg
43
+ } from "./chunk-KNXHLVF7.js";
44
44
 
45
45
  // src/restore.ts
46
46
  import { readFile as readFile2, access } from "fs/promises";
47
47
  import { constants } from "fs";
48
48
  import { join as join2 } from "path";
49
- import pg from "pg";
50
49
 
51
50
  // src/restore-data.ts
52
51
  import { readdir, readFile } from "fs/promises";
@@ -357,7 +356,7 @@ async function resetRelationGrants(client, schemas) {
357
356
  // src/restore.ts
358
357
  async function getPublicTables(targetUrl) {
359
358
  const ignoreList = DEFAULT_IGNORE_SCHEMAS.map((s) => `'${s}'`).join(", ");
360
- const client = new pg.Client(pgClientConfig(targetUrl));
359
+ const client = newPgClient(targetUrl);
361
360
  await client.connect();
362
361
  try {
363
362
  const { rows } = await client.query(
@@ -376,7 +375,7 @@ async function restoreFromSnapshot(options) {
376
375
  const result = { applied: [], skipped: [], errors: [], mode: "snapshot" };
377
376
  const manifest = await loadSnapshot(options.snapshotDir);
378
377
  const sqlOrder = RESTORE_SQL_ORDER;
379
- const client = new pg.Client(pgClientConfig(options.targetUrl));
378
+ const client = newPgClient(options.targetUrl);
380
379
  await client.connect();
381
380
  const transactional = !options.noTransaction;
382
381
  if (transactional) await client.query("BEGIN");
@@ -493,7 +492,7 @@ async function restoreFromSnapshot(options) {
493
492
  delete result.incomplete;
494
493
  }
495
494
  if (!(err instanceof RestoreAborted)) {
496
- result.errors.push({ type: "sql", label: "Restore", error: errMsg(err) });
495
+ result.errors.push({ type: "sql", label: "Restore", error: restoreError(err, transactional) });
497
496
  }
498
497
  } finally {
499
498
  await client.end();
@@ -571,7 +570,7 @@ async function restoreFromMigrations(options) {
571
570
  if (options.toVersion) {
572
571
  filtered = filtered.filter((m) => m.version <= options.toVersion);
573
572
  }
574
- const client = new pg.Client(pgClientConfig(options.targetUrl));
573
+ const client = newPgClient(options.targetUrl);
575
574
  await client.connect();
576
575
  try {
577
576
  await ensureMigrationsTable(options.targetUrl, queryFn);
@@ -810,7 +809,7 @@ async function applyStatement(client, sql, transactional, result, missing, leftO
810
809
  else result.incomplete = true;
811
810
  return;
812
811
  }
813
- result.errors.push({ type: "sql", label: summarizeStatement(sql), error: errMsg(err) });
812
+ result.errors.push({ type: "sql", label: summarizeStatement(sql), error: restoreError(err, transactional) });
814
813
  if (transactional) throw new RestoreAborted();
815
814
  }
816
815
  }
@@ -856,6 +855,14 @@ END $$;`;
856
855
  }
857
856
  var RestoreAborted = class extends Error {
858
857
  };
858
+ function restoreError(err, transactional) {
859
+ const message = errMsg(err);
860
+ const code = err?.code;
861
+ if (code === "53200" && transactional) {
862
+ return `${message} \u2014 this restore holds more locks than the server allows in one transaction. Raise max_locks_per_transaction on the target (it takes a restart), or re-run with --no-transaction to commit as it goes, giving up rolling the whole restore back on a failure.`;
863
+ }
864
+ return message;
865
+ }
859
866
 
860
867
  export {
861
868
  getPublicTables,
@@ -865,4 +872,4 @@ export {
865
872
  previewMigrationRestore,
866
873
  summarizeStatement
867
874
  };
868
- //# sourceMappingURL=chunk-7NAZGZPV.js.map
875
+ //# sourceMappingURL=chunk-7N63OPFN.js.map
@@ -0,0 +1,242 @@
1
+ import {
2
+ newPgClient
3
+ } from "./chunk-4M6OQLPO.js";
4
+
5
+ // src/utils/strings.ts
6
+ var MAX_SLUG_LENGTH = 60;
7
+ function slugify(name, separator = "_") {
8
+ const pattern = new RegExp(`[^a-z0-9]+`, "g");
9
+ const edgePattern = new RegExp(`^${escapeRegex(separator)}|${escapeRegex(separator)}$`, "g");
10
+ return name.toLowerCase().replace(pattern, separator).replace(edgePattern, "").slice(0, MAX_SLUG_LENGTH);
11
+ }
12
+ function escapeRegex(s) {
13
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ }
15
+ function parseFlagList(values) {
16
+ if (!Array.isArray(values)) return [];
17
+ return values.flatMap((v) => String(v).split(",")).map((v) => v.trim()).filter((v) => v.length > 0);
18
+ }
19
+ function globToRegExp(pattern) {
20
+ let out = "^";
21
+ for (const ch of pattern) {
22
+ if (ch === "*") out += ".*";
23
+ else if (ch === "?") out += ".";
24
+ else out += escapeRegex(ch);
25
+ }
26
+ return new RegExp(out + "$");
27
+ }
28
+ function matchesGlob(value, pattern) {
29
+ return globToRegExp(pattern.toLowerCase()).test(value.toLowerCase());
30
+ }
31
+ function normalizeRoles(roles) {
32
+ const arr = Array.isArray(roles) ? roles : [roles];
33
+ return [...new Set(
34
+ arr.flatMap((r) => /^\{.*\}$/s.test(r) ? arrayLiteralElements(r) : [r]).map((r) => r.trim()).filter(Boolean)
35
+ )].sort();
36
+ }
37
+ function arrayLiteralElements(literal) {
38
+ const inner = literal.slice(1, -1);
39
+ const out = [];
40
+ let i = 0;
41
+ while (i < inner.length) {
42
+ let value = "";
43
+ if (inner[i] === '"') {
44
+ for (i++; i < inner.length && inner[i] !== '"'; i++) {
45
+ if (inner[i] === "\\") i++;
46
+ value += inner[i];
47
+ }
48
+ i++;
49
+ } else {
50
+ const end = inner.indexOf(",", i);
51
+ value = inner.slice(i, end === -1 ? inner.length : end);
52
+ i = end === -1 ? inner.length : end;
53
+ }
54
+ out.push(value);
55
+ if (inner[i] === ",") i++;
56
+ }
57
+ return out;
58
+ }
59
+
60
+ // src/pg-tools.ts
61
+ import { execFile } from "child_process";
62
+ import { platform } from "os";
63
+ import { existsSync } from "fs";
64
+ function parsePgDumpVersion(output) {
65
+ const m = output.match(/(\d+)(?:\.\d+)?/);
66
+ return m ? Number(m[1]) : null;
67
+ }
68
+ function parseServerVersion(versionStr) {
69
+ const m = versionStr.match(/^(\d+)/);
70
+ return m ? Number(m[1]) : null;
71
+ }
72
+ async function getLocalPgDumpVersion() {
73
+ return new Promise((resolve) => {
74
+ execFile("pg_dump", ["--version"], (err, stdout) => {
75
+ if (err) return resolve(null);
76
+ resolve(parsePgDumpVersion(stdout));
77
+ });
78
+ });
79
+ }
80
+ function getPgDumpVersionAt(path) {
81
+ return new Promise((resolve) => {
82
+ execFile(path, ["--version"], (err, stdout) => {
83
+ if (err) return resolve(null);
84
+ resolve(parsePgDumpVersion(stdout));
85
+ });
86
+ });
87
+ }
88
+ var VERSIONED_PG_DIRS = [
89
+ "/usr/lib/postgresql/{v}/bin",
90
+ // Debian / Ubuntu (PGDG)
91
+ "/opt/homebrew/opt/postgresql@{v}/bin",
92
+ // macOS Homebrew (Apple Silicon)
93
+ "/usr/local/opt/postgresql@{v}/bin",
94
+ // macOS Homebrew (Intel)
95
+ "/usr/pgsql-{v}/bin"
96
+ // RHEL / CentOS (PGDG)
97
+ ];
98
+ async function resolvePgDumpPath(serverMajor) {
99
+ const named = process.env.SUPAFORGE_PG_BIN?.trim();
100
+ if (named) {
101
+ if (!existsSync(`${named}/pg_dump`)) {
102
+ throw new Error(`SUPAFORGE_PG_BIN is set to "${named}", which has no pg_dump`);
103
+ }
104
+ const major = await getPgDumpVersionAt(`${named}/pg_dump`);
105
+ if (major !== null && major >= serverMajor) return { path: `${named}/pg_dump`, major };
106
+ }
107
+ const defaultMajor = await getLocalPgDumpVersion();
108
+ if (defaultMajor !== null && defaultMajor >= serverMajor) {
109
+ return { path: "pg_dump", major: defaultMajor };
110
+ }
111
+ for (const v of versionsToCheck(serverMajor)) {
112
+ for (const tmpl of VERSIONED_PG_DIRS) {
113
+ const dir = tmpl.replace("{v}", String(v));
114
+ const candidate = `${dir}/pg_dump`;
115
+ if (!existsSync(candidate)) continue;
116
+ const major = await getPgDumpVersionAt(candidate);
117
+ if (major !== null && major >= serverMajor) {
118
+ return { path: candidate, major };
119
+ }
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+ function assertPgBinUsable() {
125
+ const named = process.env.SUPAFORGE_PG_BIN?.trim();
126
+ if (named && !existsSync(`${named}/pg_dump`)) {
127
+ throw new Error(
128
+ `SUPAFORGE_PG_BIN is set to "${named}", which has no pg_dump. Point it at a directory of PostgreSQL client tools, or unset it to use the ones on PATH.`
129
+ );
130
+ }
131
+ }
132
+ async function describeMissingPgDump(neededMajor) {
133
+ const onPath = await getLocalPgDumpVersion();
134
+ const named = process.env.SUPAFORGE_PG_BIN?.trim();
135
+ const namedMajor = named ? await getPgDumpVersionAt(`${named}/pg_dump`) : null;
136
+ const found = [
137
+ onPath === null ? "none on PATH" : `${onPath} on PATH`,
138
+ ...named ? [`${namedMajor ?? "none"} in SUPAFORGE_PG_BIN`] : []
139
+ ].join(", ");
140
+ return `no pg_dump ${neededMajor} or newer (found: ${found}); set SUPAFORGE_PG_BIN to a directory of PostgreSQL ${neededMajor}+ client tools`;
141
+ }
142
+ function resolvePgRestorePath(pgDumpPath) {
143
+ if (pgDumpPath === "pg_dump") return "pg_restore";
144
+ return pgDumpPath.replace(/pg_dump$/, "pg_restore");
145
+ }
146
+ function versionsToCheck(required) {
147
+ const versions = [];
148
+ for (let v = required + 3; v >= required; v--) {
149
+ versions.push(v);
150
+ }
151
+ return versions;
152
+ }
153
+ async function getServerMajorVersion(dbUrl) {
154
+ const client = newPgClient(dbUrl);
155
+ try {
156
+ await client.connect();
157
+ const { rows } = await client.query("SHOW server_version");
158
+ const raw = rows[0].server_version;
159
+ const major = parseServerVersion(raw);
160
+ if (!major) throw new Error(`Could not parse server version: ${raw}`);
161
+ return major;
162
+ } finally {
163
+ await client.end();
164
+ }
165
+ }
166
+ async function checkPgDumpCompat(dbUrl) {
167
+ const serverMajor = await getServerMajorVersion(dbUrl);
168
+ const resolved = await resolvePgDumpPath(serverMajor);
169
+ if (resolved) {
170
+ return {
171
+ localMajor: resolved.major,
172
+ serverMajor,
173
+ compatible: true,
174
+ message: "",
175
+ pgDumpPath: resolved.path,
176
+ pgRestorePath: resolvePgRestorePath(resolved.path)
177
+ };
178
+ }
179
+ const localMajor = await getLocalPgDumpVersion();
180
+ const message = buildInstallMessage(localMajor, serverMajor);
181
+ return {
182
+ localMajor,
183
+ serverMajor,
184
+ compatible: false,
185
+ message,
186
+ pgDumpPath: "pg_dump",
187
+ pgRestorePath: "pg_restore"
188
+ };
189
+ }
190
+ function buildInstallMessage(localMajor, serverMajor) {
191
+ const header = localMajor === null ? `pg_dump not found. The server is PostgreSQL ${serverMajor} \u2014 install postgresql-client-${serverMajor}:` : `pg_dump version mismatch: local v${localMajor}, server v${serverMajor}. Install postgresql-client-${serverMajor}:`;
192
+ const instructions = getInstallInstructions(serverMajor);
193
+ return `${header}
194
+
195
+ ${instructions}`;
196
+ }
197
+ function getInstallInstructions(majorVersion) {
198
+ const os = platform();
199
+ const v = majorVersion;
200
+ switch (os) {
201
+ case "darwin":
202
+ return [
203
+ ` brew install postgresql@${v}`,
204
+ ` # Then add to PATH:`,
205
+ ` export PATH="/opt/homebrew/opt/postgresql@${v}/bin:$PATH"`
206
+ ].join("\n");
207
+ case "linux":
208
+ return [
209
+ ` # Debian / Ubuntu:`,
210
+ ` sudo apt-get install -y postgresql-client-${v}`,
211
+ ` # If the package is not found, add the PGDG repository first:`,
212
+ ` # https://www.postgresql.org/download/linux/ubuntu/`,
213
+ ``,
214
+ ` # RHEL / Fedora:`,
215
+ ` sudo dnf install -y postgresql${v}`
216
+ ].join("\n");
217
+ case "win32":
218
+ return [
219
+ ` # Download the installer from:`,
220
+ ` # https://www.postgresql.org/download/windows/`,
221
+ ` # Or use Chocolatey:`,
222
+ ` choco install postgresql${v} --params '/Password:postgres'`
223
+ ].join("\n");
224
+ default:
225
+ return ` Download PostgreSQL ${v} client tools from: https://www.postgresql.org/download/`;
226
+ }
227
+ }
228
+
229
+ export {
230
+ slugify,
231
+ escapeRegex,
232
+ parseFlagList,
233
+ globToRegExp,
234
+ matchesGlob,
235
+ normalizeRoles,
236
+ resolvePgDumpPath,
237
+ assertPgBinUsable,
238
+ describeMissingPgDump,
239
+ getServerMajorVersion,
240
+ checkPgDumpCompat
241
+ };
242
+ //# sourceMappingURL=chunk-AGONS5JJ.js.map