@akal/supaforge 0.0.31 → 0.0.33

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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -11
  3. package/dist/base-command.d.ts +1 -0
  4. package/dist/base-command.js +2 -2
  5. package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
  6. package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
  7. package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
  8. package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
  9. package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
  10. package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
  11. package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
  12. package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
  13. package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
  14. package/dist/chunk-GZREXCQZ.js +207 -0
  15. package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
  16. package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
  17. package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
  18. package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
  19. package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
  20. package/dist/chunk-UWAVXC57.js +916 -0
  21. package/dist/commands/clone.js +10 -10
  22. package/dist/commands/diff.d.ts +16 -0
  23. package/dist/commands/diff.js +11 -12
  24. package/dist/commands/hukam.js +11 -12
  25. package/dist/commands/mcp.d.ts +1 -0
  26. package/dist/commands/mcp.js +18 -9
  27. package/dist/commands/migrate/baseline.js +3 -3
  28. package/dist/commands/migrate/create.js +5 -6
  29. package/dist/commands/migrate/list.js +4 -4
  30. package/dist/commands/migrate/run.js +5 -6
  31. package/dist/commands/report.js +3 -3
  32. package/dist/commands/restore.js +11 -13
  33. package/dist/commands/snapshot.js +6 -8
  34. package/dist/commands/sync.js +11 -12
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +16 -16
  37. package/package.json +10 -8
  38. package/bin/dev.js +0 -10
  39. package/dist/base-command.js.map +0 -1
  40. package/dist/chunk-4OU7KO5Y.js.map +0 -1
  41. package/dist/chunk-5QQBTLWO.js.map +0 -1
  42. package/dist/chunk-5Z3SAIQS.js.map +0 -1
  43. package/dist/chunk-6WAMNZLO.js.map +0 -1
  44. package/dist/chunk-BHYLBKYD.js.map +0 -1
  45. package/dist/chunk-BLKJWDTL.js.map +0 -1
  46. package/dist/chunk-DQQ5E563.js.map +0 -1
  47. package/dist/chunk-G2DIPIYU.js.map +0 -1
  48. package/dist/chunk-H5MJ5DFX.js +0 -16
  49. package/dist/chunk-H5MJ5DFX.js.map +0 -1
  50. package/dist/chunk-KIFJGON5.js.map +0 -1
  51. package/dist/chunk-LQXF65MC.js.map +0 -1
  52. package/dist/chunk-NXRSAVRU.js.map +0 -1
  53. package/dist/chunk-PARSNTBD.js.map +0 -1
  54. package/dist/chunk-RRMI5CZD.js +0 -376
  55. package/dist/chunk-RRMI5CZD.js.map +0 -1
  56. package/dist/chunk-SF3YA42C.js +0 -506
  57. package/dist/chunk-SF3YA42C.js.map +0 -1
  58. package/dist/chunk-TQJSQLWA.js.map +0 -1
  59. package/dist/chunk-VMTBLHN2.js.map +0 -1
  60. package/dist/chunk-VOXZWQ3N.js.map +0 -1
  61. package/dist/chunk-X6V2GGDZ.js.map +0 -1
  62. package/dist/chunk-XMYMIURR.js.map +0 -1
  63. package/dist/chunk-YVDSR4GM.js.map +0 -1
  64. package/dist/commands/clone.js.map +0 -1
  65. package/dist/commands/diff.js.map +0 -1
  66. package/dist/commands/help.js.map +0 -1
  67. package/dist/commands/hukam.js.map +0 -1
  68. package/dist/commands/init.js.map +0 -1
  69. package/dist/commands/mcp.js.map +0 -1
  70. package/dist/commands/migrate/baseline.js.map +0 -1
  71. package/dist/commands/migrate/create.js.map +0 -1
  72. package/dist/commands/migrate/list.js.map +0 -1
  73. package/dist/commands/migrate/run.js.map +0 -1
  74. package/dist/commands/report.js.map +0 -1
  75. package/dist/commands/restore.js.map +0 -1
  76. package/dist/commands/snapshot.js.map +0 -1
  77. package/dist/commands/sync.js.map +0 -1
  78. package/dist/help.js.map +0 -1
  79. package/dist/index.js.map +0 -1
@@ -1,28 +1,17 @@
1
1
  import {
2
- ABSENT_ON_TARGET,
3
- EXTENSION_UNAVAILABLE,
4
- UNDEFINED_COLUMN,
5
- sqlState
6
- } from "./chunk-H5MJ5DFX.js";
2
+ CHECK_NAMES,
3
+ RolesCheck,
4
+ applyTableFilter,
5
+ isComparisonCheck,
6
+ resolveTableFilter
7
+ } from "./chunk-UWAVXC57.js";
7
8
  import {
8
- destructiveReason,
9
+ policyOnlyKeys,
9
10
  runDbDiff,
11
+ sqlSkeleton,
10
12
  sqlToIssues
11
- } from "./chunk-VOXZWQ3N.js";
13
+ } from "./chunk-BUOWHE36.js";
12
14
  import {
13
- bareName,
14
- createdPolicies,
15
- createdTriggers,
16
- createsOnlyPolicies,
17
- createsOnlyTriggers,
18
- identifierMatcher,
19
- orderStatements,
20
- policyOnlyKeys,
21
- referencedTables,
22
- sqlSkeleton
23
- } from "./chunk-RRMI5CZD.js";
24
- import {
25
- isCommentOnly,
26
15
  splitSqlStatements
27
16
  } from "./chunk-G2DIPIYU.js";
