@akal/supaforge 0.0.0-stage → 0.0.31

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 (99) hide show
  1. package/README.md +350 -2
  2. package/bin/dev.js +10 -0
  3. package/bin/run.js +18 -0
  4. package/dist/base-command.d.ts +134 -0
  5. package/dist/base-command.js +9 -0
  6. package/dist/base-command.js.map +1 -0
  7. package/dist/branch-C4ndfoj5.d.ts +58 -0
  8. package/dist/chunk-4OU7KO5Y.js +13 -0
  9. package/dist/chunk-4OU7KO5Y.js.map +1 -0
  10. package/dist/chunk-5QQBTLWO.js +642 -0
  11. package/dist/chunk-5QQBTLWO.js.map +1 -0
  12. package/dist/chunk-5Z3SAIQS.js +2807 -0
  13. package/dist/chunk-5Z3SAIQS.js.map +1 -0
  14. package/dist/chunk-6WAMNZLO.js +336 -0
  15. package/dist/chunk-6WAMNZLO.js.map +1 -0
  16. package/dist/chunk-BHYLBKYD.js +156 -0
  17. package/dist/chunk-BHYLBKYD.js.map +1 -0
  18. package/dist/chunk-BLKJWDTL.js +153 -0
  19. package/dist/chunk-BLKJWDTL.js.map +1 -0
  20. package/dist/chunk-DQQ5E563.js +64 -0
  21. package/dist/chunk-DQQ5E563.js.map +1 -0
  22. package/dist/chunk-G2DIPIYU.js +94 -0
  23. package/dist/chunk-G2DIPIYU.js.map +1 -0
  24. package/dist/chunk-H5MJ5DFX.js +16 -0
  25. package/dist/chunk-H5MJ5DFX.js.map +1 -0
  26. package/dist/chunk-KIFJGON5.js +248 -0
  27. package/dist/chunk-KIFJGON5.js.map +1 -0
  28. package/dist/chunk-LQXF65MC.js +240 -0
  29. package/dist/chunk-LQXF65MC.js.map +1 -0
  30. package/dist/chunk-NXRSAVRU.js +478 -0
  31. package/dist/chunk-NXRSAVRU.js.map +1 -0
  32. package/dist/chunk-PARSNTBD.js +837 -0
  33. package/dist/chunk-PARSNTBD.js.map +1 -0
  34. package/dist/chunk-RRMI5CZD.js +376 -0
  35. package/dist/chunk-RRMI5CZD.js.map +1 -0
  36. package/dist/chunk-SF3YA42C.js +506 -0
  37. package/dist/chunk-SF3YA42C.js.map +1 -0
  38. package/dist/chunk-TQJSQLWA.js +574 -0
  39. package/dist/chunk-TQJSQLWA.js.map +1 -0
  40. package/dist/chunk-VMTBLHN2.js +122 -0
  41. package/dist/chunk-VMTBLHN2.js.map +1 -0
  42. package/dist/chunk-VOXZWQ3N.js +948 -0
  43. package/dist/chunk-VOXZWQ3N.js.map +1 -0
  44. package/dist/chunk-X6V2GGDZ.js +333 -0
  45. package/dist/chunk-X6V2GGDZ.js.map +1 -0
  46. package/dist/chunk-XMYMIURR.js +552 -0
  47. package/dist/chunk-XMYMIURR.js.map +1 -0
  48. package/dist/chunk-YVDSR4GM.js +1264 -0
  49. package/dist/chunk-YVDSR4GM.js.map +1 -0
  50. package/dist/commands/clone.d.ts +66 -0
  51. package/dist/commands/clone.js +416 -0
  52. package/dist/commands/clone.js.map +1 -0
  53. package/dist/commands/diff.d.ts +65 -0
  54. package/dist/commands/diff.js +24 -0
  55. package/dist/commands/diff.js.map +1 -0
  56. package/dist/commands/help.d.ts +32 -0
  57. package/dist/commands/help.js +36 -0
  58. package/dist/commands/help.js.map +1 -0
  59. package/dist/commands/hukam.d.ts +13 -0
  60. package/dist/commands/hukam.js +29 -0
  61. package/dist/commands/hukam.js.map +1 -0
  62. package/dist/commands/init.d.ts +47 -0
  63. package/dist/commands/init.js +388 -0
  64. package/dist/commands/init.js.map +1 -0
  65. package/dist/commands/mcp.d.ts +13 -0
  66. package/dist/commands/mcp.js +44 -0
  67. package/dist/commands/mcp.js.map +1 -0
  68. package/dist/commands/migrate/baseline.d.ts +24 -0
  69. package/dist/commands/migrate/baseline.js +69 -0
  70. package/dist/commands/migrate/baseline.js.map +1 -0
  71. package/dist/commands/migrate/create.d.ts +36 -0
  72. package/dist/commands/migrate/create.js +128 -0
  73. package/dist/commands/migrate/create.js.map +1 -0
  74. package/dist/commands/migrate/list.d.ts +23 -0
  75. package/dist/commands/migrate/list.js +110 -0
  76. package/dist/commands/migrate/list.js.map +1 -0
  77. package/dist/commands/migrate/run.d.ts +61 -0
  78. package/dist/commands/migrate/run.js +19 -0
  79. package/dist/commands/migrate/run.js.map +1 -0
  80. package/dist/commands/report.d.ts +27 -0
  81. package/dist/commands/report.js +210 -0
  82. package/dist/commands/report.js.map +1 -0
  83. package/dist/commands/restore.d.ts +26 -0
  84. package/dist/commands/restore.js +268 -0
  85. package/dist/commands/restore.js.map +1 -0
  86. package/dist/commands/snapshot.d.ts +33 -0
  87. package/dist/commands/snapshot.js +251 -0
  88. package/dist/commands/snapshot.js.map +1 -0
  89. package/dist/commands/sync.d.ts +16 -0
  90. package/dist/commands/sync.js +39 -0
  91. package/dist/commands/sync.js.map +1 -0
  92. package/dist/config-CTbeRlJk.d.ts +134 -0
  93. package/dist/help.d.ts +28 -0
  94. package/dist/help.js +64 -0
  95. package/dist/help.js.map +1 -0
  96. package/dist/index.d.ts +493 -0
  97. package/dist/index.js +147 -0
  98. package/dist/index.js.map +1 -0
  99. package/package.json +74 -4