28
17
  import {
@@ -33,26 +22,20 @@ import {
33
22
  dropEquivalentPolicyChanges,
34
23
  dropPolicySql,
35
24
  schemaPolicySql
36
- } from "./chunk-YVDSR4GM.js";
37
- import {
38
- globToRegExp,
39
- matchesGlob,
40
- parseFlagList
41
- } from "./chunk-DQQ5E563.js";
25
+ } from "./chunk-MIRLB5JM.js";
42
26
  import {
43
27
  Check,
44
28
  CheckSkipped,
45
29
  MigrationsCheck,
46
- errMsg,
47
30
  friendlyDbError,
48
31
  isCheckSkipped,
49
- pgClientConfig,
50
32
  pgQuery,
51
33
  quoteIdent,
52
34
  quoteLiteral,
53
35
  quoteName,
36
+ readOrAbsent,
54
37
  sqlLiteral
55
- } from "./chunk-X6V2GGDZ.js";
38
+ } from "./chunk-SQPCWGQO.js";
56
39
  import {
57
40
  DEFAULT_IGNORE_SCHEMAS,
58
41
  SCORE_MAX,
@@ -61,106 +44,9 @@ import {
61
44
  SCORE_PENALTY_INFO,
62
45
  SCORE_PENALTY_WARNING,
63
46
  STORAGE_LIST_LIMIT,
64
- SUPABASE_MGMT_API,
65
- SUPABASE_PLATFORM_SCHEMAS
47
+ SUPABASE_MGMT_API
66
48
  } from "./chunk-6WAMNZLO.js";
67
49
 
68
- // src/utils/table-filter.ts
69
- var parseTableList = parseFlagList;
70
- function resolveTableFilter(config, cli = {}) {
71
- const cliTables = parseTableList(cli.tables);
72
- const cliExclude = parseTableList(cli.excludeTables);
73
- const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : [];
74
- const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : [];
75
- const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables);
76
- const excludeTables = [.../* @__PURE__ */ new Set([...parseTableList(configExclude), ...cliExclude])];
77
- const filter = {};
78
- if (tables.length > 0) filter.tables = tables;
79
- if (excludeTables.length > 0) filter.excludeTables = excludeTables;
80
- return filter;
81
- }
82
- function isFiltered(filter) {
83
- return Boolean(filter?.tables?.length || filter?.excludeTables?.length);
84
- }
85
- function describeTableFilter(filter) {
86
- if (!isFiltered(filter)) return null;
87
- const parts = [];
88
- if (filter?.tables?.length) parts.push(`only ${filter.tables.join(", ")}`);
89
- if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(", ")}`);
90
- return `Scoped to ${parts.join(", ")} \u2014 applies to the schema and data checks; other layers are unfiltered.`;
91
- }
92
- function matchesPattern(name, pattern) {
93
- const candidates = [name.toLowerCase()];
94
- const dot = name.indexOf(".");
95
- if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase());
96
- const rx = globToRegExp(pattern.toLowerCase());
97
- return candidates.some((c) => rx.test(c));
98
- }
99
- function applyTableFilter(names, filter) {
100
- if (!isFiltered(filter)) return names;
101
- let out = names;
102
- if (filter?.tables?.length) {
103
- out = out.filter((n) => filter.tables.some((p) => matchesPattern(n, p)));
104
- }
105
- if (filter?.excludeTables?.length) {
106
- out = out.filter((n) => !filter.excludeTables.some((p) => matchesPattern(n, p)));
107
- }
108
- return out;
109
- }
110
-
111
- // src/types/drift.ts
112
- var CHECK_NAMES = [
113
- "schema",
114
- "rls",
115
- "rls-coverage",
116
- "edge-functions",
117
- "storage",
118
- "auth",
119
- "cron",
120
- "data",
121
- "webhooks",
122
- "realtime",
123
- "vault",
124
- "extensions",
125
- "migrations",
126
- "roles"
127
- ];
128
- var CHECK_META = {
129
- "schema": { number: 1, emoji: "\u{1F5C4}\uFE0F", label: "Schema" },
130
- "rls": { number: 2, emoji: "\u{1F512}", label: "RLS Policies" },
131
- "rls-coverage": { number: 3, emoji: "\u{1F6E1}\uFE0F", label: "RLS Coverage" },
132
- "edge-functions": { number: 4, emoji: "\u26A1", label: "Edge Functions" },
133
- "storage": { number: 5, emoji: "\u{1FAA3}", label: "Storage" },
134
- "auth": { number: 6, emoji: "\u{1F511}", label: "Auth Config" },
135
- "cron": { number: 7, emoji: "\u23F0", label: "Cron Jobs" },
136
- "data": { number: 8, emoji: "\u{1F5C3}\uFE0F", label: "Reference Data" },
137
- "webhooks": { number: 9, emoji: "\u26A1\u{1F517}", label: "Webhooks" },
138
- "realtime": { number: 10, emoji: "\u{1F4E1}", label: "Realtime Publications" },
139
- "vault": { number: 11, emoji: "\u{1F510}", label: "Vault Secrets" },
140
- "extensions": { number: 12, emoji: "\u{1F9E9}", label: "Postgres Extensions" },
141
- "migrations": { number: 13, emoji: "\u{1F4CB}", label: "Migration History" },
142
- "roles": { number: 14, emoji: "\u{1F464}", label: "Postgres Roles & Grants" }
143
- };
144
- var CHECK_KIND = {
145
- "schema": "comparison",
146
- "rls": "comparison",
147
- "rls-coverage": "posture",
148
- "edge-functions": "comparison",
149
- "storage": "comparison",
150
- "auth": "comparison",
151
- "cron": "comparison",
152
- "data": "comparison",
153
- "webhooks": "comparison",
154
- "realtime": "comparison",
155
- "vault": "comparison",
156
- "extensions": "comparison",
157
- "migrations": "posture",
158
- "roles": "comparison"
159
- };
160
- function isComparisonCheck(name) {
161
- return CHECK_KIND[name] === "comparison";
162
- }
163
-
164
50
  // src/scoring.ts
165
51
  function summarize(results) {
166
52
  let total = 0;
@@ -1224,9 +1110,11 @@ var COMPARED_BUCKET_COLUMNS = [
1224
1110
  "owner_id"
1225
1111
  ];
1226
1112
  var BUCKET_COLUMNS_SQL = `
1227
- SELECT column_name
1228
- FROM information_schema.columns
1229
- WHERE table_schema = 'storage' AND table_name = 'buckets'
1113
+ SELECT a.attname AS column_name
1114
+ FROM pg_attribute a
1115
+ JOIN pg_class c ON c.oid = a.attrelid
1116
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1117
+ WHERE n.nspname = 'storage' AND c.relname = 'buckets' AND a.attnum > 0 AND NOT a.attisdropped
1230
1118
  `;
1231
1119
  var TYPED_BUCKET_TABLES = [
1232
1120
  {
@@ -1249,8 +1137,8 @@ var TYPED_BUCKET_TABLES = [
1249
1137
  function tableExistsSql(table) {
1250
1138
  return `
1251
1139
  SELECT EXISTS (
1252
- SELECT 1 FROM information_schema.tables
1253
- WHERE table_schema = 'storage' AND table_name = '${table}'
1140
+ SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1141
+ WHERE n.nspname = 'storage' AND c.relname = '${table}'
1254
1142
  ) AS present
1255
1143
  `;
1256
1144
  }
@@ -1300,8 +1188,8 @@ function diffTypedBuckets(source, target, spec) {
1300
1188
  }
1301
1189
  var STORAGE_PRESENT_SQL = `
1302
1190
  SELECT EXISTS (
1303
- SELECT 1 FROM information_schema.tables
1304
- WHERE table_schema = 'storage' AND table_name = 'buckets'
1191
+ SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1192
+ WHERE n.nspname = 'storage' AND c.relname = 'buckets'
1305
1193
  ) AS present
1306
1194
  `;
1307
1195
  var STORAGE_POLICY_SQL = schemaPolicySql("storage");
@@ -1522,14 +1410,37 @@ function normalizeGoTrueSettings(raw) {
1522
1410
  }
1523
1411
  return out;
1524
1412
  }
1525
- var CRITICAL_KEYS = [
1526
- "EXTERNAL_EMAIL_ENABLED",
1527
- "EXTERNAL_PHONE_ENABLED",
1528
- "JWT_EXP",
1529
- "SECURITY_CAPTCHA_ENABLED",
1530
- "MFA_ENABLED",
1531
- "SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION"
1413
+ var CRITICAL_KEYS = /* @__PURE__ */ new Set([
1414
+ "external_email_enabled",
1415
+ "external_phone_enabled",
1416
+ "jwt_exp",
1417
+ "security_captcha_enabled",
1418
+ "security_update_password_require_reauthentication",
1419
+ "disable_signup"
1420
+ ]);
1421
+ var CRITICAL_PATTERN = /^mfa_[a-z_]+_(enroll|verify)_enabled$/;
1422
+ var SECRET_PATTERN = /(_secret|_secrets|_pass|_auth_token|_api_key|_access_key)$/;
1423
+ var ENVIRONMENT_PATTERNS = [
1424
+ /^(site_url|uri_allow_list|saml_external_url)$/,
1425
+ /^external_[a-z0-9_]+_(client_id|url)$/,
1426
+ /^nimbus_oauth_client_id$/,
1427
+ /^hook_[a-z_]+_uri$/,
1428
+ /^smtp_(host|port|user|admin_email|sender_name)$/,
1429
+ /^sms_[a-z]+_(account_sid|message_service_sid|content_sid|originator|sender|from)$/,
1430
+ /^sms_twilio_verify_(account_sid|message_service_sid)$/,
1431
+ /^sms_test_otp(_valid_until)?$/,
1432
+ /^webauthn_rp_(id|origins|display_name)$/
1532
1433
  ];
1434
+ function classifyAuthKey(key) {
1435
+ const k = key.toLowerCase();
1436
+ if (SECRET_PATTERN.test(k)) return "secret";
1437
+ if (ENVIRONMENT_PATTERNS.some((p) => p.test(k))) return "environment";
1438
+ return "shared";
1439
+ }
1440
+ function isCriticalAuthKey(key) {
1441
+ const k = key.toLowerCase();
1442
+ return CRITICAL_KEYS.has(k) || CRITICAL_PATTERN.test(k);
1443
+ }
1533
1444
  var AuthCheck = class extends Check {
1534
1445
  constructor(fetchFn = globalThis.fetch.bind(globalThis)) {
1535
1446
  super();
@@ -1584,27 +1495,38 @@ function diffAuthConfig(source, target, targetSrc) {
1584
1495
  for (const key of allKeys) {
1585
1496
  const sv = source[key];
1586
1497
  const tv = target[key];
1587
- if (JSON.stringify(sv) !== JSON.stringify(tv)) {
1588
- const isCritical = CRITICAL_KEYS.includes(key);
1589
- const action = targetSrc.kind === "hosted" ? {
1590
- method: "PATCH",
1591
- url: `${SUPABASE_MGMT_API}/${encodeURIComponent(targetSrc.ref)}/config/auth`,
1592
- headers: { Authorization: `Bearer ${targetSrc.token}` },
1593
- body: { [key]: sv },
1594
- label: `Set auth config "${key}" to ${JSON.stringify(sv)} in target`
1595
- } : void 0;
1596
- const remediation = action ? "" : " Self-hosted GoTrue is configured through its environment \u2014 update the target deployment and restart it.";
1498
+ if (JSON.stringify(sv) === JSON.stringify(tv)) continue;
1499
+ const kind = classifyAuthKey(key);
1500
+ const base2 = {
1501
+ id: `auth-${key.toLowerCase()}`,
1502
+ check: "auth",
1503
+ severity: isCriticalAuthKey(key) ? "critical" : "info",
1504
+ title: `Auth config mismatch: ${key}`
1505
+ };
1506
+ if (kind === "secret") {
1597
1507
  issues.push({
1598
- id: `auth-${key.toLowerCase()}`,
1599
- check: "auth",
1600
- severity: isCritical ? "critical" : "info",
1601
- title: `Auth config mismatch: ${key}`,
1602
- description: `"${key}" differs between source (${JSON.stringify(sv)}) and target (${JSON.stringify(tv)}).${remediation}`,
1603
- sourceValue: sv,
1604
- targetValue: tv,
1605
- ...action ? { action } : {}
1508
+ ...base2,
1509
+ description: `"${key}" differs between source and target. It is a secret: set it on the target directly.`,
1510
+ manualOnly: `"${key}" is a secret and is never copied. Set it on the target directly.`
1606
1511
  });
1512
+ continue;
1607
1513
  }
1514
+ const action = targetSrc.kind === "hosted" && kind === "shared" ? {
1515
+ method: "PATCH",
1516
+ url: `${SUPABASE_MGMT_API}/${encodeURIComponent(targetSrc.ref)}/config/auth`,
1517
+ headers: { Authorization: `Bearer ${targetSrc.token}` },
1518
+ body: { [key]: sv },
1519
+ label: `Set auth config "${key}" to ${JSON.stringify(sv)} in target`
1520
+ } : void 0;
1521
+ const manualOnly = kind === "environment" ? `"${key}" belongs to each environment and is not copied. Change it on the target if it is wrong there.` : action ? void 0 : "Self-hosted GoTrue is configured through its environment \u2014 update the target deployment and restart it.";
1522
+ issues.push({
1523
+ ...base2,
1524
+ description: `"${key}" differs between source (${JSON.stringify(sv)}) and target (${JSON.stringify(tv)}).` + (manualOnly ? ` ${manualOnly}` : ""),
1525
+ sourceValue: sv,
1526
+ targetValue: tv,
1527
+ ...action ? { action } : {},
1528
+ ...manualOnly ? { manualOnly } : {}
1529
+ });
1608
1530
  }
1609
1531
  return issues;
1610
1532
  }
@@ -1627,12 +1549,10 @@ var CronCheck = class extends Check {
1627
1549
  return diffCronJobs(source.jobs, target.jobs);
1628
1550
  }
1629
1551
  async fetchCronJobs(dbUrl) {
1630
- try {
1631
- const jobs = await this.queryFn(dbUrl, CRON_SQL);
1632
- return { jobs, available: true };
1633
- } catch {
1634
- return { jobs: [], available: false };
1635
- }
1552
+ return readOrAbsent(
1553
+ async () => ({ jobs: await this.queryFn(dbUrl, CRON_SQL), available: true }),
1554
+ { jobs: [], available: false }
1555
+ );
1636
1556
  }
1637
1557
  };
1638
1558
  var CRON_SQL = `
@@ -1836,19 +1756,10 @@ var WebhooksCheck = class extends Check {
1836
1756
  return issues;
1837
1757
  }
1838
1758
  async fetchHooks(dbUrl) {
1839
- try {
1840
- return await this.queryFn(dbUrl, HOOKS_SQL);
1841
- } catch {
1842
- return [];
1843
- }
1759
+ return readOrAbsent(async () => await this.queryFn(dbUrl, HOOKS_SQL), []);
1844
1760
  }