@@ -0,0 +1,1264 @@
1
+ import {
2
+ normalizeRoles
3
+ } from "./chunk-DQQ5E563.js";
4
+ import {
5
+ Check,
6
+ errMsg,
7
+ inRolledBackTransaction,
8
+ pgClientConfig,
9
+ pgQuery,
10
+ quoteIdent,
11
+ quoteLiteral,
12
+ quoteName
13
+ } from "./chunk-X6V2GGDZ.js";
14
+ import {
15
+ DEFAULT_IGNORE_SCHEMAS,
16
+ MIGRATIONS_SUBDIR,
17
+ RELATION_NOT_FOUND,
18
+ SNAPSHOTS_SUBDIR,
19
+ SUPABASE_MGMT_API,
20
+ SUPABASE_PLATFORM_SCHEMAS,
21
+ SUPAFORGE_DIR,
22
+ dim,
23
+ ok,
24
+ warn
25
+ } from "./chunk-6WAMNZLO.js";
26
+
27
+ // src/pg-tools.ts
28
+ import { execFile } from "child_process";
29
+ import { platform } from "os";
30
+ import { existsSync } from "fs";
31
+ import pg from "pg";
32
+ function parsePgDumpVersion(output) {
33
+ const m = output.match(/(\d+)(?:\.\d+)?/);
34
+ return m ? Number(m[1]) : null;
35
+ }
36
+ function parseServerVersion(versionStr) {
37
+ const m = versionStr.match(/^(\d+)/);
38
+ return m ? Number(m[1]) : null;
39
+ }
40
+ async function getLocalPgDumpVersion() {
41
+ return new Promise((resolve2) => {
42
+ execFile("pg_dump", ["--version"], (err, stdout) => {
43
+ if (err) return resolve2(null);
44
+ resolve2(parsePgDumpVersion(stdout));
45
+ });
46
+ });
47
+ }
48
+ function getPgDumpVersionAt(path) {
49
+ return new Promise((resolve2) => {
50
+ execFile(path, ["--version"], (err, stdout) => {
51
+ if (err) return resolve2(null);
52
+ resolve2(parsePgDumpVersion(stdout));
53
+ });
54
+ });
55
+ }
56
+ var VERSIONED_PG_DIRS = [
57
+ "/usr/lib/postgresql/{v}/bin",
58
+ // Debian / Ubuntu (PGDG)
59
+ "/opt/homebrew/opt/postgresql@{v}/bin",
60
+ // macOS Homebrew (Apple Silicon)
61
+ "/usr/local/opt/postgresql@{v}/bin",
62
+ // macOS Homebrew (Intel)
63
+ "/usr/pgsql-{v}/bin"
64
+ // RHEL / CentOS (PGDG)
65
+ ];
66
+ async function resolvePgDumpPath(serverMajor) {
67
+ const defaultMajor = await getLocalPgDumpVersion();
68
+ if (defaultMajor !== null && defaultMajor >= serverMajor) {
69
+ return { path: "pg_dump", major: defaultMajor };
70
+ }
71
+ const named = process.env.SUPAFORGE_PG_BIN?.trim();
72
+ if (named && existsSync(`${named}/pg_dump`)) {
73
+ const major = await getPgDumpVersionAt(`${named}/pg_dump`);
74
+ if (major !== null && major >= serverMajor) return { path: `${named}/pg_dump`, major };
75
+ }
76
+ for (const v of versionsToCheck(serverMajor)) {
77
+ for (const tmpl of VERSIONED_PG_DIRS) {
78
+ const dir = tmpl.replace("{v}", String(v));
79
+ const candidate = `${dir}/pg_dump`;
80
+ if (!existsSync(candidate)) continue;
81
+ const major = await getPgDumpVersionAt(candidate);
82
+ if (major !== null && major >= serverMajor) {
83
+ return { path: candidate, major };
84
+ }
85
+ }
86
+ }
87
+ return null;
88
+ }
89
+ function resolvePgRestorePath(pgDumpPath) {
90
+ if (pgDumpPath === "pg_dump") return "pg_restore";
91
+ return pgDumpPath.replace(/pg_dump$/, "pg_restore");
92
+ }
93
+ function versionsToCheck(required) {
94
+ const versions = [];
95
+ for (let v = required + 3; v >= required; v--) {
96
+ versions.push(v);
97
+ }
98
+ return versions;
99
+ }
100
+ async function getServerMajorVersion(dbUrl) {
101
+ const client = new pg.Client(pgClientConfig(dbUrl));
102
+ try {
103
+ await client.connect();
104
+ const { rows } = await client.query("SHOW server_version");
105
+ const raw = rows[0].server_version;
106
+ const major = parseServerVersion(raw);
107
+ if (!major) throw new Error(`Could not parse server version: ${raw}`);
108
+ return major;
109
+ } finally {
110
+ await client.end();
111
+ }
112
+ }
113
+ async function checkPgDumpCompat(dbUrl) {
114
+ const serverMajor = await getServerMajorVersion(dbUrl);
115
+ const resolved = await resolvePgDumpPath(serverMajor);
116
+ if (resolved) {
117
+ return {
118
+ localMajor: resolved.major,
119
+ serverMajor,
120
+ compatible: true,
121
+ message: "",
122
+ pgDumpPath: resolved.path,
123
+ pgRestorePath: resolvePgRestorePath(resolved.path)
124
+ };
125
+ }
126
+ const localMajor = await getLocalPgDumpVersion();
127
+ const message = buildInstallMessage(localMajor, serverMajor);
128
+ return {
129
+ localMajor,
130
+ serverMajor,
131
+ compatible: false,
132
+ message,
133
+ pgDumpPath: "pg_dump",
134
+ pgRestorePath: "pg_restore"
135
+ };
136
+ }
137
+ function buildInstallMessage(localMajor, serverMajor) {
138
+ 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}:`;
139
+ const instructions = getInstallInstructions(serverMajor);
140
+ return `${header}
141
+
142
+ ${instructions}`;
143
+ }
144
+ function getInstallInstructions(majorVersion) {
145
+ const os = platform();
146
+ const v = majorVersion;
147
+ switch (os) {
148
+ case "darwin":
149
+ return [
150
+ ` brew install postgresql@${v}`,
151
+ ` # Then add to PATH:`,
152
+ ` export PATH="/opt/homebrew/opt/postgresql@${v}/bin:$PATH"`
153
+ ].join("\n");
154
+ case "linux":
155
+ return [
156
+ ` # Debian / Ubuntu:`,
157
+ ` sudo apt-get install -y postgresql-client-${v}`,
158
+ ` # If the package is not found, add the PGDG repository first:`,
159
+ ` # https://www.postgresql.org/download/linux/ubuntu/`,
160
+ ``,
161
+ ` # RHEL / Fedora:`,
162
+ ` sudo dnf install -y postgresql${v}`
163
+ ].join("\n");
164
+ case "win32":
165
+ return [
166
+ ` # Download the installer from:`,
167
+ ` # https://www.postgresql.org/download/windows/`,
168
+ ` # Or use Chocolatey:`,
169
+ ` choco install postgresql${v} --params '/Password:postgres'`
170
+ ].join("\n");
171
+ default:
172
+ return ` Download PostgreSQL ${v} client tools from: https://www.postgresql.org/download/`;
173
+ }
174
+ }
175
+
176
+ // src/snapshot.ts
177
+ import { mkdir, writeFile, readFile, readdir, rm } from "fs/promises";
178
+ import { join, resolve } from "path";
179
+ import { execFile as execFileCb } from "child_process";
180
+ import { promisify } from "util";
181
+
182
+ // src/schema-introspect.ts
183
+ import pg2 from "pg";
184
+ async function introspectSchema(dbUrl, ignoreSchemas, clientQueryFn) {
185
+ let queryFn;
186
+ let pool;
187
+ if (clientQueryFn) {
188
+ queryFn = clientQueryFn;
189
+ } else {
190
+ pool = new pg2.Pool({ ...pgClientConfig(dbUrl), max: 6 });
191
+ queryFn = async (sql, params) => {
192
+ const { rows } = await pool.query(sql, params);
193
+ return rows;
194
+ };
195
+ }
196
+ try {
197
+ const schemaFilter = buildSchemaFilter(ignoreSchemas);
198
+ const [tables, views, functions, triggers, sequences, enums] = await Promise.all([
199
+ fetchTables(queryFn, schemaFilter),
200
+ fetchViews(queryFn, schemaFilter),
201
+ fetchFunctions(queryFn, schemaFilter),
202
+ fetchTriggers(queryFn, schemaFilter),
203
+ fetchSequences(queryFn, schemaFilter),
204
+ fetchEnums(queryFn, schemaFilter)
205
+ ]);
206
+ return { tables, views, functions, triggers, sequences, enums };
207
+ } finally {
208
+ await pool?.end();
209
+ }
210
+ }
211
+ function buildSchemaFilter(ignoreSchemas) {
212
+ if (ignoreSchemas.length === 0) {
213
+ return { clause: "", params: [] };
214
+ }
215
+ const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
216
+ return {
217
+ clause: `AND n.nspname NOT IN (${placeholders})`,
218
+ params: [...ignoreSchemas]
219
+ };
220
+ }
221
+ async function fetchTables(query, sf) {
222
+ const tableRows = await query(`
223
+ SELECT c.oid, n.nspname AS schema, c.relname AS name
224
+ FROM pg_class c
225
+ JOIN pg_namespace n ON n.oid = c.relnamespace
226
+ WHERE c.relkind IN ('r', 'p')
227
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
228
+ ${sf.clause}
229
+ ORDER BY n.nspname, c.relname
230
+ `, sf.params);
231
+ if (tableRows.length === 0) return [];
232
+ const oids = tableRows.map((t) => t.oid);
233
+ const [allColumns, allIndexes, allConstraints] = await Promise.all([
234
+ fetchColumns(query, oids),
235
+ fetchIndexes(query, oids),
236
+ fetchConstraints(query, oids)
237
+ ]);
238
+ return tableRows.map((t) => ({
239
+ schema: t.schema,
240
+ name: t.name,
241
+ columns: allColumns.get(t.oid) ?? [],
242
+ indexes: allIndexes.get(t.oid) ?? [],
243
+ constraints: allConstraints.get(t.oid) ?? []
244
+ }));
245
+ }
246
+ async function fetchColumns(query, oids) {
247
+ const rows = await query(`
248
+ SELECT
249
+ a.attrelid AS oid,
250
+ a.attname AS name,
251
+ pg_catalog.format_type(a.atttypid, a.atttypmod) AS type,
252
+ NOT a.attnotnull AS nullable,
253
+ pg_get_expr(d.adbin, d.adrelid) AS "default",
254
+ CASE a.attidentity WHEN 'a' THEN 'always' WHEN 'd' THEN 'by default' ELSE NULL END AS identity,
255
+ CASE a.attgenerated WHEN 's' THEN pg_get_expr(d.adbin, d.adrelid) ELSE NULL END AS generated
256
+ FROM pg_attribute a
257
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
258
+ WHERE a.attrelid = ANY($1)
259
+ AND a.attnum > 0
260
+ AND NOT a.attisdropped
261
+ ORDER BY a.attrelid, a.attnum
262
+ `, [oids]);
263
+ const map = /* @__PURE__ */ new Map();
264
+ for (const r of rows) {
265
+ const list = map.get(r.oid) ?? [];
266
+ list.push({ name: r.name, type: r.type, nullable: r.nullable, default: r.default, identity: r.identity, generated: r.generated });
267
+ map.set(r.oid, list);
268
+ }
269
+ return map;
270
+ }
271
+ async function fetchIndexes(query, oids) {
272
+ const rows = await query(`
273
+ SELECT
274
+ i.indrelid AS oid,
275
+ c.relname AS name,
276
+ pg_get_indexdef(i.indexrelid) AS definition,
277
+ i.indisunique AS unique
278
+ FROM pg_index i
279
+ JOIN pg_class c ON c.oid = i.indexrelid
280
+ WHERE i.indrelid = ANY($1)
281
+ AND NOT i.indisprimary
282
+ ORDER BY i.indrelid, c.relname
283
+ `, [oids]);
284
+ const map = /* @__PURE__ */ new Map();
285
+ for (const r of rows) {
286
+ const list = map.get(r.oid) ?? [];
287
+ list.push({ name: r.name, definition: r.definition, unique: r.unique });
288
+ map.set(r.oid, list);
289
+ }
290
+ return map;
291
+ }
292
+ async function fetchConstraints(query, oids) {
293
+ const rows = await query(`
294
+ SELECT
295
+ con.conrelid AS oid,
296
+ con.conname AS name,
297
+ CASE con.contype
298
+ WHEN 'p' THEN 'PRIMARY KEY'
299
+ WHEN 'u' THEN 'UNIQUE'
300
+ WHEN 'f' THEN 'FOREIGN KEY'
301
+ WHEN 'c' THEN 'CHECK'
302
+ WHEN 'x' THEN 'EXCLUDE'
303
+ ELSE con.contype::text
304
+ END AS type,
305
+ pg_get_constraintdef(con.oid) AS definition
306
+ FROM pg_constraint con
307
+ WHERE con.conrelid = ANY($1)
308
+ ORDER BY con.conrelid, con.conname
309
+ `, [oids]);
310
+ const map = /* @__PURE__ */ new Map();
311
+ for (const r of rows) {
312
+ const list = map.get(r.oid) ?? [];
313
+ list.push({ name: r.name, type: r.type, definition: r.definition });
314
+ map.set(r.oid, list);
315
+ }
316
+ return map;
317
+ }
318
+ async function fetchViews(query, sf) {
319
+ return await query(`
320
+ SELECT n.nspname AS schema, c.relname AS name, pg_get_viewdef(c.oid, true) AS definition
321
+ FROM pg_class c
322
+ JOIN pg_namespace n ON n.oid = c.relnamespace
323
+ WHERE c.relkind IN ('v', 'm')
324
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
325
+ ${sf.clause}
326
+ ORDER BY n.nspname, c.relname
327
+ `, sf.params);
328
+ }
329
+ async function fetchFunctions(query, sf) {
330
+ return await query(`
331
+ SELECT
332
+ n.nspname AS schema,
333
+ p.proname AS name,
334
+ pg_get_function_arguments(p.oid) AS args,
335
+ pg_get_function_result(p.oid) AS "returnType",
336
+ l.lanname AS language,
337
+ pg_get_functiondef(p.oid) AS definition
338
+ FROM pg_proc p
339
+ JOIN pg_namespace n ON n.oid = p.pronamespace
340
+ JOIN pg_language l ON l.oid = p.prolang
341
+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
342
+ ${sf.clause}
343
+ AND p.prokind IN ('f', 'p')
344
+ ORDER BY n.nspname, p.proname, pg_get_function_arguments(p.oid)
345
+ `, sf.params);
346
+ }
347
+ async function fetchTriggers(query, sf) {
348
+ return await query(`
349
+ SELECT
350
+ n.nspname AS schema,
351
+ c.relname AS table,
352
+ t.tgname AS name,
353
+ pg_get_triggerdef(t.oid) AS definition
354
+ FROM pg_trigger t
355
+ JOIN pg_class c ON c.oid = t.tgrelid
356
+ JOIN pg_namespace n ON n.oid = c.relnamespace
357
+ WHERE NOT t.tgisinternal
358
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
359
+ ${sf.clause}
360
+ ORDER BY n.nspname, c.relname, t.tgname
361
+ `, sf.params);
362
+ }
363
+ async function fetchSequences(query, sf) {
364
+ return await query(`
365
+ SELECT
366
+ n.nspname AS schema,
367
+ c.relname AS name,
368
+ format_type(s.seqtypid, NULL) AS "dataType",
369
+ s.seqstart::text AS "startValue",
370
+ s.seqincrement::text AS increment,
371
+ s.seqmin::text AS "minValue",
372
+ s.seqmax::text AS "maxValue"
373
+ FROM pg_sequence s
374
+ JOIN pg_class c ON c.oid = s.seqrelid
375
+ JOIN pg_namespace n ON n.oid = c.relnamespace
376
+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
377
+ ${sf.clause}
378
+ ORDER BY n.nspname, c.relname
379
+ `, sf.params);
380
+ }
381
+ async function fetchEnums(query, sf) {
382
+ const rows = await query(`
383
+ SELECT
384
+ n.nspname AS schema,
385
+ t.typname AS name,
386
+ array_agg(e.enumlabel ORDER BY e.enumsortorder) AS labels
387
+ FROM pg_type t
388
+ JOIN pg_namespace n ON n.oid = t.typnamespace
389
+ JOIN pg_enum e ON e.enumtypid = t.oid
390
+ WHERE t.typtype = 'e'
391
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
392
+ ${sf.clause}
393
+ GROUP BY n.nspname, t.typname
394
+ ORDER BY n.nspname, t.typname
395
+ `, sf.params);
396
+ return rows;
397
+ }
398
+
399
+ // src/utils/schema-policies.ts
400
+ function schemaPolicySql(schema) {
401
+ return `
402
+ SELECT tablename, policyname, permissive, roles, cmd, qual, with_check,
403
+ (SELECT obj_description(p.oid, 'pg_policy') FROM pg_policy p
404
+ JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace
405
+ WHERE n.nspname = pg_policies.schemaname AND c.relname = pg_policies.tablename
406
+ AND p.polname = pg_policies.policyname) AS comment
407
+ FROM pg_policies
408
+ WHERE schemaname = '${schema}'
409
+ ORDER BY tablename, policyname
410
+ `;
411
+ }
412
+ function policyKey(p) {
413
+ return `${p.tablename}.${p.policyname}`;
414
+ }
415
+ var policyTable = (schema, p) => `${quoteName(schema)}.${quoteName(p.tablename)}`;
416
+ var roleSql = (role) => role === "public" ? "PUBLIC" : quoteName(role);
417
+ function createPolicySql(schema, p) {
418
+ const roles = normalizeRoles(p.roles).map(roleSql).join(", ");
419
+ const lines = [
420
+ `CREATE POLICY ${quoteName(p.policyname)}`,
421
+ ` ON ${policyTable(schema, p)}`,
422
+ ` AS ${p.permissive}`,
423
+ ` FOR ${p.cmd}`,
424
+ ` TO ${roles}`
425
+ ];
426
+ if (p.qual) lines.push(` USING (${p.qual})`);
427
+ if (p.with_check) lines.push(` WITH CHECK (${p.with_check})`);
428
+ lines.push(";");
429
+ if (p.comment) lines.push(commentPolicySql(schema, p));
430
+ return lines.join("\n");
431
+ }
432
+ function commentPolicySql(schema, p) {
433
+ return `COMMENT ON POLICY ${quoteName(p.policyname)} ON ${policyTable(schema, p)} IS ${p.comment ? quoteLiteral(p.comment) : "NULL"};`;
434
+ }
435
+ function dropPolicySql(schema, p) {
436
+ return `DROP POLICY IF EXISTS ${quoteName(p.policyname)} ON ${policyTable(schema, p)};`;
437
+ }
438
+ function policiesEqual(a, b) {
439
+ return a.permissive === b.permissive && a.cmd === b.cmd && a.qual === b.qual && a.with_check === b.with_check && normalizeRoles(a.roles).join(",") === normalizeRoles(b.roles).join(",");
440
+ }
441
+ function diffSchemaPolicies(source, target, opts) {
442
+ const { schema, check, idPrefix, label } = opts;
443
+ const Label = label.charAt(0).toUpperCase() + label.slice(1);
444
+ const issues = [];
445
+ const sourceMap = new Map(source.map((p) => [policyKey(p), p]));
446
+ const targetMap = new Map(target.map((p) => [policyKey(p), p]));
447
+ for (const [key, sp] of sourceMap) {
448
+ if (targetMap.has(key)) continue;
449
+ issues.push({
450
+ id: `${idPrefix}-missing-${key}`,
451
+ check,
452
+ severity: "critical",
453
+ title: `Missing ${label} policy: ${sp.policyname} on ${sp.tablename}`,
454
+ description: `${Label} RLS policy "${sp.policyname}" on ${schema}.${sp.tablename} exists in source but not in target.`,
455
+ sourceValue: sp,
456
+ sql: {
457
+ up: createPolicySql(schema, sp),
458
+ down: dropPolicySql(schema, sp)
459
+ }
460
+ });
461
+ }
462
+ for (const [key, tp] of targetMap) {
463
+ if (sourceMap.has(key)) continue;
464
+ issues.push({
465
+ id: `${idPrefix}-extra-${key}`,
466
+ check,
467
+ severity: "info",
468
+ title: `Extra ${label} policy: ${tp.policyname} on ${tp.tablename}`,
469
+ description: `${Label} RLS policy "${tp.policyname}" on ${schema}.${tp.tablename} exists in target but not in source.`,
470
+ targetValue: tp,
471
+ sql: {
472
+ up: dropPolicySql(schema, tp),
473
+ down: createPolicySql(schema, tp)
474
+ }
475
+ });
476
+ }
477
+ for (const [key, sp] of sourceMap) {
478
+ const tp = targetMap.get(key);
479
+ if (!tp || policiesEqual(sp, tp)) continue;
480
+ issues.push({
481
+ id: `${idPrefix}-changed-${key}`,
482
+ check,
483
+ severity: "critical",
484
+ title: `${Label} policy changed: ${sp.policyname} on ${sp.tablename}`,
485
+ description: `${Label} RLS policy "${sp.policyname}" on ${schema}.${sp.tablename} differs between source and target.`,
486
+ sourceValue: sp,
487
+ targetValue: tp,
488
+ sql: {
489
+ up: [dropPolicySql(schema, sp), createPolicySql(schema, sp)].join("\n"),
490
+ down: [dropPolicySql(schema, tp), createPolicySql(schema, tp)].join("\n")
491
+ }
492
+ });
493
+ }
494
+ for (const [key, sp] of sourceMap) {
495
+ const tp = targetMap.get(key);
496
+ if (!tp || (sp.comment ?? null) === (tp.comment ?? null)) continue;
497
+ issues.push({
498
+ id: `${idPrefix}-comment-${key}`,
499
+ check,
500
+ severity: "info",
501
+ title: `${Label} policy comment changed: ${sp.policyname} on ${sp.tablename}`,
502
+ description: `The comment on ${label} RLS policy "${sp.policyname}" on ${schema}.${sp.tablename} differs between source and target.`,
503
+ sourceValue: sp.comment ?? null,
504
+ targetValue: tp.comment ?? null,
505
+ sql: {
506
+ up: commentPolicySql(schema, sp),
507
+ down: commentPolicySql(schema, tp)
508
+ }
509
+ });
510
+ }
511
+ return issues;
512
+ }
513
+
514
+ // src/utils/policy-equivalence.ts
515
+ var canonicalPolicyExpressions = async (dbUrl, policy) => {
516
+ try {
517
+ return await inRolledBackTransaction(dbUrl, async (client) => {
518
+ await client.query(
519
+ `CREATE TEMP TABLE sf_canon (LIKE ${quoteName(policy.schemaname)}.${quoteName(policy.tablename)})`
520
+ );
521
+ const command = (policy.cmd ?? "ALL").toUpperCase();
522
+ await client.query(
523
+ `CREATE POLICY sf_canon_p ON sf_canon FOR ${command}` + (policy.qual ? ` USING (${policy.qual})` : "") + (policy.with_check ? ` WITH CHECK (${policy.with_check})` : "")
524
+ );
525
+ const { rows } = await client.query(
526
+ `SELECT pg_get_expr(polqual, polrelid) AS qual, pg_get_expr(polwithcheck, polrelid) AS with_check
527
+ FROM pg_policy WHERE polrelid = 'pg_temp.sf_canon'::regclass`
528
+ );
529
+ return rows[0] ?? null;
530
+ });
531
+ } catch {
532
+ return null;
533
+ }
534
+ };
535
+ function defaultCanonicalizer(queryFn) {
536
+ return queryFn === pgQuery ? canonicalPolicyExpressions : async () => null;
537
+ }
538
+ async function dropEquivalentPolicyChanges(issues, ctx, canonicalize, schema) {
539
+ const withSchema = (p) => p && typeof p === "object" ? { schemaname: schema, ...p } : void 0;
540
+ const kept = [];
541
+ for (const issue of issues) {
542
+ const source = withSchema(issue.sourceValue);
543
+ const target = withSchema(issue.targetValue);
544
+ if (!isPolicy(source) || !isPolicy(target) || !sameApartFromExpressions(source, target)) {
545
+ kept.push(issue);
546
+ continue;
547
+ }
548
+ const [a, b] = await Promise.all([
549
+ canonicalize(ctx.source.dbUrl, source),
550
+ canonicalize(ctx.target.dbUrl, target)
551
+ ]);
552
+ if (a && b && a.qual === b.qual && a.with_check === b.with_check) continue;
553
+ kept.push(issue);
554
+ }
555
+ return kept;
556
+ }
557
+ function isPolicy(p) {
558
+ return !!p && typeof p.schemaname === "string" && typeof p.policyname === "string" && typeof p.tablename === "string" && "qual" in p;
559
+ }
560
+ function sameApartFromExpressions(a, b) {
561
+ return a.schemaname === b.schemaname && a.tablename === b.tablename && a.policyname === b.policyname && String(a.permissive) === String(b.permissive) && (a.cmd ?? null) === (b.cmd ?? null) && JSON.stringify(a.roles) === JSON.stringify(b.roles) && (a.qual !== b.qual || a.with_check !== b.with_check);
562
+ }
563
+
564
+ // src/checks/realtime.ts
565
+ var RealtimeCheck = class extends Check {
566
+ constructor(queryFn = pgQuery) {
567
+ super();
568
+ this.queryFn = queryFn;
569
+ }
570
+ name = "realtime";
571
+ async scan(ctx) {
572
+ const [source, target] = await Promise.all([
573
+ this.fetchPublications(ctx.source.dbUrl),
574
+ this.fetchPublications(ctx.target.dbUrl)
575
+ ]);
576
+ const publicationIssues = diffPublications(source, target);
577
+ const [srcPolicies, tgtPolicies] = await Promise.all([
578
+ this.fetchPolicies(ctx.source.dbUrl),
579
+ this.fetchPolicies(ctx.target.dbUrl)
580
+ ]);
581
+ const policyIssues = await dropEquivalentPolicyChanges(
582
+ diffSchemaPolicies(srcPolicies, tgtPolicies, {
583
+ schema: "realtime",
584
+ check: "realtime",
585
+ idPrefix: "realtime-policy",
586
+ label: "realtime authorization"
587
+ }),
588
+ ctx,
589
+ defaultCanonicalizer(this.queryFn),
590
+ "realtime"
591
+ );
592
+ return [...publicationIssues, ...policyIssues];
593
+ }
594
+ async fetchPolicies(dbUrl) {
595
+ try {
596
+ return await this.queryFn(dbUrl, schemaPolicySql("realtime"));
597
+ } catch {
598
+ return [];
599
+ }
600
+ }
601
+ async fetchPublications(dbUrl) {
602
+ try {
603
+ return await this.queryFn(dbUrl, PUBLICATION_SQL);
604
+ } catch {
605
+ return [];
606
+ }
607
+ }
608
+ };
609
+ var PLATFORM_PUBLICATIONS = ["supabase_realtime_messages_publication"];
610
+ var PUBLICATION_SQL = `
611
+ SELECT p.pubname, pt.schemaname, pt.tablename
612
+ FROM pg_publication p
613
+ LEFT JOIN pg_publication_tables pt
614
+ ON p.pubname = pt.pubname
615
+ AND pt.schemaname <> ALL (${sqlTextArray(DEFAULT_IGNORE_SCHEMAS)})
616
+ WHERE p.pubname <> ALL (${sqlTextArray(PLATFORM_PUBLICATIONS)})
617
+ ORDER BY p.pubname, pt.schemaname, pt.tablename
618
+ `;
619
+ function sqlTextArray(values) {
620
+ return `ARRAY[${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ")}]::text[]`;
621
+ }
622
+ function diffPublications(source, target) {
623
+ const issues = [];
624
+ const sourcePubs = new Set(source.map((p) => p.pubname));
625
+ const targetPubs = new Set(target.map((p) => p.pubname));
626
+ for (const pubname of sourcePubs) {
627
+ if (!targetPubs.has(pubname)) {
628
+ const tables = source.filter((p) => p.pubname === pubname && p.tablename);
629
+ issues.push({
630
+ id: `realtime-missing-pub-${pubname}`,
631
+ check: "realtime",
632
+ severity: "warning",
633
+ title: `Missing publication: ${pubname}`,
634
+ description: `Publication "${pubname}" exists in source but not in target.`,
635
+ sourceValue: tables,
636
+ sql: {
637
+ up: `CREATE PUBLICATION ${quoteName(pubname)}${tables.length > 0 ? ` FOR TABLE ${tables.map((t) => `${quoteName(t.schemaname)}.${quoteName(t.tablename)}`).join(", ")}` : ""};`,
638
+ down: `DROP PUBLICATION IF EXISTS ${quoteName(pubname)};`
639
+ }
640
+ });
641
+ }
642
+ }
643
+ for (const pubname of targetPubs) {
644
+ if (!sourcePubs.has(pubname)) {
645
+ issues.push({
646
+ id: `realtime-extra-pub-${pubname}`,
647
+ check: "realtime",
648
+ severity: "info",
649
+ title: `Extra publication: ${pubname}`,
650
+ description: `Publication "${pubname}" exists in target but not in source.`
651
+ });
652
+ }
653
+ }
654
+ const sharedPubs = [...sourcePubs].filter((p) => targetPubs.has(p));
655
+ for (const pubname of sharedPubs) {
656
+ const sourceTables = new Set(
657
+ source.filter((p) => p.pubname === pubname && p.tablename).map((p) => `${p.schemaname}.${p.tablename}`)
658
+ );
659
+ const targetTables = new Set(
660
+ target.filter((p) => p.pubname === pubname && p.tablename).map((p) => `${p.schemaname}.${p.tablename}`)
661
+ );
662
+ for (const fqn of sourceTables) {
663
+ if (!targetTables.has(fqn)) {
664
+ issues.push({
665
+ id: `realtime-missing-table-${pubname}-${fqn}`,
666
+ check: "realtime",
667
+ severity: "warning",
668
+ title: `Table not published: ${fqn} in ${pubname}`,
669
+ description: `Table "${fqn}" is published in source publication "${pubname}" but not in target.`,
670
+ sql: {
671
+ up: `ALTER PUBLICATION ${quoteName(pubname)} ADD TABLE ${fqn};`,
672
+ down: `ALTER PUBLICATION ${quoteName(pubname)} DROP TABLE ${fqn};`
673
+ }
674
+ });
675
+ }
676
+ }
677
+ for (const fqn of targetTables) {
678
+ if (!sourceTables.has(fqn)) {
679
+ issues.push({
680
+ id: `realtime-extra-table-${pubname}-${fqn}`,
681
+ check: "realtime",
682
+ severity: "info",
683
+ title: `Extra published table: ${fqn} in ${pubname}`,
684
+ description: `Table "${fqn}" is published in target publication "${pubname}" but not in source.`
685
+ });
686
+ }
687
+ }
688
+ }
689
+ return issues;
690
+ }
691
+
692
+ // src/snapshot.ts
693
+ var execFile2 = promisify(execFileCb);
694
+ function generateTimestamp() {
695
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
696
+ }
697
+ function snapshotsBaseDir(cwd) {
698
+ return resolve(cwd, SUPAFORGE_DIR, SNAPSHOTS_SUBDIR);
699
+ }
700
+ function snapshotDir(cwd, timestamp) {
701
+ return join(snapshotsBaseDir(cwd), timestamp);
702
+ }
703
+ async function captureSnapshot(options) {
704
+ const cwd = options.cwd ?? process.cwd();
705
+ const timestamp = generateTimestamp();
706
+ const dir = options.outputDir ? join(resolve(options.outputDir), timestamp) : snapshotDir(cwd, timestamp);
707
+ await mkdir(dir, { recursive: true });
708
+ const queryFn = options.queryFn ?? pgQuery;
709
+ const fetchFn = options.fetchFn ?? globalThis.fetch.bind(globalThis);
710
+ const ignoreSchemas = options.config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS;
711
+ const layers = {};
712
+ layers.schema = await captureSchema(dir, options.env.dbUrl, ignoreSchemas, queryFn);
713
+ layers.rls = await captureRlsPolicies(dir, options.env.dbUrl, ignoreSchemas, queryFn);
714
+ layers["edge-functions"] = await captureEdgeFunctions(dir, options.env, fetchFn);
715
+ layers.storage = await captureStorage(dir, options.env, queryFn);
716
+ layers.auth = await captureAuthConfig(dir, options.env, fetchFn);
717
+ layers.cron = await captureCronJobs(dir, options.env.dbUrl, queryFn);
718
+ const dataTables = options.config.checks?.data?.tables ?? [];
719
+ layers.data = await captureData(dir, options.env.dbUrl, dataTables, queryFn);
720
+ layers.webhooks = await captureWebhooks(dir, options.env.dbUrl, queryFn);
721
+ layers.extensions = await captureExtensions(dir, options.env.dbUrl, queryFn);
722
+ layers.realtime = await captureRealtime(dir, options.env.dbUrl, queryFn);
723
+ layers.vault = await captureVaultSecrets(dir, options.env.dbUrl, queryFn);
724
+ layers.roles = await captureRoleGrants(dir, options.env.dbUrl, queryFn);
725
+ const manifest = {
726
+ version: 1,
727
+ timestamp,
728
+ environment: options.envName,
729
+ projectRef: options.env.projectRef,
730
+ layers
731
+ };
732
+ await writeFile(join(dir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
733
+ return { manifest, dir, timestamp };
734
+ }
735
+ function formatSnapshotLayers(manifest) {
736
+ const layers = manifest.layers;
737
+ const lines = [];
738
+ for (const [name, info] of Object.entries(layers)) {
739
+ if (info.captured) {
740
+ lines.push(`${ok("\u2713")} ${name.padEnd(16)} ${info.itemCount} item(s)`);
741
+ } else if (info.error) {
742
+ lines.push(`${warn("\u2717")} ${name.padEnd(16)} ${warn(`error: ${info.error}`)}`);
743
+ } else {
744
+ const skipSuffix = info.skipReason ? ` \u2014 ${info.skipReason}` : "";
745
+ lines.push(`${dim("\u25CB")} ${name.padEnd(16)} ${dim(`skipped${skipSuffix}`)}`);
746
+ }
747
+ }
748
+ return lines;
749
+ }
750
+ async function captureSchema(dir, dbUrl, ignoreSchemas, queryFn) {
751
+ const file = "schema.json";
752
+ try {
753
+ const schema = await introspectSchema(dbUrl, ignoreSchemas);
754
+ await writeFile(join(dir, file), JSON.stringify(schema, null, 2) + "\n");
755
+ return {
756
+ captured: true,
757
+ file,
758
+ itemCount: schema.tables.length,
759
+ ...await captureSchemaSql(dir, dbUrl, [
760
+ .../* @__PURE__ */ new Set([...schemasIn(schema), ...await projectSchemas(dbUrl, ignoreSchemas, queryFn)])
761
+ ].sort())
762
+ };
763
+ } catch (err) {
764
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
765
+ }
766
+ }
767
+ async function projectSchemas(dbUrl, ignoreSchemas, queryFn) {
768
+ const rows = await queryFn(dbUrl, `SELECT n.nspname AS name FROM pg_namespace n
769
+ WHERE n.nspname NOT LIKE 'pg\\_%' AND n.nspname <> 'information_schema'
770
+ AND n.nspname <> ALL($1::text[])
771
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_namespace'::regclass
772
+ AND d.objid = n.oid AND d.deptype = 'e')`, [ignoreSchemas]);
773
+ return rows.map((r) => r.name);
774
+ }
775
+ function schemasIn(schema) {
776
+ const names = /* @__PURE__ */ new Set();
777
+ for (const group of [
778
+ schema.tables,
779
+ schema.views,
780
+ schema.functions,
781
+ schema.triggers,
782
+ schema.sequences,
783
+ schema.enums
784
+ ]) {
785
+ for (const item of group) {
786
+ if (item.schema) names.add(item.schema);
787
+ }
788
+ }
789
+ return names.size > 0 ? [...names].sort() : ["public"];
790
+ }
791
+ async function captureSchemaSql(dir, dbUrl, schemas) {
792
+ const sqlFile = "schema.sql";
793
+ try {
794
+ const serverMajor = await getServerMajorVersion(dbUrl);
795
+ const resolved = await resolvePgDumpPath(serverMajor);
796
+ if (!resolved) {
797
+ return {
798
+ sqlSkipReason: `no pg_dump new enough for this server (needs ${serverMajor} or later) \u2014 schema.json was still captured, but restore cannot replay the schema`
799
+ };
800
+ }
801
+ const { stdout } = await execFile2(resolved.path, [
802
+ dbUrl,
803
+ "--schema-only",
804
+ "--no-owner",
805
+ "--no-privileges",
806
+ // Quoted: pg_dump reads --schema as a pattern, folding `App Data` to lower case.
807
+ ...schemas.map((s) => `--schema=${quoteName(s)}`)
808
+ ], { maxBuffer: 256 * 1024 * 1024, timeout: 3e5 });
809
+ if (stdout.trim().length === 0) {
810
+ return { sqlSkipReason: "pg_dump produced an empty schema dump" };
811
+ }
812
+ await writeFile(join(dir, sqlFile), stdout);
813
+ return { sqlFile };
814
+ } catch (err) {
815
+ return { sqlSkipReason: errMsg(err) };
816
+ }
817
+ }
818
+ var POLICY_COMMENT = `(SELECT obj_description(p.oid, 'pg_policy') FROM pg_policy p
819
+ JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace
820
+ WHERE n.nspname = pg_policies.schemaname AND c.relname = pg_policies.tablename
821
+ AND p.polname = pg_policies.policyname) AS comment`;
822
+ async function captureRlsPolicies(dir, dbUrl, ignoreSchemas, queryFn) {
823
+ const file = "rls.sql";
824
+ try {
825
+ const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
826
+ const sql = ignoreSchemas.length > 0 ? `SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check, ${POLICY_COMMENT}
827
+ FROM pg_policies WHERE schemaname NOT IN (${placeholders})
828
+ ORDER BY schemaname, tablename, policyname` : `SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check, ${POLICY_COMMENT}
829
+ FROM pg_policies ORDER BY schemaname, tablename, policyname`;
830
+ const rows = await queryFn(dbUrl, sql, ignoreSchemas.length > 0 ? ignoreSchemas : void 0);
831
+ const statements = rows.map((p) => generateCreatePolicySql(p));
832
+ const output = statements.length > 0 ? `-- SupaForge RLS Policy Snapshot
833
+ -- ${rows.length} policies
834
+
835
+ ${statements.join("\n\n")}
836
+ ` : "-- No RLS policies found\n";
837
+ await writeFile(join(dir, file), output);
838
+ return { captured: true, file, itemCount: rows.length };
839
+ } catch (err) {
840
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
841
+ }
842
+ }
843
+ async function captureEdgeFunctions(dir, env, fetchFn) {
844
+ const file = "edge-functions.json";
845
+ const token = env.accessToken;
846
+ if (!env.projectRef || !token) {
847
+ return { captured: false, file, itemCount: 0, skipReason: "no projectRef or accessToken configured" };
848
+ }
849
+ try {
850
+ const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(env.projectRef)}/functions`;
851
+ const res = await fetchFn(url, {
852
+ headers: { Authorization: `Bearer ${token}` }
853
+ });
854
+ if (!res.ok) throw new Error(res.statusText);
855
+ const functions = await res.json();
856
+ await writeFile(join(dir, file), JSON.stringify(functions, null, 2) + "\n");
857
+ return { captured: true, file, itemCount: functions.length };
858
+ } catch (err) {
859
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
860
+ }
861
+ }
862
+ async function captureStorage(dir, env, queryFn) {
863
+ let bucketCount = 0;
864
+ let policyCount = 0;
865
+ let storageError;
866
+ const bucketsFile = "storage-buckets.json";
867
+ try {
868
+ const buckets = await queryFn(env.dbUrl, `
869
+ SELECT id, name, public, file_size_limit, allowed_mime_types,
870
+ avif_autodetection, created_at, updated_at
871
+ FROM storage.buckets
872
+ ORDER BY name
873
+ `);
874
+ await writeFile(join(dir, bucketsFile), JSON.stringify(buckets, null, 2) + "\n");
875
+ bucketCount = buckets.length;
876
+ } catch {
877
+ }
878
+ const policiesFile = "storage-policies.sql";
879
+ try {
880
+ const rows = await queryFn(env.dbUrl, schemaPolicySql("storage"));
881
+ const statements = rows.map((p) => (
882
+ // Dropped first so a snapshot can be restored twice, as below.
883
+ `${dropPolicySql("storage", p)}
884
+ ${createPolicySql("storage", p)}`
885
+ ));
886
+ const output = statements.length > 0 ? `-- SupaForge Storage Policy Snapshot
887
+ -- ${rows.length} policies
888
+
889
+ ${statements.join("\n\n")}
890
+ ` : "-- No storage policies found\n";
891
+ await writeFile(join(dir, policiesFile), output);
892
+ policyCount = rows.length;
893
+ } catch (err) {
894
+ storageError = errMsg(err);
895
+ }
896
+ const captured = bucketCount > 0 || policyCount > 0;
897
+ return {
898
+ captured,
899
+ file: bucketsFile,
900
+ itemCount: bucketCount + policyCount,
901
+ ...storageError && !policyCount ? { error: storageError } : {},
902
+ ...!captured && !storageError ? { skipReason: "no storage buckets or policies found" } : {}
903
+ };
904
+ }
905
+ async function captureAuthConfig(dir, env, fetchFn) {
906
+ const file = "auth.json";
907
+ const token = env.accessToken;
908
+ if (!env.projectRef || !token) {
909
+ return { captured: false, file, itemCount: 0, skipReason: "no projectRef or accessToken configured" };
910
+ }
911
+ try {
912
+ const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(env.projectRef)}/config/auth`;
913
+ const res = await fetchFn(url, {
914
+ headers: { Authorization: `Bearer ${token}` }
915
+ });
916
+ if (!res.ok) throw new Error(res.statusText);
917
+ const config = await res.json();
918
+ await writeFile(join(dir, file), JSON.stringify(config, null, 2) + "\n");
919
+ return { captured: true, file, itemCount: Object.keys(config).length };
920
+ } catch (err) {
921
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
922
+ }
923
+ }
924
+ async function captureCronJobs(dir, dbUrl, queryFn) {
925
+ const file = "cron.sql";
926
+ try {
927
+ const rows = await queryFn(dbUrl, `
928
+ SELECT jobid, schedule, command, nodename, nodeport, database, username, active, jobname
929
+ FROM cron.job ORDER BY jobname, jobid
930
+ `);
931
+ const statements = rows.map((job) => {
932
+ const name = job.jobname ?? `job-${job.jobid}`;
933
+ return `SELECT cron.schedule('${name}', '${job.schedule}', $$${job.command}$$);`;
934
+ });
935
+ const output = statements.length > 0 ? `-- SupaForge Cron Job Snapshot
936
+ -- ${rows.length} jobs
937
+
938
+ ${statements.join("\n\n")}
939
+ ` : "-- No cron jobs found (pg_cron may not be installed)\n";
940
+ await writeFile(join(dir, file), output);
941
+ return { captured: true, file, itemCount: rows.length };
942
+ } catch (err) {
943
+ const msg = errMsg(err);
944
+ await writeFile(join(dir, file), "-- pg_cron extension not available\n").catch(() => {
945
+ });
946
+ if (msg.includes(RELATION_NOT_FOUND)) {
947
+ return { captured: false, file, itemCount: 0, skipReason: "pg_cron extension not installed" };
948
+ }
949
+ return { captured: false, file, itemCount: 0, error: msg };
950
+ }
951
+ }
952
+ async function captureData(dir, dbUrl, tables, queryFn) {
953
+ if (tables.length === 0) {
954
+ return { captured: false, file: "data/", itemCount: 0, skipReason: "no tables configured in checks.data.tables" };
955
+ }
956
+ const dataDir = join(dir, "data");
957
+ await mkdir(dataDir, { recursive: true });
958
+ let captured = 0;
959
+ const errors = [];
960
+ for (const table of tables) {
961
+ try {
962
+ await writeFile(join(dataDir, `${table}.json`), await capturedRows(dbUrl, table, queryFn) + "\n");
963
+ captured++;
964
+ } catch (err) {
965
+ errors.push(`${table}: ${errMsg(err)}`);
966
+ }
967
+ }
968
+ return {
969
+ captured: captured > 0,
970
+ file: "data/",
971
+ itemCount: captured,
972
+ ...errors.length > 0 ? { error: errors.join("; ") } : {}
973
+ };
974
+ }
975
+ async function capturedRows(dbUrl, table, queryFn) {
976
+ const columns = (await queryFn(dbUrl, `SELECT attname AS name FROM pg_attribute
977
+ WHERE attrelid = ${quoteLiteral(quoteIdent(table))}::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`)).map((c) => c.name);
978
+ const keys = columns.map(quoteLiteral).join(", ");
979
+ const values = columns.map((c) => `t.${quoteName(c)}::text`).join(", ");
980
+ const [{ rows }] = await queryFn(dbUrl, `SELECT jsonb_pretty(jsonb_build_object('format', 'text', 'rows',
981
+ coalesce(jsonb_agg(json_object(ARRAY[${keys}]::text[], ARRAY[${values}]::text[])::jsonb), '[]'::jsonb))) AS rows
982
+ FROM (SELECT * FROM ${quoteIdent(table)} ORDER BY 1) t`);
983
+ return rows;
984
+ }
985
+ async function captureWebhooks(dir, dbUrl, queryFn) {
986
+ const file = "webhooks.sql";
987
+ try {
988
+ const rows = await queryFn(dbUrl, `
989
+ SELECT n.nspname || '.' || c.relname AS table_name,
990
+ t.tgname AS name,
991
+ pg_get_triggerdef(t.oid) AS definition
992
+ FROM pg_trigger t
993
+ JOIN pg_class c ON c.oid = t.tgrelid
994
+ JOIN pg_namespace n ON n.oid = c.relnamespace
995
+ JOIN pg_proc p ON p.oid = t.tgfoid
996
+ JOIN pg_namespace pn ON pn.oid = p.pronamespace
997
+ WHERE NOT t.tgisinternal
998
+ AND pn.nspname = 'supabase_functions'
999
+ AND p.proname = 'http_request'
1000
+ ORDER BY 1, 2
1001
+ `);
1002
+ const statements = rows.filter((h) => h.definition).map((hook) => [
1003
+ `-- Webhook: ${hook.name} on ${hook.table_name}`,
1004
+ `${hook.definition.replace(/;\s*$/, "")};`
1005
+ ].join("\n"));
1006
+ const output = statements.length > 0 ? `-- SupaForge Webhook Snapshot
1007
+ -- ${statements.length} webhooks
1008
+
1009
+ ${statements.join("\n\n")}
1010
+ ` : "-- No webhooks found\n";
1011
+ await writeFile(join(dir, file), output);
1012
+ return { captured: true, file, itemCount: statements.length };
1013
+ } catch (err) {
1014
+ const msg = errMsg(err);
1015
+ await writeFile(join(dir, file), `-- Webhook snapshot failed: ${msg}
1016
+ `).catch(() => {
1017
+ });
1018
+ return { captured: false, file, itemCount: 0, error: msg };
1019
+ }
1020
+ }
1021
+ async function captureRealtime(dir, dbUrl, queryFn) {
1022
+ const file = "realtime.sql";
1023
+ try {
1024
+ const rows = await queryFn(dbUrl, PUBLICATION_SQL);
1025
+ const byPublication = /* @__PURE__ */ new Map();
1026
+ for (const row of rows) {
1027
+ const tables = byPublication.get(row.pubname) ?? [];
1028
+ if (row.schemaname && row.tablename) {
1029
+ tables.push(`${quoteName(row.schemaname)}.${quoteName(row.tablename)}`);
1030
+ }
1031
+ byPublication.set(row.pubname, tables);
1032
+ }
1033
+ const statements = [];
1034
+ for (const [pubname, tables] of byPublication) {
1035
+ statements.push(`-- Publication: ${pubname}`);
1036
+ statements.push(`DO $$ BEGIN
1037
+ IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = ${quoteLiteral(pubname)}) THEN
1038
+ EXECUTE ${quoteLiteral(`CREATE PUBLICATION ${quoteName(pubname)}`)};
1039
+ END IF;
1040
+ END $$;`);
1041
+ for (const table of tables) {
1042
+ statements.push(`ALTER PUBLICATION ${quoteName(pubname)} ADD TABLE ${table};`);
1043
+ }
1044
+ }
1045
+ const output = statements.length > 0 ? `-- SupaForge Realtime Snapshot
1046
+ -- ${byPublication.size} publication(s)
1047
+
1048
+ ${statements.join("\n")}
1049
+ ` : "-- No publications found\n";
1050
+ await writeFile(join(dir, file), output);
1051
+ return { captured: true, file, itemCount: byPublication.size };
1052
+ } catch (err) {
1053
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
1054
+ }
1055
+ }
1056
+ async function captureVaultSecrets(dir, dbUrl, queryFn) {
1057
+ const file = "vault.sql";
1058
+ try {
1059
+ const rows = await queryFn(dbUrl, `
1060
+ SELECT coalesce(name, id::text) AS name, description
1061
+ FROM vault.secrets
1062
+ ORDER BY 1
1063
+ `);
1064
+ const lines = rows.map((row) => `-- ${row.name}${row.description ? ` \u2014 ${row.description}` : ""}`);
1065
+ const output = rows.length > 0 ? `-- SupaForge Vault Snapshot
1066
+ -- ${rows.length} secret(s), names only:
1067
+ -- the values cannot be read out of Vault and must be recreated by hand.
1068
+ ${lines.join("\n")}
1069
+ ` : "-- No vault secrets found\n";
1070
+ await writeFile(join(dir, file), output);
1071
+ return { captured: true, file, itemCount: rows.length };
1072
+ } catch (err) {
1073
+ if (!await vaultInstalled(dbUrl, queryFn)) {
1074
+ return { captured: false, file, itemCount: 0, skipReason: "vault extension not installed" };
1075
+ }
1076
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
1077
+ }
1078
+ }
1079
+ async function vaultInstalled(dbUrl, queryFn) {
1080
+ try {
1081
+ const [row] = await queryFn(dbUrl, `SELECT to_regnamespace('vault') IS NOT NULL AS installed`);
1082
+ return row?.installed === true;
1083
+ } catch {
1084
+ return true;
1085
+ }
1086
+ }
1087
+ async function captureRoleGrants(dir, dbUrl, queryFn) {
1088
+ const file = "roles.sql";
1089
+ const excluded = SUPABASE_PLATFORM_SCHEMAS.map(quoteLiteral).join(", ");
1090
+ try {
1091
+ const rows = await queryFn(dbUrl, `
1092
+ -- From relacl, not information_schema.role_table_grants: that view
1093
+ -- counts the owner's own privileges as grants, which a restore then
1094
+ -- replayed as GRANT ... TO <owner>, creating the role on the target;
1095
+ -- and it hides grants the connecting role takes no part in.
1096
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
1097
+ n.nspname AS table_schema, c.relname AS table_name, NULL::text AS column_name,
1098
+ a.privilege_type, a.is_grantable
1099
+ FROM pg_class c
1100
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1101
+ CROSS JOIN LATERAL aclexplode(c.relacl) a
1102
+ WHERE c.relacl IS NOT NULL AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
1103
+ AND a.grantee <> c.relowner
1104
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (
1105
+ 'postgres','supabase_admin','authenticator','supabase_auth_admin',
1106
+ 'supabase_storage_admin','dashboard_user','pgbouncer','supavisor'
1107
+ ))
1108
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg\\_%')
1109
+ AND n.nspname NOT IN (${excluded})
1110
+ UNION ALL
1111
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END,
1112
+ n.nspname, c.relname, att.attname, a.privilege_type, a.is_grantable
1113
+ FROM pg_attribute att
1114
+ JOIN pg_class c ON c.oid = att.attrelid
1115
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1116
+ CROSS JOIN LATERAL aclexplode(att.attacl) a
1117
+ WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
1118
+ AND a.grantee <> c.relowner
1119
+ AND n.nspname NOT IN (${excluded})
1120
+ ORDER BY 1, 2, 3, 4, 5
1121
+ `);
1122
+ const grouped = /* @__PURE__ */ new Map();
1123
+ for (const row of rows) {
1124
+ const key = JSON.stringify([
1125
+ row.grantee,
1126
+ row.table_schema,
1127
+ row.table_name,
1128
+ row.column_name,
1129
+ Boolean(row.is_grantable),
1130
+ row.privilege_type === "MAINTAIN"
1131
+ ]);
1132
+ grouped.set(key, [...grouped.get(key) ?? [], row]);
1133
+ }
1134
+ const statements = [...grouped.values()].map(([row, ...rest]) => `GRANT ${[row, ...rest].map((r) => r.privilege_type + (r.column_name ? ` (${quoteName(r.column_name)})` : "")).join(", ")} ON ${quoteName(row.table_schema)}.${quoteName(row.table_name)} TO ${row.grantee === "PUBLIC" ? "PUBLIC" : quoteName(row.grantee)}` + (row.is_grantable ? " WITH GRANT OPTION" : "") + ";");
1135
+ const output = statements.length > 0 ? `-- SupaForge Role Grants Snapshot
1136
+ -- ${rows.length} grant(s)
1137
+
1138
+ ${statements.join("\n")}
1139
+ ` : "-- No role grants found\n";
1140
+ await writeFile(join(dir, file), output);
1141
+ return { captured: true, file, itemCount: rows.length };
1142
+ } catch (err) {
1143
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
1144
+ }
1145
+ }
1146
+ async function captureExtensions(dir, dbUrl, queryFn) {
1147
+ const file = "extensions.sql";
1148
+ try {
1149
+ const rows = await queryFn(dbUrl, `
1150
+ SELECT extname, extversion, n.nspname AS schema
1151
+ FROM pg_extension e
1152
+ JOIN pg_namespace n ON n.oid = e.extnamespace
1153
+ ORDER BY extname
1154
+ `);
1155
+ const statements = rows.map((ext) => {
1156
+ return `CREATE EXTENSION IF NOT EXISTS ${quoteName(ext.extname)} WITH SCHEMA ${quoteName(ext.schema)};`;
1157
+ });
1158
+ const output = statements.length > 0 ? `-- SupaForge Extensions Snapshot
1159
+ -- ${rows.length} extensions
1160
+
1161
+ ${statements.join("\n")}
1162
+ ` : "-- No extensions found\n";
1163
+ await writeFile(join(dir, file), output);
1164
+ return { captured: true, file, itemCount: rows.length };
1165
+ } catch (err) {
1166
+ return { captured: false, file, itemCount: 0, error: errMsg(err) };
1167
+ }
1168
+ }
1169
+ async function loadSnapshot(dir) {
1170
+ const raw = await readFile(join(dir, "manifest.json"), "utf-8");
1171
+ return JSON.parse(raw);
1172
+ }
1173
+ async function findLatestSnapshot(cwd = process.cwd()) {
1174
+ const base = snapshotsBaseDir(cwd);
1175
+ try {
1176
+ const entries = await readdir(base);
1177
+ const sorted = entries.filter((e) => /^\d{8}T\d{6}Z$/.test(e)).sort();
1178
+ return sorted.length > 0 ? join(base, sorted[sorted.length - 1]) : null;
1179
+ } catch {
1180
+ return null;
1181
+ }
1182
+ }
1183
+ async function listSnapshots(cwd = process.cwd()) {
1184
+ const base = snapshotsBaseDir(cwd);
1185
+ try {
1186
+ const entries = await readdir(base);
1187
+ const sorted = entries.filter((e) => /^\d{8}T\d{6}Z$/.test(e)).sort();
1188
+ const results = [];
1189
+ for (const entry of sorted) {
1190
+ try {
1191
+ const manifest = await loadSnapshot(join(base, entry));
1192
+ results.push({ dir: join(base, entry), manifest });
1193
+ } catch {
1194
+ }
1195
+ }
1196
+ return results;
1197
+ } catch {
1198
+ return [];
1199
+ }
1200
+ }
1201
+ var DEFAULT_KEEP_COUNT = 7;
1202
+ async function pruneSnapshots(keep = DEFAULT_KEEP_COUNT, cwd = process.cwd()) {
1203
+ const snapshots = await listSnapshots(cwd);
1204
+ if (snapshots.length <= keep) {
1205
+ return { deleted: [], kept: snapshots.map((s) => s.dir) };
1206
+ }
1207
+ const candidates = snapshots.slice(0, snapshots.length - keep);
1208
+ const withinBudget = snapshots.slice(snapshots.length - keep);
1209
+ const referenced = await snapshotVersionsReferencedByMigrations(cwd);
1210
+ const toDelete = candidates.filter((s) => !referenced.has(versionOf(s.dir)));
1211
+ const retained = candidates.filter((s) => referenced.has(versionOf(s.dir)));
1212
+ for (const snap of toDelete) {
1213
+ await rm(snap.dir, { recursive: true, force: true });
1214
+ }
1215
+ return {
1216
+ deleted: toDelete.map((s) => s.dir),
1217
+ kept: [...retained, ...withinBudget].map((s) => s.dir),
1218
+ retainedForMigrations: retained.map((s) => s.dir)
1219
+ };
1220
+ }
1221
+ function versionOf(dir) {
1222
+ return dir.split("/").filter(Boolean).pop() ?? dir;
1223
+ }
1224
+ async function snapshotVersionsReferencedByMigrations(cwd) {
1225
+ const referenced = /* @__PURE__ */ new Set();
1226
+ try {
1227
+ const dir = resolve(cwd, SUPAFORGE_DIR, MIGRATIONS_SUBDIR);
1228
+ for (const name of await readdir(dir)) {
1229
+ if (!name.endsWith(".json")) continue;
1230
+ try {
1231
+ const migration = JSON.parse(await readFile(join(dir, name), "utf-8"));
1232
+ if (migration.parent) referenced.add(migration.parent);
1233
+ } catch {
1234
+ }
1235
+ }
1236
+ } catch {
1237
+ }
1238
+ return referenced;
1239
+ }
1240
+ function generateCreatePolicySql(p) {
1241
+ return `${dropPolicySql(p.schemaname, p)}
1242
+ ${createPolicySql(p.schemaname, p)}`;
1243
+ }
1244
+
1245
+ export {
1246
+ schemaPolicySql,
1247
+ createPolicySql,
1248
+ dropPolicySql,
1249
+ diffSchemaPolicies,
1250
+ defaultCanonicalizer,
1251
+ dropEquivalentPolicyChanges,
1252
+ RealtimeCheck,
1253
+ resolvePgDumpPath,
1254
+ getServerMajorVersion,
1255
+ checkPgDumpCompat,
1256
+ captureSnapshot,
1257
+ formatSnapshotLayers,
1258
+ loadSnapshot,
1259
+ findLatestSnapshot,
1260
+ listSnapshots,
1261
+ DEFAULT_KEEP_COUNT,
1262
+ pruneSnapshots
1263
+ };
1264
+ //# sourceMappingURL=chunk-YVDSR4GM.js.map