1845
1761
  async checkPgNet(dbUrl) {
1846
- try {
1847
- const rows = await this.queryFn(dbUrl, PG_NET_CHECK_SQL);
1848
- return rows.length > 0;
1849
- } catch {
1850
- return false;
1851
- }
1762
+ return readOrAbsent(async () => (await this.queryFn(dbUrl, PG_NET_CHECK_SQL)).length > 0, false);
1852
1763
  }
1853
1764
  };
1854
1765
  var HOOKS_SQL = `
@@ -1903,6 +1814,9 @@ function diffHooks(source, target) {
1903
1814
  title: `Extra webhook: ${h.name} on ${h.table_name}`,
1904
1815
  description: `Webhook "${h.name}" on ${h.table_name} exists in target but not in source.`,
1905
1816
  targetValue: h,
1817
+ // Removing one stops the target calling out, which nobody may notice
1818
+ // until something downstream goes quiet.
1819
+ destructive: "removes a webhook",
1906
1820
  sql: {
1907
1821
  up: dropStatement(h),
1908
1822
  // Recoverable, unlike before: the target's own definition is the way back.
@@ -1950,16 +1864,15 @@ var VaultCheck = class extends Check {
1950
1864
  return diffVaultSecrets(source, target);
1951
1865
  }
1952
1866
  async fetchSecrets(dbUrl) {
1953
- try {
1954
- return await this.queryFn(dbUrl, VAULT_SQL);
1955
- } catch {
1867
+ return readOrAbsent(async () => {
1956
1868
  try {
1869
+ return await this.queryFn(dbUrl, VAULT_SQL);
1870
+ } catch (err) {
1871
+ if (err.code !== "42703") throw err;
1957
1872
  const rows = await this.queryFn(dbUrl, VAULT_SQL_FALLBACK);
1958
1873
  return rows.map((r) => ({ ...r, unique_name: null }));
1959
- } catch {
1960
- return [];
1961
1874
  }
1962
- }
1875
+ }, []);
1963
1876
  }
1964
1877
  };
1965
1878
  var VAULT_SQL = `
@@ -2129,343 +2042,6 @@ function diffExtensions(source, target) {
2129
2042
  return issues;
2130
2043
  }
2131
2044
 
2132
- // src/checks/roles.ts
2133
- var PLATFORM_ROLES = [
2134
- "postgres",
2135
- "supabase_admin",
2136
- "authenticator",
2137
- "supabase_auth_admin",
2138
- "supabase_storage_admin",
2139
- "dashboard_user",
2140
- "pgbouncer",
2141
- "supavisor",
2142
- // Created by Supabase's own images for Edge Functions, Realtime, read
2143
- // replicas and logical replication. Diffing a project against plain
2144
- // PostgreSQL offered to create all four on the target.
2145
- "supabase_functions_admin",
2146
- "supabase_realtime_admin",
2147
- "supabase_read_only_user",
2148
- "supabase_replication_admin"
2149
- ];
2150
- var API_ROLES = ["anon", "authenticated", "service_role"];
2151
- var quoted = (names) => names.map((n) => `'${n.replace(/'/g, "''")}'`).join(", ");
2152
- var ROLES_SQL = `
2153
- SELECT
2154
- rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,
2155
- rolcanlogin, rolreplication, rolbypassrls, rolconnlimit,
2156
- rolvaliduntil::text AS rolvaliduntil
2157
- FROM pg_roles
2158
- WHERE NOT (rolname LIKE 'pg_%')
2159
- AND rolname NOT IN (${quoted([...PLATFORM_ROLES, ...API_ROLES])})
2160
- AND rolname <> current_user
2161
- ORDER BY rolname
2162
- `;
2163
- function grantSchemaFilter(ignoreSchemas) {
2164
- const excluded = [.../* @__PURE__ */ new Set([...SUPABASE_PLATFORM_SCHEMAS, ...ignoreSchemas])];
2165
- return `NOT IN (${quoted(excluded)})`;
2166
- }
2167
- var grantsSql = (ignoreSchemas) => `
2168
- SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
2169
- n.nspname AS table_schema, c.relname AS table_name,
2170
- a.privilege_type, a.is_grantable
2171
- FROM pg_class c
2172
- JOIN pg_namespace n ON n.oid = c.relnamespace
2173
- CROSS JOIN LATERAL aclexplode(c.relacl) a
2174
- WHERE c.relacl IS NOT NULL
2175
- AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
2176
- AND a.grantee <> c.relowner
2177
- AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
2178
- AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
2179
- AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
2180
- ORDER BY 1, 2, 3, 4
2181
- `;
2182
- var columnGrantsSql = (ignoreSchemas) => `
2183
- SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
2184
- n.nspname AS table_schema, c.relname AS table_name, att.attname AS column_name,
2185
- a.privilege_type, a.is_grantable
2186
- FROM pg_attribute att
2187
- JOIN pg_class c ON c.oid = att.attrelid
2188
- JOIN pg_namespace n ON n.oid = c.relnamespace
2189
- CROSS JOIN LATERAL aclexplode(att.attacl) a
2190
- WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
2191
- AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
2192
- AND a.grantee <> c.relowner
2193
- AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
2194
- AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
2195
- AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
2196
- ORDER BY 1, 2, 3, 4, 5
2197
- `;
2198
- var relationsSql = (ignoreSchemas) => `
2199
- SELECT n.nspname AS table_schema, c.relname AS table_name
2200
- FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
2201
- WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f')
2202
- AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
2203
- `;
2204
- var DEFAULT_TABLE_GRANTS_SQL = `
2205
- SELECT n.nspname AS table_schema,
2206
- CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
2207
- a.privilege_type, a.is_grantable
2208
- FROM pg_default_acl d
2209
- LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace
2210
- CROSS JOIN LATERAL aclexplode(d.defaclacl) a
2211
- WHERE d.defaclobjtype = 'r' AND d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
2212
- AND a.grantee <> d.defaclrole
2213
- `;
2214
- function grantedByDefault(relations, defaults) {
2215
- const present = new Set(relations.map((r) => `${r.table_schema}.${r.table_name}`));
2216
- const granted = new Set(defaults.map((d) => `${d.table_schema ?? "*"}|${d.grantee}|${d.privilege_type}|${Boolean(d.is_grantable)}`));
2217
- return (g) => !g.column_name && !present.has(`${g.table_schema}.${g.table_name}`) && [g.table_schema, "*"].some((schema) => granted.has(`${schema}|${g.grantee}|${g.privilege_type}|${Boolean(g.is_grantable)}`));
2218
- }
2219
- function defaultGrantsToRevoke(sourceRelations, targetRelations, defaults, sourceGrants) {
2220
- const present = new Set(targetRelations.map((r) => `${r.table_schema}.${r.table_name}`));
2221
- const held = new Set(sourceGrants.filter((g) => !g.column_name).map((g) => `${g.table_schema}.${g.table_name}|${g.grantee}|${g.privilege_type}`));
2222
- const issues = [];
2223
- for (const rel of sourceRelations) {
2224
- const name = `${rel.table_schema}.${rel.table_name}`;
2225
- if (present.has(name)) continue;
2226
- const extra = /* @__PURE__ */ new Map();
2227
- for (const d of defaults) {
2228
- if (d.table_schema !== null && d.table_schema !== rel.table_schema) continue;
2229
- if (held.has(`${name}|${d.grantee}|${d.privilege_type}`)) continue;
2230
- extra.set(d.grantee, (extra.get(d.grantee) ?? /* @__PURE__ */ new Set()).add(d.privilege_type));
2231
- }
2232
- for (const [grantee, privileges] of [...extra].sort(([a], [b]) => a.localeCompare(b))) {
2233
- const gs = [...privileges].sort().map((privilege_type) => ({ grantee, table_schema: rel.table_schema, table_name: rel.table_name, privilege_type, is_grantable: false }));
2234
- issues.push({
2235
- id: `roles-grant-default-${grantee}.${name}`,
2236
- check: "roles",
2237
- severity: extraGrantSeverity(grantee),
2238
- title: `Default grants to take back: ${describeGroup(gs)}`,
2239
- description: `Creating ${name} on the target gives ${grantee} what its default privileges grant. The source does not grant "${describeGroup(gs)}", so it is revoked once the table exists.`,
2240
- targetValue: gs,
2241
- sql: {
2242
- up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(grantee)};`,
2243
- down: `GRANT ${groupTarget(gs)} TO ${granteeSql(grantee)};`
2244
- }
2245
- });
2246
- }
2247
- }
2248
- return issues;
2249
- }
2250
- var OPEN_GRANTEES = /* @__PURE__ */ new Set(["anon", "authenticated", "PUBLIC"]);
2251
- function extraGrantSeverity(grantee) {
2252
- return OPEN_GRANTEES.has(grantee) ? "critical" : "warning";
2253
- }
2254
- var RolesCheck = class extends Check {
2255
- constructor(queryFn = pgQuery) {
2256
- super();
2257
- this.queryFn = queryFn;
2258
- }
2259
- name = "roles";
2260
- async scan(ctx) {
2261
- const ignore = ctx.config.ignoreSchemas ?? [];
2262
- const version = async (url) => Number((await this.queryFn(url, `SELECT current_setting('server_version_num') AS v`))[0]?.v ?? 0);
2263
- const [
2264
- sourceRoles,
2265
- targetRoles,
2266
- sourceGrants,
2267
- targetGrants,
2268
- sourceColumns,
2269
- targetColumns,
2270
- sourceVersion,
2271
- targetVersion,
2272
- sourceRelations,
2273
- targetRelations,
2274
- targetDefaults
2275
- ] = await Promise.all([
2276
- this.queryFn(ctx.source.dbUrl, ROLES_SQL),
2277
- this.queryFn(ctx.target.dbUrl, ROLES_SQL),
2278
- this.queryFn(ctx.source.dbUrl, grantsSql(ignore)),
2279
- this.queryFn(ctx.target.dbUrl, grantsSql(ignore)),
2280
- this.queryFn(ctx.source.dbUrl, columnGrantsSql(ignore)),
2281
- this.queryFn(ctx.target.dbUrl, columnGrantsSql(ignore)),
2282
- version(ctx.source.dbUrl),
2283
- version(ctx.target.dbUrl),
2284
- this.queryFn(ctx.source.dbUrl, relationsSql(ignore)),
2285
- this.queryFn(ctx.target.dbUrl, relationsSql(ignore)),
2286
- this.queryFn(ctx.target.dbUrl, DEFAULT_TABLE_GRANTS_SQL)
2287
- ]);
2288
- const comparable = comparablePrivileges(sourceVersion, targetVersion);
2289
- const byDefault = grantedByDefault(targetRelations ?? [], targetDefaults ?? []);
2290
- return [
2291
- ...diffRoles(sourceRoles, targetRoles),
2292
- ...diffGrants(
2293
- [...sourceGrants ?? [], ...sourceColumns ?? []].filter((g) => comparable(g) && !byDefault(g)),
2294
- [...targetGrants ?? [], ...targetColumns ?? []].filter(comparable)
2295
- ),
2296
- ...defaultGrantsToRevoke(
2297
- sourceRelations ?? [],
2298
- targetRelations ?? [],
2299
- (targetDefaults ?? []).filter((d) => comparable(d)),
2300
- sourceGrants ?? []
2301
- )
2302
- ];
2303
- }
2304
- };
2305
- function roleAttrs(r) {
2306
- const attrs = [];
2307
- if (r.rolsuper) attrs.push("SUPERUSER");
2308
- if (r.rolinherit) attrs.push("INHERIT");
2309
- if (r.rolcreaterole) attrs.push("CREATEROLE");
2310
- if (r.rolcreatedb) attrs.push("CREATEDB");
2311
- if (r.rolcanlogin) attrs.push("LOGIN");
2312
- if (r.rolreplication) attrs.push("REPLICATION");
2313
- if (r.rolbypassrls) attrs.push("BYPASSRLS");
2314
- if (r.rolconnlimit >= 0) attrs.push(`CONNECTION LIMIT ${r.rolconnlimit}`);
2315
- if (r.rolvaliduntil) attrs.push(`VALID UNTIL '${r.rolvaliduntil}'`);
2316
- return attrs.length > 0 ? attrs.join(" ") : "NOLOGIN";
2317
- }
2318
- function rolesEqual(a, b) {
2319
- return a.rolsuper === b.rolsuper && a.rolinherit === b.rolinherit && a.rolcreaterole === b.rolcreaterole && a.rolcreatedb === b.rolcreatedb && a.rolcanlogin === b.rolcanlogin && a.rolreplication === b.rolreplication && a.rolbypassrls === b.rolbypassrls && a.rolconnlimit === b.rolconnlimit && a.rolvaliduntil === b.rolvaliduntil;
2320
- }
2321
- function diffRoles(source, target) {
2322
- const issues = [];
2323
- const sourceMap = new Map(source.map((r) => [r.rolname, r]));
2324
- const targetMap = new Map(target.map((r) => [r.rolname, r]));
2325
- for (const [name, sr] of sourceMap) {
2326
- if (!targetMap.has(name)) {
2327
- issues.push({
2328
- id: `roles-missing-${name}`,
2329
- check: "roles",
2330
- severity: "critical",
2331
- title: `Missing role: ${name}`,
2332
- description: `Role "${name}" exists in source but is missing from target. Any RLS policies or grants referencing this role will be silently ineffective.`,
2333
- sourceValue: sr,
2334
- sql: {
2335
- up: `CREATE ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
2336
- down: `DROP ROLE IF EXISTS ${quoteName(name)};`
2337
- }
2338
- });
2339
- }
2340
- }
2341
- for (const [name, tr] of targetMap) {
2342
- if (!sourceMap.has(name)) {
2343
- issues.push({
2344
- id: `roles-extra-${name}`,
2345
- check: "roles",
2346
- severity: "warning",
2347
- title: `Extra role: ${name}`,
2348
- description: `Role "${name}" exists in target but not in source.`,
2349
- targetValue: tr,
2350
- sql: {
2351
- up: `DROP ROLE IF EXISTS ${quoteName(name)};`,
2352
- down: `CREATE ROLE ${quoteName(name)} ${roleAttrs(tr)};`
2353
- }
2354
- });
2355
- }
2356
- }
2357
- for (const [name, sr] of sourceMap) {
2358
- const tr = targetMap.get(name);
2359
- if (tr && !rolesEqual(sr, tr)) {
2360
- issues.push({
2361
- id: `roles-modified-${name}`,
2362
- check: "roles",
2363
- severity: "warning",
2364
- title: `Modified role: ${name}`,
2365
- description: `Role "${name}" has different attributes between source and target.`,
2366
- sourceValue: sr,
2367
- targetValue: tr,
2368
- sql: {
2369
- up: `ALTER ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
2370
- down: `ALTER ROLE ${quoteName(name)} ${roleAttrs(tr)};`
2371
- }
2372
- });
2373
- }
2374
- }
2375
- return issues;
2376
- }
2377
- function grantKey(g) {
2378
- const column = g.column_name ? `.${g.column_name}` : "";
2379
- return `${g.grantee}.${g.table_schema}.${g.table_name}${column}.${g.privilege_type}`;
2380
- }
2381
- function granteeSql(grantee) {
2382
- return grantee === "PUBLIC" ? "PUBLIC" : `"${grantee.replace(/"/g, '""')}"`;
2383
- }
2384
- function grantTarget(g) {
2385
- const column = g.column_name ? ` ("${g.column_name.replace(/"/g, '""')}")` : "";
2386
- return `${g.privilege_type}${column} ON ${quoteName(g.table_schema)}.${quoteName(g.table_name)}`;
2387
- }
2388
- function describeGrant(g) {
2389
- const column = g.column_name ? `(${g.column_name}) ` : "";
2390
- return `${g.privilege_type} ${column}ON ${g.table_schema}.${g.table_name} TO ${g.grantee}`;
2391
- }
2392
- var grantSql = (g, withOption = g.is_grantable) => `GRANT ${grantTarget(g)} TO ${granteeSql(g.grantee)}${withOption ? " WITH GRANT OPTION" : ""};`;
2393
- function comparablePrivileges(sourceVersion, targetVersion) {
2394
- const both = Math.min(sourceVersion || Infinity, targetVersion || Infinity);
2395
- return (g) => g.privilege_type !== "MAINTAIN" || both >= 17e4;
2396
- }
2397
- function grouped(grants) {
2398
- const groups = /* @__PURE__ */ new Map();
2399
- for (const g of grants) {
2400
- const key = `${g.grantee}.${g.table_schema}.${g.table_name}${g.column_name ? `.${g.column_name}` : ""}.${Boolean(g.is_grantable)}`;
2401
- groups.set(key, [...groups.get(key) ?? [], g]);
2402
- }
2403
- return [...groups.values()];
2404
- }
2405
- function groupTarget(gs) {
2406
- const column = gs[0].column_name ? ` ("${gs[0].column_name.replace(/"/g, '""')}")` : "";
2407
- return `${gs.map((g) => `${g.privilege_type}${column}`).join(", ")} ON ${quoteName(gs[0].table_schema)}.${quoteName(gs[0].table_name)}`;
2408
- }
2409
- function describeGroup(gs) {
2410
- const column = gs[0].column_name ? `(${gs[0].column_name}) ` : "";
2411
- return `${gs.map((g) => g.privilege_type).join(", ")} ${column}ON ${gs[0].table_schema}.${gs[0].table_name} TO ${gs[0].grantee}`;
2412
- }
2413
- var groupKey = (gs) => grantKey(gs[0]).replace(/\.[^.]+$/, "");
2414
- function diffGrants(source, target) {
2415
- const issues = [];
2416
- const sourceMap = new Map(source.map((g) => [grantKey(g), g]));
2417
- const targetMap = new Map(target.map((g) => [grantKey(g), g]));
2418
- const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g);
2419
- for (const gs of grouped(missing)) {
2420
- const plural = gs.length > 1 ? "s" : "";
2421
- issues.push({
2422
- id: `roles-grant-missing-${groupKey(gs)}`,
2423
- check: "roles",
2424
- severity: "warning",
2425
- title: `Missing grant${plural}: ${describeGroup(gs)}`,
2426
- description: `Grant${plural} "${describeGroup(gs)}" ${gs.length > 1 ? "are" : "is"} missing from target.`,
2427
- sourceValue: gs.length > 1 ? gs : gs[0],
2428
- sql: {
2429
- up: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`,
2430
- down: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`
2431
- }
2432
- });
2433
- }
2434
- for (const [key, sg] of sourceMap) {
2435
- const tg = targetMap.get(key);
2436
- if (tg && Boolean(sg.is_grantable) !== Boolean(tg.is_grantable)) {
2437
- const revokeOption = `REVOKE GRANT OPTION FOR ${grantTarget(sg)} FROM ${granteeSql(sg.grantee)};`;
2438
- issues.push({
2439
- id: `roles-grant-option-${key}`,
2440
- check: "roles",
2441
- severity: "warning",
2442
- title: `Grant option differs: ${describeGrant(sg)}`,
2443
- description: `"${describeGrant(sg)}" is held ${sg.is_grantable ? "with" : "without"} the grant option in source and ${tg.is_grantable ? "with" : "without"} it in target.`,
2444
- sourceValue: sg,
2445
- targetValue: tg,
2446
- sql: sg.is_grantable ? { up: grantSql(sg, true), down: revokeOption } : { up: revokeOption, down: grantSql(tg, true) }
2447
- });
2448
- }
2449
- }
2450
- const extra = [...targetMap].filter(([key]) => !sourceMap.has(key)).map(([, g]) => g);
2451
- for (const gs of grouped(extra)) {
2452
- const plural = gs.length > 1 ? "s" : "";
2453
- issues.push({
2454
- id: `roles-grant-extra-${groupKey(gs)}`,
2455
- check: "roles",
2456
- severity: extraGrantSeverity(gs[0].grantee),
2457
- title: `Extra grant${plural}: ${describeGroup(gs)}`,
2458
- description: `Grant${plural} "${describeGroup(gs)}" exist${gs.length > 1 ? "" : "s"} in target but not in source.`,
2459
- targetValue: gs.length > 1 ? gs : gs[0],
2460
- sql: {
2461
- up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,
2462
- down: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`
2463
- }
2464
- });
2465
- }
2466
- return issues;
2467
- }
2468
-
2469
2045
  // src/checks/index.ts
2470
2046
  function createDefaultRegistry(options = {}) {
2471
2047
  const registry = new CheckRegistry();
@@ -2486,322 +2062,12 @@ function createDefaultRegistry(options = {}) {
2486
2062
  return registry;
2487
2063
  }
2488
2064
 
2489
- // src/promote.ts
2490
- import pg from "pg";
2491
- function outOfScopeReason(sql, filter) {
2492
- if (!isFiltered(filter)) return null;
2493
- const referenced = referencedTables(sql);
2494
- if (referenced.length === 0) return null;
2495
- const excluded = referenced.filter((t) => applyTableFilter([t], filter).length === 0);
2496
- if (excluded.length === 0) return null;
2497
- const names = excluded.map((t) => `'${t}'`).join(", ");
2498
- const flag = filter?.tables?.length ? "--tables" : "--exclude-tables";
2499
- const noun = excluded.length === 1 ? "table" : "tables";
2500
- return `Depends on ${noun} ${names}, excluded by ${flag}`;
2501
- }
2502
- function isSelected(issueId, only) {
2503
- if (!only?.length) return true;
2504
- return only.some((pattern) => matchesGlob(issueId, pattern));
2505
- }
2506
- function classifyIssue(issue, options, recreatedPolicies = /* @__PURE__ */ new Set()) {
2507
- if (!isSelected(issue.id, options.only)) {
2508
- return { kind: "skip", reason: "Not selected by --only" };
2509
- }
2510
- if (issue.manualOnly) return { kind: "skip", reason: issue.manualOnly };
2511
- if (!issue.sql?.up) {
2512
- if (issue.action) return { kind: "api", action: issue.action };
2513
- return { kind: "skip", reason: issue.manualOnly ?? "No SQL fix or API action available" };
2514
- }
2515
- if (!options.allowDestructive) {
2516
- const why = destructiveReason(issue.sql.up, recreatedPolicies);
2517
- if (why) {
2518
- return { kind: "skip", reason: `Destructive \u2014 ${why}; re-run with --allow-destructive to apply` };
2519
- }
2520
- }
2521
- const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter);
2522
- if (outOfScope) return { kind: "skip", reason: outOfScope };
2523
- return { kind: "sql", sql: issue.sql.up };
2524
- }
2525
- function policiesCreatedBySelectedFixes(checks, options) {
2526
- const created = /* @__PURE__ */ new Set();
2527
- for (const check of checks) {
2528
- const askedForExplicitly = options.checks?.includes(check.check) ?? false;
2529
- if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue;
2530
- for (const issue of check.issues) {
2531
- const sql = issue.sql?.up;
2532
- if (!sql || !isSelected(issue.id, options.only)) continue;
2533
- if (!options.allowDestructive && destructiveReason(sql)) continue;
2534
- if (outOfScopeReason(sql, options.tableFilter)) continue;
2535
- for (const key of createdPolicies(sql)) created.add(key);
2536
- }
2537
- }
2538
- return created;
2539
- }
2540
- function planWork(scanResult, options = {}) {
2541
- const plan = { sqlStatements: [], apiActions: [], skipped: [] };
2542
- const relevant = scanResult.checks.filter(
2543
- (c) => c.status === "drifted" && (!options.checks || options.checks.includes(c.check))
2544
- );
2545
- const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options);
2546
- const keptBack = [];
2547
- for (const checkResult of relevant) {
2548
- const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false;
2549
- if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {
2550
- for (const issue of checkResult.issues) {
2551
- plan.skipped.push({
2552
- check: checkResult.check,
2553
- issueId: issue.id,
2554
- reason: "Posture finding about the target, not drift from the source \u2014 applying it would create drift. Use --apply-posture to apply anyway."
2555
- });
2556
- }
2557
- continue;
2558
- }
2559
- for (const issue of checkResult.issues) {
2560
- const at = { check: checkResult.check, issueId: issue.id };
2561
- const outcome = classifyIssue(issue, options, recreatedPolicies);
2562
- if (outcome.kind === "sql") plan.sqlStatements.push({ ...at, sql: outcome.sql });
2563
- else if (outcome.kind === "api") plan.apiActions.push({ ...at, action: outcome.action });
2564
- else {
2565
- plan.skipped.push({ ...at, reason: outcome.reason });
2566
- if (outcome.reason.startsWith("Destructive") && issue.sql?.down) {
2567
- keptBack.push({ issueId: issue.id, definition: issue.sql.down });
2568
- }
2569
- }
2570
- }
2571
- }
2572
- plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant));
2573
- const dbdiffOrder = new Map(plan.sqlStatements.filter((s) => s.check === "schema").map((s, i) => [s, i]));
2574
- plan.sqlStatements = orderStatements(plan.sqlStatements, (s) => s.sql, (s) => dbdiffOrder.get(s));
2575
- plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped);
2576
- return plan;
2577
- }
2578
- var DROPS_SUPPORTING_OBJECT = /^\s*DROP\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\s+(?:IF\s+EXISTS\s+)?((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i;
2579
- function holdBackDropsStillInUse(statements, keptBack, skipped, downs = /* @__PURE__ */ new Map()) {
2580
- const kept = keptBack.map((k) => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }));
2581
- let remaining = statements;
2582
- for (let changed = kept.length > 0; changed; ) {
2583
- changed = false;
2584
- remaining = remaining.filter((statement) => {
2585
- const names = droppedSupportingObjects(statement.sql);
2586
- if (names.length === 0) return true;
2587
- const user = kept.find((k) => names.some((n) => identifierMatcher(bareName(n)).test(k.skeleton)));
2588
- if (!user) return true;
2589
- skipped.push({
2590
- check: statement.check,
2591
- issueId: statement.issueId,
2592
- reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; re-run with --allow-destructive to apply both`
2593
- });
2594
- const definition = downs.get(statement.issueId);
2595
- if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) });
2596
- changed = true;
2597
- return false;
2598
- });
2599
- }
2600
- return remaining;
2601
- }
2602
- function droppedSupportingObjects(sql) {
2603
- const parts = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
2604
- const names = parts.map((s) => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1]);
2605
- return names.length > 0 && names.every((n) => n !== void 0) ? names : [];
2606
- }
2607
- function downsOf(checks) {
2608
- const downs = /* @__PURE__ */ new Map();
2609
- for (const check of checks) {
2610
- for (const issue of check.issues) {
2611
- if (issue.sql?.down) downs.set(issue.id, issue.sql.down);
2612
- }
2613
- }
2614
- return downs;
2615
- }
2616
- function dropDuplicateObjectFixes(statements, skipped) {
2617
- const kinds = [
2618
- { what: "policy", created: createdPolicies, onlyThis: createsOnlyPolicies, seen: /* @__PURE__ */ new Set() },
2619
- { what: "trigger", created: createdTriggers, onlyThis: createsOnlyTriggers, seen: /* @__PURE__ */ new Set() }
2620
- ];
2621
- const kept = [];
2622
- for (const statement of statements) {
2623
- const duplicate = kinds.find((kind) => {
2624
- const names = kind.created(statement.sql);
2625
- return names.length > 0 && names.every((n) => kind.seen.has(n)) && kind.onlyThis(statement.sql);
2626
- });
2627
- if (duplicate) {
2628
- skipped.push({
2629
- check: statement.check,
2630
- issueId: statement.issueId,
2631
- reason: `Already created by the schema fix for the same ${duplicate.what}`
2632
- });
2633
- continue;
2634
- }
2635
- for (const kind of kinds) {
2636
- for (const name of kind.created(statement.sql)) kind.seen.add(name);
2637
- }
2638
- kept.push(statement);
2639
- }
2640
- return kept;
2641
- }
2642
- async function executeSql(dbUrl, statements, result, transactional) {
2643
- if (statements.length === 0) return;
2644
- const client = new pg.Client(pgClientConfig(dbUrl));
2645
- await client.connect();
2646
- try {
2647
- if (transactional) await runInTransaction(client, statements, result);
2648
- else await runIndependently(client, statements, result);
2649
- } finally {
2650
- await client.end();
2651
- }
2652
- }
2653
- async function runIndependently(client, statements, result) {
2654
- for (const stmt of statements) {
2655
- try {
2656
- await client.query(stmt.sql);
2657
- result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
2658
- } catch (err) {
2659
- result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
2660
- }
2661
- }
2662
- }
2663
- function isEnumValueAddition(sql) {
2664
- const statements = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
2665
- return statements.length > 0 && statements.every((s) => /^\s*ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE\b/i.test(sqlSkeleton(s)));
2666
- }
2667
- async function runInTransaction(client, statements, result) {
2668
- const additions = statements.filter((s) => isEnumValueAddition(s.sql));
2669
- const rest = statements.filter((s) => !isEnumValueAddition(s.sql));
2670
- if (additions.length > 0 && !await runBatch(client, additions, result)) return;
2671
- await runBatch(client, rest, result);
2672
- }
2673
- function unmetDependency(sql, err) {
2674
- const code = sqlState(err);
2675
- if (!code) return void 0;
2676
- if (/^\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
2677
- return EXTENSION_UNAVAILABLE.has(code) ? "this server does not ship it" : void 0;
2678
- }
2679
- if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {
2680
- return "it needs something the target does not have";
2681
- }
2682
- return void 0;
2683
- }
2684
- async function runBatch(client, statements, result) {
2685
- if (statements.length === 0) return true;
2686
- const done = [];
2687
- await client.query("BEGIN");
2688
- let pending = statements;
2689
- let unmet = [];
2690
- while (pending.length > 0) {
2691
- unmet = [];
2692
- for (const stmt of pending) {
2693
- await client.query("SAVEPOINT sf_fix");
2694
- try {
2695
- await client.query(stmt.sql);
2696
- await client.query("RELEASE SAVEPOINT sf_fix");
2697
- done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
2698
- } catch (err) {
2699
- const why = unmetDependency(stmt.sql, err);
2700
- if (why && await client.query("ROLLBACK TO SAVEPOINT sf_fix").then(() => true, () => false)) {
2701
- unmet.push({ stmt, err, why });
2702
- continue;
2703
- }
2704
- await client.query("ROLLBACK").catch(() => {
2705
- });
2706
- result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
2707
- result.rolledBack = [...result.rolledBack ?? [], ...done];
2708
- return false;
2709
- }
2710
- }
2711
- if (unmet.length === pending.length) break;
2712
- pending = unmet.map((u) => u.stmt);
2713
- }
2714
- await client.query("COMMIT");
2715
- result.applied.push(...done);
2716
- for (const { stmt, err, why } of unmet) {
2717
- result.errors.push({
2718
- check: stmt.check,
2719
- issueId: stmt.issueId,
2720
- error: `${errMsg(err)} \u2014 not applied: ${why}. The other fixes were.`
2721
- });
2722
- }
2723
- return true;
2724
- }
2725
- async function executeApiActions(actions, fetchFn, result) {
2726
- for (const act of actions) {
2727
- try {
2728
- const init = {
2729
- method: act.action.method,
2730
- headers: { "Content-Type": "application/json", ...act.action.headers }
2731
- };
2732
- if (act.action.body !== void 0) {
2733
- init.body = JSON.stringify(act.action.body);
2734
- }
2735
- const res = await fetchFn(act.action.url, init);
2736
- if (!res.ok) {
2737
- const text = await res.text().catch(() => res.statusText);
2738
- throw new Error(`${act.action.method} ${act.action.url} \u2192 ${res.status}: ${text}`);
2739
- }
2740
- result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
2741
- } catch (err) {
2742
- result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) });
2743
- }
2744
- }
2745
- }
2746
- async function promote(options) {
2747
- const {
2748
- dbUrl,
2749
- scanResult,
2750
- checks,
2751
- dryRun = false,
2752
- allowDestructive = false,
2753
- tableFilter,
2754
- only,
2755
- applyPosture = false,
2756
- transactional = true,
2757
- fetchFn = globalThis.fetch.bind(globalThis)
2758
- } = options;
2759
- const { sqlStatements, apiActions, skipped } = planWork(scanResult, {
2760
- checks,
2761
- allowDestructive,
2762
- tableFilter,
2763
- only,
2764
- applyPosture
2765
- });
2766
- const result = { applied: [], skipped, errors: [] };
2767
- if (dryRun) {
2768
- for (const stmt of sqlStatements) {
2769
- result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
2770
- }
2771
- for (const act of apiActions) {
2772
- result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
2773
- }
2774
- return result;
2775
- }
2776
- await executeSql(dbUrl, sqlStatements, result, transactional);
2777
- if (result.rolledBack) {
2778
- for (const act of apiActions) {
2779
- result.skipped.push({
2780
- check: act.check,
2781
- issueId: act.issueId,
2782
- reason: "Not attempted \u2014 the SQL fixes were rolled back"
2783
- });
2784
- }
2785
- return result;
2786
- }
2787
- await executeApiActions(apiActions, fetchFn, result);
2788
- return result;
2789
- }
2790
-
2791
2065
  export {
2792
- resolveTableFilter,
2793
- isFiltered,
2794
- describeTableFilter,
2795
- CHECK_NAMES,
2796
- CHECK_META,
2797
- isComparisonCheck,
2798
2066
  summarize,
2799
2067
  summarizeByKind,
2800
2068
  computeScore,
2801
2069
  scan,
2802
2070
  CheckRegistry,
2803
- createDefaultRegistry,
2804
- planWork,
2805
- promote
2071
+ createDefaultRegistry
2806
2072
  };
2807
- //# sourceMappingURL=chunk-5Z3SAIQS.js.map
2073
+ //# sourceMappingURL=chunk-3HGAV5CC.js.map