@akal/supaforge 0.0.0-stage → 0.0.32

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 (97) 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 +135 -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-2SELREHW.js +156 -0
  9. package/dist/chunk-2SELREHW.js.map +1 -0
  10. package/dist/chunk-3HGAV5CC.js +2073 -0
  11. package/dist/chunk-3HGAV5CC.js.map +1 -0
  12. package/dist/chunk-4IVN7QVY.js +632 -0
  13. package/dist/chunk-4IVN7QVY.js.map +1 -0
  14. package/dist/chunk-6LJERPUN.js +499 -0
  15. package/dist/chunk-6LJERPUN.js.map +1 -0
  16. package/dist/chunk-6Q7MHFBM.js +13 -0
  17. package/dist/chunk-6Q7MHFBM.js.map +1 -0
  18. package/dist/chunk-6WAMNZLO.js +336 -0
  19. package/dist/chunk-6WAMNZLO.js.map +1 -0
  20. package/dist/chunk-7NAZGZPV.js +868 -0
  21. package/dist/chunk-7NAZGZPV.js.map +1 -0
  22. package/dist/chunk-BLKJWDTL.js +153 -0
  23. package/dist/chunk-BLKJWDTL.js.map +1 -0
  24. package/dist/chunk-BUOWHE36.js +1311 -0
  25. package/dist/chunk-BUOWHE36.js.map +1 -0
  26. package/dist/chunk-DMIWAJRB.js +602 -0
  27. package/dist/chunk-DMIWAJRB.js.map +1 -0
  28. package/dist/chunk-DQQ5E563.js +64 -0
  29. package/dist/chunk-DQQ5E563.js.map +1 -0
  30. package/dist/chunk-G2DIPIYU.js +94 -0
  31. package/dist/chunk-G2DIPIYU.js.map +1 -0
  32. package/dist/chunk-GEHPTPNZ.js +240 -0
  33. package/dist/chunk-GEHPTPNZ.js.map +1 -0
  34. package/dist/chunk-GZREXCQZ.js +207 -0
  35. package/dist/chunk-GZREXCQZ.js.map +1 -0
  36. package/dist/chunk-MIRLB5JM.js +1292 -0
  37. package/dist/chunk-MIRLB5JM.js.map +1 -0
  38. package/dist/chunk-NTUASFQ3.js +248 -0
  39. package/dist/chunk-NTUASFQ3.js.map +1 -0
  40. package/dist/chunk-ORQJVE57.js +642 -0
  41. package/dist/chunk-ORQJVE57.js.map +1 -0
  42. package/dist/chunk-SC2XHGIS.js +122 -0
  43. package/dist/chunk-SC2XHGIS.js.map +1 -0
  44. package/dist/chunk-SQPCWGQO.js +657 -0
  45. package/dist/chunk-SQPCWGQO.js.map +1 -0
  46. package/dist/chunk-UWAVXC57.js +916 -0
  47. package/dist/chunk-UWAVXC57.js.map +1 -0
  48. package/dist/commands/clone.d.ts +66 -0
  49. package/dist/commands/clone.js +416 -0
  50. package/dist/commands/clone.js.map +1 -0
  51. package/dist/commands/diff.d.ts +81 -0
  52. package/dist/commands/diff.js +23 -0
  53. package/dist/commands/diff.js.map +1 -0
  54. package/dist/commands/help.d.ts +32 -0
  55. package/dist/commands/help.js +36 -0
  56. package/dist/commands/help.js.map +1 -0
  57. package/dist/commands/hukam.d.ts +13 -0
  58. package/dist/commands/hukam.js +28 -0
  59. package/dist/commands/hukam.js.map +1 -0
  60. package/dist/commands/init.d.ts +47 -0
  61. package/dist/commands/init.js +388 -0
  62. package/dist/commands/init.js.map +1 -0
  63. package/dist/commands/mcp.d.ts +13 -0
  64. package/dist/commands/mcp.js +43 -0
  65. package/dist/commands/mcp.js.map +1 -0
  66. package/dist/commands/migrate/baseline.d.ts +24 -0
  67. package/dist/commands/migrate/baseline.js +69 -0
  68. package/dist/commands/migrate/baseline.js.map +1 -0
  69. package/dist/commands/migrate/create.d.ts +36 -0
  70. package/dist/commands/migrate/create.js +127 -0
  71. package/dist/commands/migrate/create.js.map +1 -0
  72. package/dist/commands/migrate/list.d.ts +23 -0
  73. package/dist/commands/migrate/list.js +110 -0
  74. package/dist/commands/migrate/list.js.map +1 -0
  75. package/dist/commands/migrate/run.d.ts +61 -0
  76. package/dist/commands/migrate/run.js +18 -0
  77. package/dist/commands/migrate/run.js.map +1 -0
  78. package/dist/commands/report.d.ts +27 -0
  79. package/dist/commands/report.js +210 -0
  80. package/dist/commands/report.js.map +1 -0
  81. package/dist/commands/restore.d.ts +26 -0
  82. package/dist/commands/restore.js +266 -0
  83. package/dist/commands/restore.js.map +1 -0
  84. package/dist/commands/snapshot.d.ts +33 -0
  85. package/dist/commands/snapshot.js +249 -0
  86. package/dist/commands/snapshot.js.map +1 -0
  87. package/dist/commands/sync.d.ts +16 -0
  88. package/dist/commands/sync.js +38 -0
  89. package/dist/commands/sync.js.map +1 -0
  90. package/dist/config-CTbeRlJk.d.ts +134 -0
  91. package/dist/help.d.ts +28 -0
  92. package/dist/help.js +64 -0
  93. package/dist/help.js.map +1 -0
  94. package/dist/index.d.ts +498 -0
  95. package/dist/index.js +147 -0
  96. package/dist/index.js.map +1 -0
  97. package/package.json +74 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/table-filter.ts","../src/types/drift.ts","../src/promote.ts","../src/pg-errors.ts","../src/checks/roles.ts"],"sourcesContent":["import type { SupaForgeConfig } from '../types/config.js'\nimport { parseFlagList, globToRegExp } from './strings.js'\n\n/**\n * Which tables a diff should look at.\n *\n * Empty/undefined means \"everything\", which is the default and what every\n * existing caller gets. Patterns are passed to @dbdiff/cli verbatim, so its\n * glob support (`*`, `?`) works here too.\n */\nexport interface TableFilter {\n /** Only compare these. Undefined means all. */\n tables?: string[]\n /** Never compare these. Applied after `tables`. */\n excludeTables?: string[]\n}\n\n/**\n * Split a repeatable table flag into individual patterns.\n *\n * `--tables=a,b --tables=c` and `--tables=a --tables=b --tables=c` mean the\n * same thing. The splitting itself is shared with every other repeatable list\n * flag; this name is what the table call sites read by.\n */\nexport const parseTableList = parseFlagList\n\n/**\n * Resolve the effective filter from config and CLI flags.\n *\n * `tables` is an *override*: `--tables=orders` means \"only orders\", so a\n * broader list in config must not widen it back out. `excludeTables` is a\n * *union*: an exclusion is a safety rail, and the two sources agreeing to\n * exclude more is never the surprising direction. This mirrors how `--skip`\n * already merges with `checks.exclude`.\n *\n * Tolerates a malformed config — a non-array yields no filter rather than\n * throwing, so a bad config compares everything instead of taking the scan\n * down.\n */\nexport function resolveTableFilter(\n config: SupaForgeConfig | undefined,\n cli: { tables?: string[]; excludeTables?: string[] } = {},\n): TableFilter {\n const cliTables = parseTableList(cli.tables)\n const cliExclude = parseTableList(cli.excludeTables)\n\n const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : []\n const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : []\n\n const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables)\n const excludeTables = [...new Set([...parseTableList(configExclude), ...cliExclude])]\n\n const filter: TableFilter = {}\n if (tables.length > 0) filter.tables = tables\n if (excludeTables.length > 0) filter.excludeTables = excludeTables\n return filter\n}\n\n/** True when the filter would narrow anything. */\nexport function isFiltered(filter: TableFilter | undefined): boolean {\n return Boolean(filter?.tables?.length || filter?.excludeTables?.length)\n}\n\n/**\n * One line describing what the run is scoped to, or null when it is not\n * scoped at all.\n *\n * Printed before the scan because a narrowed run must never look like a full\n * one — particularly with `--apply`, where the difference is which statements\n * get executed. It also names the layers the filter reaches: a table is a\n * concept the schema and data checks have and the others do not, so `diff\n * --tables=orders` still compares every RLS policy and storage bucket.\n */\nexport function describeTableFilter(filter: TableFilter | undefined): string | null {\n if (!isFiltered(filter)) return null\n const parts: string[] = []\n if (filter?.tables?.length) parts.push(`only ${filter.tables.join(', ')}`)\n if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(', ')}`)\n return `Scoped to ${parts.join(', ')} — applies to the schema and data checks; other layers are unfiltered.`\n}\n\n/**\n * Does `name` match a @dbdiff/cli-style glob pattern?\n *\n * Only `*` and `?` are special, matching dbdiff's own syntax. Used to narrow\n * the Reference Data table list locally, since that check picks its tables\n * from config before dbdiff is invoked and so cannot rely on `--tables` alone.\n *\n * Comparison is case-insensitive and tolerant of a schema qualifier: a pattern\n * of `orders` matches `public.orders`, because that is what a user means when\n * they name a table without a schema.\n */\nexport function matchesPattern(name: string, pattern: string): boolean {\n const candidates = [name.toLowerCase()]\n const dot = name.indexOf('.')\n if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase())\n\n const rx = globToRegExp(pattern.toLowerCase())\n return candidates.some(c => rx.test(c))\n}\n\n/**\n * Apply a filter to a concrete list of table names.\n *\n * Include first, then exclude — so `--tables='billing_*' --exclude-tables='*_audit'`\n * reads left to right the way it is written.\n */\nexport function applyTableFilter(names: string[], filter: TableFilter | undefined): string[] {\n if (!isFiltered(filter)) return names\n\n let out = names\n if (filter?.tables?.length) {\n out = out.filter(n => filter.tables!.some(p => matchesPattern(n, p)))\n }\n if (filter?.excludeTables?.length) {\n out = out.filter(n => !filter.excludeTables!.some(p => matchesPattern(n, p)))\n }\n return out\n}\n","export const CHECK_NAMES = [\n 'schema', 'rls', 'rls-coverage', 'edge-functions', 'storage', 'auth', 'cron', 'data',\n 'webhooks', 'realtime', 'vault', 'extensions', 'migrations', 'roles',\n] as const\n\nexport type CheckName = (typeof CHECK_NAMES)[number]\n\nexport type Severity = 'critical' | 'warning' | 'info'\n\nexport const CHECK_META: Record<CheckName, { number: number; emoji: string; label: string }> = {\n 'schema': { number: 1, emoji: '🗄️', label: 'Schema' },\n 'rls': { number: 2, emoji: '🔒', label: 'RLS Policies' },\n 'rls-coverage': { number: 3, emoji: '🛡️', label: 'RLS Coverage' },\n 'edge-functions': { number: 4, emoji: '⚡', label: 'Edge Functions' },\n 'storage': { number: 5, emoji: '🪣', label: 'Storage' },\n 'auth': { number: 6, emoji: '🔑', label: 'Auth Config' },\n 'cron': { number: 7, emoji: '⏰', label: 'Cron Jobs' },\n 'data': { number: 8, emoji: '🗃️', label: 'Reference Data' },\n 'webhooks': { number: 9, emoji: '⚡🔗', label: 'Webhooks' },\n 'realtime': { number: 10, emoji: '📡', label: 'Realtime Publications' },\n 'vault': { number: 11, emoji: '🔐', label: 'Vault Secrets' },\n 'extensions': { number: 12, emoji: '🧩', label: 'Postgres Extensions' },\n 'migrations': { number: 13, emoji: '📋', label: 'Migration History' },\n 'roles': { number: 14, emoji: '👤', label: 'Postgres Roles & Grants' },\n}\n\n/**\n * Whether a check compares the two environments, or reports on the target's\n * own posture regardless of what it is being compared against.\n *\n * Two of the fourteen are not comparisons:\n *\n * - **rls-coverage** reads only the target, listing tables with RLS disabled.\n * It reports the same tables whichever pair you diff.\n * - **migrations** compares local migration *files* against the target's\n * tracking table — a project-level observation, not a source-to-target one.\n *\n * Both are real and useful findings, but neither is drift. Counting them\n * toward the drift score meant diffing an environment against *itself* could\n * never score 100, so \"no drift detected\" stopped being a trustworthy signal\n * and the score was useless as a synchronisation measure (issue #40).\n */\nexport type CheckKind = 'comparison' | 'posture'\n\nexport const CHECK_KIND: Record<CheckName, CheckKind> = {\n 'schema': 'comparison',\n 'rls': 'comparison',\n 'rls-coverage': 'posture',\n 'edge-functions': 'comparison',\n 'storage': 'comparison',\n 'auth': 'comparison',\n 'cron': 'comparison',\n 'data': 'comparison',\n 'webhooks': 'comparison',\n 'realtime': 'comparison',\n 'vault': 'comparison',\n 'extensions': 'comparison',\n 'migrations': 'posture',\n 'roles': 'comparison',\n}\n\n/** Checks that compare source against target. */\nexport function isComparisonCheck(name: CheckName): boolean {\n return CHECK_KIND[name] === 'comparison'\n}\n\n/** API-based sync action for non-SQL drift fixes. */\nexport interface SyncAction {\n /** HTTP method */\n method: 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n /** Full URL (resolved at scan time, using target projectRef). */\n url: string\n /** Request headers (Authorization injected by promote). */\n headers?: Record<string, string>\n /** JSON body to send. */\n body?: unknown\n /** Human-readable description of what this action does. */\n label: string\n}\n\nexport interface DriftIssue {\n id: string\n check: CheckName\n severity: Severity\n title: string\n description: string\n sourceValue?: unknown\n targetValue?: unknown\n sql?: { up: string; down: string }\n /** API-based sync action (for non-SQL fixes like storage buckets, auth config, edge functions). */\n action?: SyncAction\n /**\n * Why this difference has no automatic fix, and what to do instead.\n *\n * For findings that are real but cannot be applied: a Vault secret whose\n * value exists only in the source, an Edge Function that needs deploying.\n * Set it rather than inventing SQL — the vault check used to emit\n * `vault.create_secret('PLACEHOLDER_VALUE', …)`, and `--apply` ran it, which\n * left the target holding a live secret with a bogus value (issue #91).\n *\n * Reported as the skip reason at apply time, so the user is told the command\n * instead of being told there is nothing to be done.\n */\n manualOnly?: string\n /**\n * Why this fix waits for --allow-destructive, when that isn't visible from\n * its SQL: a webhook is a trigger, and dropping a trigger usually isn't.\n */\n destructive?: string\n}\n\nexport interface CheckResult {\n check: CheckName\n status: 'clean' | 'drifted' | 'error' | 'skipped'\n issues: DriftIssue[]\n error?: string\n /**\n * Why the check declined to run — missing credentials, an absent extension,\n * nothing configured to compare.\n *\n * Present only when status is 'skipped'. Without it a skipped layer was\n * indistinguishable from a clean one in both the terminal output and the\n * JSON payload (issue #42).\n */\n skipReason?: string\n /**\n * Findings left out because another check reports the same object — the\n * schema check's policy findings where the RLS check has them (issue #97),\n * its extension findings where the extensions check has them. Counted so\n * the difference from the live progress line is explained.\n */\n folded?: Array<{ count: number; into: CheckName }>\n durationMs: number\n}\n\nexport interface ScanResult {\n timestamp: string\n source: string\n target: string\n checks: CheckResult[]\n /**\n * How closely the two environments match, 0–100, over the comparison checks\n * only. Posture findings are excluded so a genuinely synchronised pair can\n * reach 100 even when it carries pre-existing findings on both sides.\n */\n score: number\n /**\n * The target's own security and tracking posture, 0–100, over the posture\n * checks only. `null` when none of them ran.\n */\n postureScore: number | null\n summary: { total: number; critical: number; warning: number; info: number }\n}\n","import pg from 'pg'\nimport { pgClientConfig } from './db.js'\nimport type { ScanResult, SyncAction } from './types/drift'\nimport { errMsg } from './utils/error'\nimport { ABSENT_ON_TARGET, EXTENSION_UNAVAILABLE, UNDEFINED_COLUMN, sqlState } from './pg-errors.js'\nimport { destructiveReason } from './dbdiff'\nimport { parseStatements } from './sql-ast'\nimport {\n orderStatements, referencedTables,\n createdPolicies, createsOnlyPolicies,\n createdTriggers, createsOnlyTriggers,\n sqlSkeleton, bareName, identifierMatcher,\n} from './sql-deps.js'\nimport { splitSqlStatements, isCommentOnly } from './utils/sql-split.js'\nimport { applyTableFilter, isFiltered, type TableFilter } from './utils/table-filter.js'\nimport { isComparisonCheck } from './types/drift.js'\nimport { matchesGlob } from './utils/strings.js'\n\nexport type FetchFn = (url: string, init?: RequestInit) => Promise<Response>\n\nexport interface PromoteOptions {\n /** Target database connection string */\n dbUrl: string\n /** The scan result with SQL fixes to apply */\n scanResult: ScanResult\n /** Only promote specific checks */\n checks?: string[]\n /** Also apply posture fixes; off by default — see planWork */\n applyPosture?: boolean\n /** Dry-run mode — print SQL without executing */\n dryRun?: boolean\n /**\n * Permit statements that destroy data (DROP TABLE, DROP COLUMN).\n *\n * Off by default: those are reported as drift but skipped at apply time, so\n * `supaforge diff --apply` can never drop a table or column without the user\n * asking for it. Set by the `--allow-destructive` flag.\n */\n allowDestructive?: boolean\n /**\n * The table scope the diff ran under.\n *\n * Needed at apply time as well as scan time. `--tables` reaches dbdiff, which\n * scopes *tables* only, so a narrowed fix set still arrives carrying the\n * views, triggers and indexes that hang off the tables it excluded. Applying\n * those fails, because the column or table they need was deliberately not\n * added (issue #48).\n */\n tableFilter?: TableFilter\n /**\n * Apply only these issues, by id. Globs allowed. Undefined means all.\n *\n * Every issue in `--json` already carries a stable id, so a review step can\n * pick a subset out of one diff and apply exactly that, with no new matching\n * syntax to learn.\n */\n only?: string[]\n /**\n * Run every SQL fix in one transaction, rolling the whole set back if any\n * statement fails. On by default — see `executeSql`.\n */\n transactional?: boolean\n /** Fetch function for API-based sync actions (defaults to globalThis.fetch) */\n fetchFn?: FetchFn\n}\n\n/** Where a fix came from: which check reported it, and under which issue id. */\ninterface FixOrigin {\n check: string\n issueId: string\n}\n\nexport type PlannedSql = FixOrigin & { sql: string }\ntype PlannedAction = FixOrigin & { action: SyncAction }\ntype PlannedSkip = FixOrigin & { reason: string }\n\nexport interface PromoteResult {\n applied: (FixOrigin & { sql?: string; action?: string })[]\n skipped: PlannedSkip[]\n errors: (FixOrigin & { error: string })[]\n /**\n * Fixes that ran and were then undone because a later statement in the same\n * transaction failed. Reported separately from `applied`, which only ever\n * lists what is actually in the target now.\n */\n rolledBack?: (FixOrigin & { sql?: string })[]\n}\n\ninterface PlannedWork {\n sqlStatements: PlannedSql[]\n apiActions: PlannedAction[]\n skipped: PlannedSkip[]\n}\n\n/** What `planWork` needs to know beyond the scan result itself. */\nexport interface PlanOptions {\n checks?: string[]\n /**\n * Also apply fixes from the checks that judge the target on its own rather\n * than comparing it to the source. Off by default — see planWork.\n */\n applyPosture?: boolean\n allowDestructive?: boolean\n tableFilter?: TableFilter\n only?: string[]\n}\n\n/**\n * Why a fix cannot be applied under the current scope, or null when it can.\n *\n * A fix set narrowed by `--tables` is internally inconsistent by construction:\n * dbdiff's `--tables` covers tables, so the views, triggers and indexes\n * belonging to an excluded table survive the filter while the table change they\n * need does not. Naming the excluded table is the difference between a fix a\n * user can reason about and an error they cannot (issue #48).\n */\nexport function outOfScopeReason(sql: string, filter: TableFilter | undefined): string | null {\n if (!isFiltered(filter)) return null\n\n const referenced = referencedTables(sql)\n if (referenced.length === 0) return null\n\n const excluded = referenced.filter(t => applyTableFilter([t], filter).length === 0)\n if (excluded.length === 0) return null\n\n const names = excluded.map(t => `'${t}'`).join(', ')\n const flag = filter?.tables?.length ? '--tables' : '--exclude-tables'\n const noun = excluded.length === 1 ? 'table' : 'tables'\n return `Depends on ${noun} ${names}, excluded by ${flag}`\n}\n\n/** Does this issue id match any of the `--only` selectors? */\nfunction isSelected(issueId: string, only: string[] | undefined): boolean {\n if (!only?.length) return true\n return only.some(pattern => matchesGlob(issueId, pattern))\n}\n\n/**\n * `--only` plus the \"default grants to take back\" of every table, view or\n * routine the selection creates.\n *\n * A new table picks up the target's default privileges — on Supabase,\n * everything to anon and authenticated — and the roles check's\n * `roles-grant-default-<role>.<schema>.<table>` fixes take back what the\n * source doesn't grant. Selecting the table without them left it open to the\n * Data API, so they come along with it.\n */\nfunction withDefaultGrantRevokes(scanResult: ScanResult, only: string[] | undefined): string[] | undefined {\n if (!only?.length) return only\n const issues = scanResult.checks.flatMap(c => c.issues)\n const created = new Set(issues\n .filter(i => i.sql?.up && isSelected(i.id, only))\n .flatMap(i => relationsCreatedBy(i.sql!.up)))\n if (created.size === 0) return only\n const companions = issues\n .filter(i => i.id.startsWith('roles-grant-default-')\n && [...created].some(rel => rel.endsWith('(')\n // A routine, by schema and name: the fix spells its arguments as\n // written (`p integer DEFAULT 1`), the finding as PostgreSQL\n // identifies them (`p integer`).\n ? i.id.toLowerCase().includes(`.${rel}`)\n : i.id.toLowerCase().endsWith(`.${rel}`)))\n .map(i => i.id)\n return [...only, ...companions]\n}\n\n/** `schema.name` (lower case, `public` when unqualified) of each table and view the SQL creates, and `schema.name(` of each routine. */\nfunction relationsCreatedBy(sql: string): string[] {\n const statements = parseStatements(sql)\n if (!statements) return []\n return statements.flatMap(({ kind, node }) => {\n if (kind === 'CreateFunctionStmt') {\n // `schema.name(`, matched against routine ids by prefix.\n const parts = (node.funcname as Array<{ String?: { sval: string } }> ?? []).map(n => n.String?.sval ?? '')\n const name = parts.at(-1)\n return name ? [`${(parts.length > 1 ? parts.at(-2)! : 'public').toLowerCase()}.${name.toLowerCase()}(`] : []\n }\n const rel = kind === 'CreateStmt' ? node.relation\n : kind === 'ViewStmt' ? node.view\n : kind === 'CreateTableAsStmt' ? node.into?.rel\n : undefined\n return rel?.relname ? [`${(rel.schemaname || 'public').toLowerCase()}.${String(rel.relname).toLowerCase()}`] : []\n })\n}\n\n/**\n * Decide what happens to one issue: run its SQL, call its API, or skip it.\n *\n * Split out of planWork so each reason a fix is withheld is one readable\n * branch, and so the decision can be asserted directly in tests.\n */\nfunction classifyIssue(\n issue: { id: string; sql?: { up: string }; action?: SyncAction; manualOnly?: string; destructive?: string },\n options: PlanOptions,\n recreatedPolicies: ReadonlySet<string> = new Set(),\n): { kind: 'sql'; sql: string } | { kind: 'api'; action: SyncAction } | { kind: 'skip'; reason: string } {\n if (!isSelected(issue.id, options.only)) {\n return { kind: 'skip', reason: 'Not selected by --only' }\n }\n\n // Real, but not for an automatic apply: the finding says what to do.\n if (issue.manualOnly) return { kind: 'skip', reason: issue.manualOnly }\n\n if (!issue.sql?.up) {\n // A DELETE removes a bucket or an Edge Function as surely as DROP TABLE\n // removes a table, so it waits for the same flag.\n if (issue.action?.method === 'DELETE' && !options.allowDestructive) {\n return { kind: 'skip', reason: `Destructive — ${issue.action.label}; re-run with --allow-destructive to apply` }\n }\n if (issue.action) return { kind: 'api', action: issue.action }\n // A check that knows why it cannot offer a fix says so; \"nothing\n // available\" on its own leaves the user with no next step.\n return { kind: 'skip', reason: issue.manualOnly ?? 'No SQL fix or API action available' }\n }\n\n if (!options.allowDestructive) {\n const why = issue.destructive ?? destructiveReason(issue.sql.up, recreatedPolicies)\n if (why) {\n return { kind: 'skip', reason: `Destructive — ${why}; re-run with --allow-destructive to apply` }\n }\n }\n\n const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter)\n if (outOfScope) return { kind: 'skip', reason: outOfScope }\n\n return { kind: 'sql', sql: issue.sql.up }\n}\n\n/**\n * Policies that fixes in this apply create — the ones that will actually run.\n *\n * Lets the destructive gate tell a policy being removed from one being\n * replaced across two fixes: a column type change drops the policies reading\n * the column, and the policy's own fix creates the new definition once the\n * type has changed (they cannot be one statement, because the new definition\n * is not valid until then). Counted only from fixes that are selected and not\n * held back themselves, so `--only` a column change without its policy fix is\n * still gated as the removal it would be.\n */\nfunction policiesCreatedBySelectedFixes(checks: ScanResult['checks'], options: PlanOptions): Set<string> {\n const created = new Set<string>()\n for (const check of checks) {\n // Posture fixes do not run unless asked for (see planWork), so what they\n // would create cannot stand in for a policy another fix drops.\n const askedForExplicitly = options.checks?.includes(check.check) ?? false\n if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue\n for (const issue of check.issues) {\n const sql = issue.sql?.up\n if (!sql || !isSelected(issue.id, options.only)) continue\n if (!options.allowDestructive && destructiveReason(sql)) continue\n if (outOfScopeReason(sql, options.tableFilter)) continue\n for (const key of createdPolicies(sql)) created.add(key)\n }\n }\n return created\n}\n\n/**\n * Sort a scan result's issues into what can be run as SQL, what needs an API\n * call, and what has to be skipped.\n *\n * Kept separate from promote() so the decision of *what* to apply is one\n * self-contained, directly testable pass, and promote() is left to the\n * execution.\n *\n * The SQL comes back in dependency order rather than the order the checks\n * reported it — see `orderStatements`.\n */\nexport function planWork(scanResult: ScanResult, options: PlanOptions = {}): PlannedWork {\n options = { ...options, only: withDefaultGrantRevokes(scanResult, options.only) }\n const plan: PlannedWork = { sqlStatements: [], apiActions: [], skipped: [] }\n\n const relevant = scanResult.checks.filter(\n c => c.status === 'drifted' && (!options.checks || options.checks.includes(c.check)),\n )\n const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options)\n // What the destructive gate keeps, as the definitions that would put it\n // back — the objects still there after the apply.\n const keptBack: Array<{ issueId: string; definition: string }> = []\n\n for (const checkResult of relevant) {\n // A posture check judges the target on its own and fires identically\n // whichever pair you diff, so its fix is not a reconciliation — applying it\n // changes the target away from the source and *creates* drift. Enabling RLS\n // on a table the source leaves open is the clear case: the next diff reports\n // \"RLS enabled unexpectedly\", the next sync switches it back off, and the\n // coverage check flags it again, forever. Worse, RLS enabled without the\n // policies to go with it denies every row to non-owners, so a posture fix\n // applied to a working table can take it offline.\n //\n // Naming the check explicitly (--check=rls-coverage) or passing\n // --apply-posture is taken as asking for it on purpose.\n const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false\n if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {\n for (const issue of checkResult.issues) {\n plan.skipped.push({\n check: checkResult.check,\n issueId: issue.id,\n reason: 'Posture finding about the target, not drift from the source — '\n + 'applying it would create drift. Use --apply-posture to apply anyway.',\n })\n }\n continue\n }\n\n for (const issue of checkResult.issues) {\n const at = { check: checkResult.check, issueId: issue.id }\n const outcome = classifyIssue(issue, options, recreatedPolicies)\n\n if (outcome.kind === 'sql') plan.sqlStatements.push({ ...at, sql: outcome.sql })\n else if (outcome.kind === 'api') plan.apiActions.push({ ...at, action: outcome.action })\n else {\n plan.skipped.push({ ...at, reason: outcome.reason })\n if (outcome.reason.startsWith('Destructive') && issue.sql?.down) {\n keptBack.push({ issueId: issue.id, definition: issue.sql.down })\n }\n }\n }\n }\n\n plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant))\n // DBDiff's fixes keep the order DBDiff wrote them in, which it took from\n // the catalog; the others are placed around them — see orderStatements().\n const dbdiffOrder = new Map(plan.sqlStatements.filter(s => s.check === 'schema').map((s, i) => [s, i]))\n plan.sqlStatements = orderStatements(plan.sqlStatements, s => s.sql, s => dbdiffOrder.get(s))\n plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped)\n return plan\n}\n\n/** `DROP TYPE|DOMAIN|FUNCTION|PROCEDURE|SEQUENCE [IF EXISTS] <name>`, capturing the name. */\nconst DROPS_SUPPORTING_OBJECT = /^\\s*DROP\\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\\s+(?:IF\\s+EXISTS\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\s*\\.\\s*(?:\"[^\"]+\"|[\\w$]+))?)/i\n\n/**\n * Hold back the drop of a type, domain, routine or sequence that something\n * the destructive gate keeps still uses.\n *\n * The source no longer has a table and the enum its column was typed by; the\n * table's DROP is held back without --allow-destructive, and the enum's DROP\n * then fails — `cannot drop type ... because other objects depend on it` —\n * taking every other fix in the transaction with it. A kept object's own\n * definition (its fix's DOWN) says what it uses. Only a fix that does nothing\n * but drop such objects is held back; holding back more is the safe side.\n */\nfunction holdBackDropsStillInUse(\n statements: PlannedSql[],\n keptBack: Array<{ issueId: string; definition: string }>,\n skipped: PlannedWork['skipped'],\n downs: ReadonlyMap<string, string> = new Map(),\n): PlannedSql[] {\n const kept = keptBack.map(k => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }))\n let remaining = statements\n\n // Until nothing more is held back: what one held-back drop keeps can keep\n // something else — a column kept keeps its composite type, and the\n // composite keeps the enum it holds.\n for (let changed = kept.length > 0; changed;) {\n changed = false\n remaining = remaining.filter((statement) => {\n const names = droppedSupportingObjects(statement.sql)\n if (names.length === 0) return true\n\n const user = kept.find(k => names.some(n => identifierMatcher(bareName(n)).test(k.skeleton)))\n if (!user) return true\n skipped.push({\n check: statement.check,\n issueId: statement.issueId,\n reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; `\n + 're-run with --allow-destructive to apply both',\n })\n const definition = downs.get(statement.issueId)\n if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) })\n changed = true\n return false\n })\n }\n return remaining\n}\n\n/** The names a fix drops, when all it does is drop types, domains, routines or sequences. */\nfunction droppedSupportingObjects(sql: string): string[] {\n const parts = splitSqlStatements(sql).filter(s => !isCommentOnly(s))\n const names = parts.map(s => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1])\n return names.length > 0 && names.every(n => n !== undefined) ? names as string[] : []\n}\n\n/** Each issue's DOWN — the definition of what it would drop — by issue id. */\nfunction downsOf(checks: ScanResult['checks']): Map<string, string> {\n const downs = new Map<string, string>()\n for (const check of checks) {\n for (const issue of check.issues) {\n if (issue.sql?.down) downs.set(issue.id, issue.sql.down)\n }\n }\n return downs\n}\n\n/**\n * Remove a fix that an earlier statement in the same set already performs.\n *\n * Two layers can legitimately produce the same object. The schema check's SQL\n * comes from `@dbdiff/cli`, which models RLS policies as of 3.0.0-rc.10 and has\n * always modelled triggers; the rls check writes its own policies, and since\n * issue #77 the webhooks check writes its own triggers. Applied together the\n * second fails — `policy ... already exists`, `trigger ... already exists` —\n * and because the apply is transactional that single collision discards every\n * other fix with it. Reported twice now: a new policy that could not be synced\n * at all (#67), and a full apply rolling back six correct schema fixes (#77).\n *\n * Run over the statements in execution order, after `orderStatements`, so\n * \"already created\" means created by something that genuinely runs first rather\n * than merely reported first.\n *\n * Only a statement that does nothing else is dropped. The schema check bundles\n * its policy with the table and the ENABLE ROW LEVEL SECURITY beside it, and its\n * trigger with the function the trigger calls; losing either would be far worse\n * than the collision.\n */\nfunction dropDuplicateObjectFixes(\n statements: PlannedSql[],\n skipped: PlannedWork['skipped'],\n): PlannedSql[] {\n const kinds = [\n { what: 'policy', created: createdPolicies, onlyThis: createsOnlyPolicies, seen: new Set<string>() },\n { what: 'trigger', created: createdTriggers, onlyThis: createsOnlyTriggers, seen: new Set<string>() },\n ]\n const kept: PlannedSql[] = []\n\n for (const statement of statements) {\n const duplicate = kinds.find((kind) => {\n const names = kind.created(statement.sql)\n return names.length > 0\n && names.every(n => kind.seen.has(n))\n && kind.onlyThis(statement.sql)\n })\n\n if (duplicate) {\n skipped.push({\n check: statement.check,\n issueId: statement.issueId,\n reason: `Already created by the schema fix for the same ${duplicate.what}`,\n })\n continue\n }\n\n for (const kind of kinds) {\n for (const name of kind.created(statement.sql)) kind.seen.add(name)\n }\n kept.push(statement)\n }\n\n return kept\n}\n\n/**\n * Run the planned SQL against the target on a single connection.\n *\n * Transactional by default. PostgreSQL supports transactional DDL, so a fix set\n * either lands whole or not at all, and a failure leaves the target exactly as\n * it was. The alternative — the behaviour before issue #48 — left a shared\n * environment matching neither the source nor its own previous state, and the\n * person running it having to work out which fixes had landed before retrying.\n *\n * `transactional: false` restores the statement-at-a-time behaviour, for the\n * cases where partial progress is genuinely wanted.\n */\nasync function executeSql(\n dbUrl: string,\n statements: PlannedSql[],\n result: PromoteResult,\n transactional: boolean,\n): Promise<void> {\n if (statements.length === 0) return\n\n const client = new pg.Client(pgClientConfig(dbUrl))\n await client.connect()\n try {\n if (transactional) await runInTransaction(client, statements, result)\n else await runIndependently(client, statements, result)\n } finally {\n await client.end()\n }\n}\n\n/**\n * Run fixes exactly as a transactional apply would — dependency-order input,\n * one savepoint per fix, a fix whose extension or object is missing left out\n * and the rest kept — against any database. The proof replays a migration\n * this way, so it rehearses what the apply will do rather than a stricter\n * script that stopped at the first fix the server could not hold.\n */\nexport async function runLikeApply(dbUrl: string, statements: PlannedSql[]): Promise<PromoteResult> {\n const result: PromoteResult = { applied: [], skipped: [], errors: [] }\n await executeSql(dbUrl, statements, result, true)\n return result\n}\n\n/** One statement at a time: a failure is recorded and the rest still run. */\nasync function runIndependently(\n client: pg.Client,\n statements: PlannedSql[],\n result: PromoteResult,\n): Promise<void> {\n for (const stmt of statements) {\n try {\n await client.query(stmt.sql)\n result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql })\n } catch (err) {\n result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) })\n }\n }\n}\n\n/**\n * Does this fix consist only of `ALTER TYPE ... ADD VALUE`?\n *\n * PostgreSQL lets that run inside a transaction but not the new label be\n * *used* there until it commits:\n *\n * ERROR: unsafe use of new value \"refunded\" of enum type order_state\n * HINT: New enum values must be committed before they can be used.\n *\n * and the same apply often uses it straight away — a column default, or a\n * reference-data row the data check inserts.\n */\nexport function isEnumValueAddition(sql: string): boolean {\n const statements = splitSqlStatements(sql).filter(s => !isCommentOnly(s))\n return statements.length > 0\n && statements.every(s => /^\\s*ALTER\\s+TYPE\\s+\\S+\\s+ADD\\s+VALUE\\b/i.test(sqlSkeleton(s)))\n}\n\n/**\n * All statements in one transaction, each fix under a savepoint of its own.\n *\n * A fix that fails because the target lacks something it needs — an extension\n * the server does not ship, the type or schema that extension would have\n * created, a table or column an earlier such fix would have added — is undone\n * on its own and reported as an error, and the rest still commit. One column\n * typed `extensions.vector` on a target without pgvector used to roll back\n * every unrelated fix in the apply, which left nothing synced at all.\n *\n * Every other failure still rolls back everything. What ran before it moves to\n * `rolledBack` rather than `applied`, because none of it is in the target any\n * more.\n *\n * Enum label additions go first, in a transaction of their own that commits,\n * so the rest can use the new labels — see isEnumValueAddition. They are\n * additive and idempotent (`IF NOT EXISTS`), so keeping them when the rest\n * rolls back leaves nothing half-done; they are reported as applied because\n * they are.\n */\nasync function runInTransaction(\n client: pg.Client,\n statements: PlannedSql[],\n result: PromoteResult,\n): Promise<void> {\n const additions = statements.filter(s => isEnumValueAddition(s.sql))\n const rest = statements.filter(s => !isEnumValueAddition(s.sql))\n\n if (additions.length > 0 && !(await runBatch(client, additions, result))) return\n await runBatch(client, rest, result)\n}\n\n/**\n * Why a fix cannot apply to this target at all, or undefined when the failure\n * is something else.\n *\n * Only \"does not exist\" failures qualify, and for `CREATE EXTENSION`, an\n * extension the server does not ship.\n */\nexport function unmetDependency(sql: string, err: unknown): string | undefined {\n const code = sqlState(err)\n if (!code) return undefined\n if (/^\\s*CREATE\\s+EXTENSION\\b/i.test(sqlSkeleton(sql))) {\n return EXTENSION_UNAVAILABLE.has(code) ? 'this server does not ship it' : undefined\n }\n if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {\n return 'it needs something the target does not have'\n }\n return undefined\n}\n\n/** One transaction; true when it committed. */\nasync function runBatch(\n client: pg.Client,\n statements: PlannedSql[],\n result: PromoteResult,\n): Promise<boolean> {\n if (statements.length === 0) return true\n const done: PromoteResult['applied'] = []\n await client.query('BEGIN')\n\n // Fixes whose dependency is missing are tried again once the others have\n // run, in case what they need comes later in the batch. Only the ones still\n // failing when a pass makes no progress are left out.\n let pending = statements\n let unmet: Array<{ stmt: PlannedSql; err: unknown; why: string }> = []\n while (pending.length > 0) {\n unmet = []\n for (const stmt of pending) {\n await client.query('SAVEPOINT sf_fix')\n try {\n await client.query(stmt.sql)\n await client.query('RELEASE SAVEPOINT sf_fix')\n done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql })\n } catch (err) {\n const why = unmetDependency(stmt.sql, err)\n if (why && await client.query('ROLLBACK TO SAVEPOINT sf_fix').then(() => true, () => false)) {\n unmet.push({ stmt, err, why })\n continue\n }\n await client.query('ROLLBACK').catch(() => {})\n result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) })\n result.rolledBack = [...(result.rolledBack ?? []), ...done]\n return false\n }\n }\n if (unmet.length === pending.length) break\n pending = unmet.map(u => u.stmt)\n }\n\n await client.query('COMMIT')\n result.applied.push(...done)\n for (const { stmt, err, why } of unmet) {\n result.errors.push({\n check: stmt.check,\n issueId: stmt.issueId,\n error: `${errMsg(err)} — not applied: ${why}. The other fixes were.`,\n })\n }\n return true\n}\n\n/** Run the planned API-based sync actions, recording per-action failures. */\nasync function executeApiActions(\n actions: PlannedAction[],\n fetchFn: FetchFn,\n result: PromoteResult,\n): Promise<void> {\n for (const act of actions) {\n try {\n const init: RequestInit = {\n method: act.action.method,\n headers: { 'Content-Type': 'application/json', ...act.action.headers },\n }\n if (act.action.body !== undefined) {\n init.body = JSON.stringify(act.action.body)\n }\n\n const res = await fetchFn(act.action.url, init)\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText)\n throw new Error(`${act.action.method} ${act.action.url} → ${res.status}: ${text}`)\n }\n\n result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label })\n } catch (err) {\n result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) })\n }\n }\n}\n\nexport async function promote(options: PromoteOptions): Promise<PromoteResult> {\n const {\n dbUrl,\n scanResult,\n checks,\n dryRun = false,\n allowDestructive = false,\n tableFilter,\n only,\n applyPosture = false,\n transactional = true,\n fetchFn = globalThis.fetch.bind(globalThis),\n } = options\n\n // applyPosture was accepted by PromoteOptions and then dropped on the floor\n // here, so `--apply-posture` was a no-op through this path — the only caller\n // that honoured it was `--prove`, which calls planWork directly. The unit\n // tests covering the flag tested planWork rather than promote, which is\n // exactly why the gap survived them.\n const { sqlStatements, apiActions, skipped } = planWork(scanResult, {\n checks,\n allowDestructive,\n tableFilter,\n only,\n applyPosture,\n })\n const result: PromoteResult = { applied: [], skipped, errors: [] }\n\n if (dryRun) {\n for (const stmt of sqlStatements) {\n result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql })\n }\n for (const act of apiActions) {\n result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label })\n }\n return result\n }\n\n await executeSql(dbUrl, sqlStatements, result, transactional)\n\n // A rolled-back batch leaves the target untouched, so the API calls that\n // would have gone with it must not fire either — they are not transactional\n // and could not be undone.\n if (result.rolledBack) {\n for (const act of apiActions) {\n result.skipped.push({\n check: act.check,\n issueId: act.issueId,\n reason: 'Not attempted — the SQL fixes were rolled back',\n })\n }\n return result\n }\n\n await executeApiActions(apiActions, fetchFn, result)\n\n return result\n}\n","/**\n * SQLSTATEs for \"that does not exist here\": a relation, function, schema or\n * other object the statement names is missing from the database it ran on.\n */\nexport const ABSENT_ON_TARGET: ReadonlySet<string> = new Set(['42P01', '42883', '3F000', '42704'])\n\n/** A column the statement names is missing. */\nexport const UNDEFINED_COLUMN = '42703'\n\n/** SQLSTATEs for an extension the server does not ship. */\nexport const EXTENSION_UNAVAILABLE: ReadonlySet<string> = new Set(['0A000', '58P01'])\n\n/** The SQLSTATE of a PostgreSQL error, if it is one. */\nexport function sqlState(err: unknown): string | undefined {\n const code = (err as { code?: unknown } | null)?.code\n return typeof code === 'string' ? code : undefined\n}\n","import type { QueryFn } from '../db.js'\nimport { pgQuery } from '../db.js'\nimport type { DriftIssue } from '../types/drift.js'\nimport { Check, type CheckContext } from './base.js'\nimport { SUPABASE_PLATFORM_SCHEMAS } from '../defaults.js'\nimport { quoteName } from '../utils/sql.js'\n\ninterface PgRole {\n rolname: string\n rolsuper: boolean\n rolinherit: boolean\n rolcreaterole: boolean\n rolcreatedb: boolean\n rolcanlogin: boolean\n rolreplication: boolean\n rolbypassrls: boolean\n rolconnlimit: number\n rolvaliduntil: string | null\n}\n\n/**\n * What a grant is on. Tables, views and the like share PostgreSQL's TABLE\n * syntax; a sequence and a routine each need their own keyword, and a\n * routine its argument types, since overloads share a name.\n */\ntype ObjectKind = 'table' | 'sequence' | 'function' | 'procedure'\n\ninterface RoleGrant {\n grantee: string\n table_schema: string\n /** The object's name; for a routine, without its arguments. */\n table_name: string\n privilege_type: string\n is_grantable: boolean\n /** Set for a column-level grant, `GRANT UPDATE (col) ON t TO r`. */\n column_name?: string | null\n /** Omitted for a table, view or other relation. */\n object_kind?: ObjectKind\n /** A routine's identity arguments, `p integer`. */\n args?: string | null\n}\n\n/**\n * Roles the platform owns outright.\n *\n * Their attributes and their grants are Supabase's to manage, and a difference\n * in either means the two projects run different Supabase versions rather than\n * that anybody changed anything.\n */\nexport const PLATFORM_ROLES = [\n 'postgres', 'supabase_admin', 'authenticator',\n 'supabase_auth_admin', 'supabase_storage_admin', 'dashboard_user',\n 'pgbouncer', 'supavisor',\n // Created by Supabase's own images for Edge Functions, Realtime, read\n // replicas and logical replication. Diffing a project against plain\n // PostgreSQL offered to create all four on the target.\n 'supabase_functions_admin', 'supabase_realtime_admin',\n 'supabase_read_only_user', 'supabase_replication_admin',\n]\n\n/**\n * The roles the Data API authenticates as.\n *\n * Their *attributes* are Supabase's — nobody usefully diffs whether `anon` can\n * log in — but their *table grants* are the application's, and are exactly the\n * drift worth catching: `REVOKE ALL ON public.plans FROM anon` is the\n * difference between a table being readable through the anon key and not\n * (issue #90). All three were filtered out of the grants query, so that change\n * reported clean.\n */\nconst API_ROLES = ['anon', 'authenticated', 'service_role']\n\nconst quoted = (names: string[]) => names.map(n => `'${n.replace(/'/g, \"''\")}'`).join(', ')\n\n/**\n * Every role but the platform's, the built-in ones, and the one this check is\n * connected as.\n *\n * The connecting role is the credential each environment was given, not part\n * of the project: two databases reached as different users reported each user\n * as drift, and the fix for the target's was `DROP ROLE` on the very role the\n * apply was running as.\n */\nconst ROLES_SQL = `\n SELECT\n rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,\n rolcanlogin, rolreplication, rolbypassrls, rolconnlimit,\n rolvaliduntil::text AS rolvaliduntil\n FROM pg_roles\n WHERE NOT (rolname LIKE 'pg_%')\n AND rolname NOT IN (${quoted([...PLATFORM_ROLES, ...API_ROLES])})\n AND rolname <> current_user\n ORDER BY rolname\n`\n\n/**\n * Schemas whose grants are compared: everything but Supabase's own.\n *\n * Grants on `storage.objects`, `realtime.messages` or `vault.secrets` are set by\n * Supabase and move with its version. Comparing them reported one project's\n * Supabase upgrade as drift in the other — and offered `REVOKE ... ON\n * storage.objects FROM anon` as the fix, which breaks Storage. On a test stack\n * two thirds of the grants the Data API roles hold were in these schemas.\n */\nfunction grantSchemaFilter(ignoreSchemas: string[]): string {\n const excluded = [...new Set([...SUPABASE_PLATFORM_SCHEMAS, ...ignoreSchemas])]\n return `NOT IN (${quoted(excluded)})`\n}\n\n/**\n * Table-level grants, read from `relacl` like the column grants below.\n *\n * `information_schema.role_table_grants` was read instead, and it is wrong\n * twice over for a comparison. It includes the owner's own privileges, which\n * are not grants: a table owned by `postgres` on one side and by another user\n * on the other reported every privilege of both owners as drift — 35 findings\n * for a project restored into plain PostgreSQL. And it lists only grants the\n * connecting role takes part in, so a grant between two other roles was not\n * seen at all.\n */\nconst grantsSql = (ignoreSchemas: string[]) => `\n SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,\n n.nspname AS table_schema, c.relname AS table_name,\n a.privilege_type, a.is_grantable,\n CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n WHERE c.relacl IS NOT NULL\n AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')\n AND a.grantee <> c.relowner\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')\n ORDER BY 1, 2, 3, 4\n`\n\n/**\n * Column-level grants, read from `attacl`.\n *\n * `information_schema.column_privileges` also lists every column a table-level\n * grant covers, which would report each table grant once per column. The\n * attribute ACL holds only what was granted on the column itself —\n * `GRANT UPDATE (display_name) ON profiles TO authenticated`, the usual way to\n * let a user edit some columns of their row and not others.\n */\nconst columnGrantsSql = (ignoreSchemas: string[]) => `\n SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,\n n.nspname AS table_schema, c.relname AS table_name, att.attname AS column_name,\n a.privilege_type, a.is_grantable\n FROM pg_attribute att\n JOIN pg_class c ON c.oid = att.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n CROSS JOIN LATERAL aclexplode(att.attacl) a\n WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped\n AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n AND a.grantee <> c.relowner\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')\n ORDER BY 1, 2, 3, 4, 5\n`\n\n/**\n * Routine grants, read from `proacl`.\n *\n * A NULL `proacl` is not \"no grants\": it is PostgreSQL's default, EXECUTE to\n * PUBLIC, so it is read through acldefault(). These were never compared at\n * all, and a SECURITY DEFINER function the source kept from the Data API —\n * the usual way to keep an elevated function out of reach — arrived on the\n * target callable with the anon key. Functions an extension owns are its own.\n */\nconst functionGrantsSql = (ignoreSchemas: string[]) => `\n SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,\n n.nspname AS table_schema, p.proname AS table_name,\n pg_get_function_identity_arguments(p.oid) AS args,\n CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind,\n a.privilege_type, a.is_grantable\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a\n WHERE a.grantee <> p.proowner\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')\n ORDER BY 1, 2, 3, 4, 6\n`\n\n/** Each side's routines, to tell one the target lacks yet. */\nconst routinesSql = (ignoreSchemas: string[]) => `\n SELECT n.nspname AS table_schema, p.proname AS table_name,\n pg_get_function_identity_arguments(p.oid) AS args,\n CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind\n FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')\n`\n\n/** Each side's relations, to tell a table the target lacks yet. */\nconst relationsSql = (ignoreSchemas: string[]) => `\n SELECT n.nspname AS table_schema, c.relname AS table_name,\n CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n`\n\n/**\n * What an object the connecting role creates is granted by default, per kind\n * and schema (NULL for every schema): ALTER DEFAULT PRIVILEGES ... ON TABLES,\n * SEQUENCES and FUNCTIONS.\n *\n * A routine has a default of PostgreSQL's own as well: EXECUTE to PUBLIC. A\n * global entry for the role replaces it; without one it applies, and the\n * per-schema entries add to it. That is the second row source here.\n */\nconst DEFAULT_GRANTS_SQL = `\n SELECT CASE d.defaclobjtype WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'function' ELSE 'table' END AS object_kind,\n n.nspname AS table_schema,\n CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,\n a.privilege_type, a.is_grantable\n FROM pg_default_acl d\n LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace\n CROSS JOIN LATERAL aclexplode(d.defaclacl) a\n WHERE d.defaclobjtype IN ('r', 'S', 'f') AND d.defaclrole = current_user::regrole::oid\n AND a.grantee <> d.defaclrole\n UNION ALL\n SELECT 'function', NULL, 'PUBLIC', 'EXECUTE', false\n WHERE NOT EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclobjtype = 'f' AND d.defaclnamespace = 0 AND d.defaclrole = current_user::regrole::oid)\n`\n\ntype Relation = { table_schema: string; table_name: string; object_kind?: ObjectKind; args?: string | null }\ntype DefaultGrant = {\n table_schema: string | null; grantee: string; privilege_type: string; is_grantable: boolean\n /** Omitted for tables. A procedure gets a function's defaults. */\n object_kind?: ObjectKind\n}\n\n/** The object a grant or relation names, with its kind and a routine's arguments. */\nfunction objectKey(o: { table_schema: string; table_name: string; object_kind?: ObjectKind; args?: string | null }): string {\n const routine = o.object_kind === 'function' || o.object_kind === 'procedure'\n return `${routine ? 'routine' : o.object_kind ?? 'table'}:${o.table_schema}.${o.table_name}${routine ? `(${o.args ?? ''})` : ''}`\n}\n\n/** The kind of default privileges an object takes: a procedure's are a function's. */\nfunction defaultKind(kind: ObjectKind | undefined): ObjectKind {\n return kind === 'procedure' ? 'function' : kind ?? 'table'\n}\n\n/**\n * Leave out a missing grant the target will make by itself: one on a table it\n * does not have yet, which its default privileges grant when the schema fix\n * creates it. On Supabase that is every Data API grant on every new table —\n * most of a report, and gone again after the first apply.\n */\nexport function grantedByDefault(\n relations: Relation[],\n defaults: DefaultGrant[],\n): (g: RoleGrant) => boolean {\n const present = new Set(relations.map(objectKey))\n const granted = new Set(defaults.map(d =>\n `${defaultKind(d.object_kind)}|${d.table_schema ?? '*'}|${d.grantee}|${d.privilege_type}|${Boolean(d.is_grantable)}`))\n return g => !g.column_name\n && !present.has(objectKey(g))\n && [g.table_schema, '*'].some(schema =>\n granted.has(`${defaultKind(g.object_kind)}|${schema}|${g.grantee}|${g.privilege_type}|${Boolean(g.is_grantable)}`))\n}\n\n/**\n * What the target's default privileges will grant on a table the schema fix\n * creates, and the source does not: the other half of `grantedByDefault`.\n *\n * A table kept away from the Data API (`REVOKE ALL ... FROM anon,\n * authenticated`) and created on a Supabase target got everything the\n * defaults give, and nothing took it back until a second sync, so one sync\n * left it open to the anon key. The REVOKE runs with the grants, after the\n * table is created.\n */\nexport function defaultGrantsToRevoke(\n sourceRelations: Relation[],\n targetRelations: Relation[],\n defaults: DefaultGrant[],\n sourceGrants: RoleGrant[],\n): DriftIssue[] {\n const present = new Set(targetRelations.map(objectKey))\n const held = new Set(sourceGrants.filter(g => !g.column_name)\n .map(g => `${objectKey(g)}|${g.grantee}|${g.privilege_type}`))\n const issues: DriftIssue[] = []\n for (const rel of sourceRelations) {\n if (present.has(objectKey(rel))) continue\n const name = `${rel.table_schema}.${rel.table_name}`\n const extra = new Map<string, Set<string>>()\n for (const d of defaults) {\n if (defaultKind(d.object_kind) !== defaultKind(rel.object_kind)) continue\n if (d.table_schema !== null && d.table_schema !== rel.table_schema) continue\n if (held.has(`${objectKey(rel)}|${d.grantee}|${d.privilege_type}`)) continue\n extra.set(d.grantee, (extra.get(d.grantee) ?? new Set()).add(d.privilege_type))\n }\n for (const [grantee, privileges] of [...extra].sort(([a], [b]) => a.localeCompare(b))) {\n const gs: RoleGrant[] = [...privileges].sort().map(privilege_type => ({\n grantee, table_schema: rel.table_schema, table_name: rel.table_name, privilege_type, is_grantable: false,\n ...(rel.object_kind && rel.object_kind !== 'table' ? { object_kind: rel.object_kind } : {}),\n ...(rel.args !== undefined ? { args: rel.args } : {}),\n }))\n const routine = rel.object_kind === 'function' || rel.object_kind === 'procedure'\n issues.push({\n // Tables keep the id they have always had; others say what they are.\n id: `roles-grant-default-${grantee}.${name}${routine ? `(${rel.args ?? ''})` : ''}`,\n check: 'roles',\n severity: extraGrantSeverity(grantee),\n title: `Default grants to take back: ${describeGroup(gs)}`,\n description: `Creating ${describeObject(gs[0])} on the target gives ${grantee} what its default privileges grant. `\n + `The source does not grant \"${describeGroup(gs)}\", so it is revoked once it exists.`,\n targetValue: gs,\n sql: {\n up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(grantee)};`,\n down: `GRANT ${groupTarget(gs)} TO ${granteeSql(grantee)};`,\n },\n })\n }\n }\n return issues\n}\n\n/**\n * A grant the target has and the source does not widens access. To the roles\n * the Data API serves (and PUBLIC) that is the anon key reaching a table, so\n * critical; to any other role a warning. It was info, which a sync's summary\n * does not lead with.\n */\nconst OPEN_GRANTEES = new Set(['anon', 'authenticated', 'PUBLIC'])\nfunction extraGrantSeverity(grantee: string): 'critical' | 'warning' {\n return OPEN_GRANTEES.has(grantee) ? 'critical' : 'warning'\n}\n\nexport class RolesCheck extends Check {\n readonly name = 'roles' as const\n\n constructor(private queryFn: QueryFn = pgQuery) {\n super()\n }\n\n async scan(ctx: CheckContext): Promise<DriftIssue[]> {\n const ignore = ctx.config.ignoreSchemas ?? []\n const version = async (url: string) =>\n Number((await this.queryFn(url, `SELECT current_setting('server_version_num') AS v`) as Array<{ v: string }>)[0]?.v ?? 0)\n const [\n sourceRoles, targetRoles, sourceGrants, targetGrants, sourceColumns, targetColumns,\n sourceVersion, targetVersion, sourceRelations, targetRelations, targetDefaults,\n sourceRoutineGrants, targetRoutineGrants, sourceRoutines, targetRoutines,\n ] = await Promise.all([\n this.queryFn(ctx.source.dbUrl, ROLES_SQL) as unknown as Promise<PgRole[]>,\n this.queryFn(ctx.target.dbUrl, ROLES_SQL) as unknown as Promise<PgRole[]>,\n this.queryFn(ctx.source.dbUrl, grantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.target.dbUrl, grantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.source.dbUrl, columnGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.target.dbUrl, columnGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n version(ctx.source.dbUrl),\n version(ctx.target.dbUrl),\n this.queryFn(ctx.source.dbUrl, relationsSql(ignore)) as unknown as Promise<Relation[]>,\n this.queryFn(ctx.target.dbUrl, relationsSql(ignore)) as unknown as Promise<Relation[]>,\n this.queryFn(ctx.target.dbUrl, DEFAULT_GRANTS_SQL) as unknown as Promise<DefaultGrant[]>,\n this.queryFn(ctx.source.dbUrl, functionGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.target.dbUrl, functionGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.source.dbUrl, routinesSql(ignore)) as unknown as Promise<Relation[]>,\n this.queryFn(ctx.target.dbUrl, routinesSql(ignore)) as unknown as Promise<Relation[]>,\n ])\n const sourceObjects = [...(sourceRelations ?? []), ...(sourceRoutines ?? [])]\n const targetObjects = [...(targetRelations ?? []), ...(targetRoutines ?? [])]\n const sourceAll = [...(sourceGrants ?? []), ...(sourceRoutineGrants ?? [])]\n // A routine or sequence only the target has is the schema check's finding,\n // and its grants go with it. Every routine grants EXECUTE to PUBLIC unless\n // told otherwise, so each one present on the target alone was reported\n // again as an extra grant.\n const inSource = new Set(sourceObjects.map(objectKey))\n const targetAll = [...(targetGrants ?? []), ...(targetRoutineGrants ?? [])]\n .filter(g => !g.object_kind || g.object_kind === 'table' || inSource.has(objectKey(g)))\n const comparable = comparablePrivileges(sourceVersion, targetVersion)\n const byDefault = grantedByDefault(targetObjects, targetDefaults ?? [])\n\n return [\n ...diffRoles(sourceRoles, targetRoles),\n ...diffGrants(\n [...sourceAll, ...(sourceColumns ?? [])].filter(g => comparable(g) && !byDefault(g)),\n [...targetAll, ...(targetColumns ?? [])].filter(comparable),\n ),\n ...defaultGrantsToRevoke(\n sourceObjects, targetObjects,\n (targetDefaults ?? []).filter(d => comparable(d as RoleGrant)), sourceAll),\n ]\n }\n}\n\nfunction roleAttrs(r: PgRole): string {\n const attrs: string[] = []\n if (r.rolsuper) attrs.push('SUPERUSER')\n if (r.rolinherit) attrs.push('INHERIT')\n if (r.rolcreaterole) attrs.push('CREATEROLE')\n if (r.rolcreatedb) attrs.push('CREATEDB')\n if (r.rolcanlogin) attrs.push('LOGIN')\n if (r.rolreplication) attrs.push('REPLICATION')\n if (r.rolbypassrls) attrs.push('BYPASSRLS')\n if (r.rolconnlimit >= 0) attrs.push(`CONNECTION LIMIT ${r.rolconnlimit}`)\n if (r.rolvaliduntil) attrs.push(`VALID UNTIL '${r.rolvaliduntil}'`)\n return attrs.length > 0 ? attrs.join(' ') : 'NOLOGIN'\n}\n\nfunction rolesEqual(a: PgRole, b: PgRole): boolean {\n return (\n a.rolsuper === b.rolsuper &&\n a.rolinherit === b.rolinherit &&\n a.rolcreaterole === b.rolcreaterole &&\n a.rolcreatedb === b.rolcreatedb &&\n a.rolcanlogin === b.rolcanlogin &&\n a.rolreplication === b.rolreplication &&\n a.rolbypassrls === b.rolbypassrls &&\n a.rolconnlimit === b.rolconnlimit &&\n a.rolvaliduntil === b.rolvaliduntil\n )\n}\n\nexport function diffRoles(source: PgRole[], target: PgRole[]): DriftIssue[] {\n const issues: DriftIssue[] = []\n const sourceMap = new Map(source.map(r => [r.rolname, r]))\n const targetMap = new Map(target.map(r => [r.rolname, r]))\n\n for (const [name, sr] of sourceMap) {\n if (!targetMap.has(name)) {\n issues.push({\n id: `roles-missing-${name}`,\n check: 'roles',\n severity: 'critical',\n title: `Missing role: ${name}`,\n description: `Role \"${name}\" exists in source but is missing from target. Any RLS policies or grants referencing this role will be silently ineffective.`,\n sourceValue: sr,\n sql: {\n up: `CREATE ROLE ${quoteName(name)} ${roleAttrs(sr)};`,\n down: `DROP ROLE IF EXISTS ${quoteName(name)};`,\n },\n })\n }\n }\n\n for (const [name, tr] of targetMap) {\n if (!sourceMap.has(name)) {\n issues.push({\n id: `roles-extra-${name}`,\n check: 'roles',\n severity: 'warning',\n title: `Extra role: ${name}`,\n description: `Role \"${name}\" exists in target but not in source.`,\n targetValue: tr,\n sql: {\n up: `DROP ROLE IF EXISTS ${quoteName(name)};`,\n down: `CREATE ROLE ${quoteName(name)} ${roleAttrs(tr)};`,\n },\n })\n }\n }\n\n for (const [name, sr] of sourceMap) {\n const tr = targetMap.get(name)\n if (tr && !rolesEqual(sr, tr)) {\n issues.push({\n id: `roles-modified-${name}`,\n check: 'roles',\n severity: 'warning',\n title: `Modified role: ${name}`,\n description: `Role \"${name}\" has different attributes between source and target.`,\n sourceValue: sr,\n targetValue: tr,\n sql: {\n up: `ALTER ROLE ${quoteName(name)} ${roleAttrs(sr)};`,\n down: `ALTER ROLE ${quoteName(name)} ${roleAttrs(tr)};`,\n },\n })\n }\n }\n\n return issues\n}\n\nfunction grantKey(g: RoleGrant): string {\n const column = g.column_name ? `.${g.column_name}` : ''\n const routine = g.object_kind === 'function' || g.object_kind === 'procedure'\n return `${g.grantee}.${g.table_schema}.${g.table_name}${routine ? `(${g.args ?? ''})` : ''}${column}.${g.privilege_type}`\n}\n\n/** The object as SQL: `\"s\".\"t\"`, `SEQUENCE \"s\".\"q\"`, `FUNCTION \"s\".\"f\"(integer)`. */\nfunction objectSql(g: RoleGrant): string {\n const name = `${quoteName(g.table_schema)}.${quoteName(g.table_name)}`\n switch (g.object_kind) {\n case 'sequence': return `SEQUENCE ${name}`\n case 'function': return `FUNCTION ${name}(${g.args ?? ''})`\n case 'procedure': return `PROCEDURE ${name}(${g.args ?? ''})`\n default: return name\n }\n}\n\n/** The object as a reader names it: `public.t`, `sequence public.q`, `function public.f(integer)`. */\nfunction describeObject(g: RoleGrant): string {\n const name = `${g.table_schema}.${g.table_name}`\n switch (g.object_kind) {\n case 'sequence': return `sequence ${name}`\n case 'function': return `function ${name}(${g.args ?? ''})`\n case 'procedure': return `procedure ${name}(${g.args ?? ''})`\n default: return name\n }\n}\n\n/**\n * A grantee as SQL. `PUBLIC` is a keyword, not a role: quoted, it names a\n * role called \"PUBLIC\", which does not exist, so the fix failed.\n */\nfunction granteeSql(grantee: string): string {\n return grantee === 'PUBLIC' ? 'PUBLIC' : `\"${grantee.replace(/\"/g, '\"\"')}\"`\n}\n\n/** `SELECT ON \"s\".\"t\"`, or `UPDATE (\"col\") ON \"s\".\"t\"` for a column grant. */\nfunction grantTarget(g: RoleGrant): string {\n const column = g.column_name ? ` (\"${g.column_name.replace(/\"/g, '\"\"')}\")` : ''\n return `${g.privilege_type}${column} ON ${objectSql(g)}`\n}\n\nfunction describeGrant(g: RoleGrant): string {\n const column = g.column_name ? `(${g.column_name}) ` : ''\n return `${g.privilege_type} ${column}ON ${describeObject(g)} TO ${g.grantee}`\n}\n\nconst grantSql = (g: RoleGrant, withOption = g.is_grantable) =>\n `GRANT ${grantTarget(g)} TO ${granteeSql(g.grantee)}${withOption ? ' WITH GRANT OPTION' : ''};`\nconst revokeSql = (g: RoleGrant) => `REVOKE ${grantTarget(g)} FROM ${granteeSql(g.grantee)};`\n\n/**\n * The grants both servers can hold. MAINTAIN is a PostgreSQL 17 privilege:\n * a 17 source reported it missing from a 15 target, and the fix failed with\n * `unrecognized privilege type \"maintain\"`, rolling back every grant with it.\n */\nexport function comparablePrivileges(sourceVersion: number, targetVersion: number): (g: RoleGrant) => boolean {\n const both = Math.min(sourceVersion || Infinity, targetVersion || Infinity)\n return g => g.privilege_type !== 'MAINTAIN' || both >= 170000\n}\n\n/** Grants that differ the same way, on one table (or column) to one role, as one finding. */\nfunction grouped(grants: RoleGrant[]): RoleGrant[][] {\n const groups = new Map<string, RoleGrant[]>()\n for (const g of grants) {\n const key = `${grantKey(g).replace(/\\.[^.]+$/, '')}.${Boolean(g.is_grantable)}`\n groups.set(key, [...(groups.get(key) ?? []), g])\n }\n return [...groups.values()]\n}\n\n/** `SELECT, INSERT ON \"s\".\"t\"` for a group of grants on one object. */\nfunction groupTarget(gs: RoleGrant[]): string {\n const column = gs[0].column_name ? ` (\"${gs[0].column_name.replace(/\"/g, '\"\"')}\")` : ''\n return `${gs.map(g => `${g.privilege_type}${column}`).join(', ')} ON ${objectSql(gs[0])}`\n}\n\nfunction describeGroup(gs: RoleGrant[]): string {\n const column = gs[0].column_name ? `(${gs[0].column_name}) ` : ''\n return `${gs.map(g => g.privilege_type).join(', ')} ${column}ON ${describeObject(gs[0])} TO ${gs[0].grantee}`\n}\n\n/** A group's key: the grant key without its privilege. */\nconst groupKey = (gs: RoleGrant[]) => grantKey(gs[0]).replace(/\\.[^.]+$/, '')\n\n/**\n * Grants on the target that differ from the source's.\n *\n * Missing and extra grants are one finding per role, table (or column) and\n * grant option, listing the privileges: one finding per privilege made a\n * table granted to Supabase's three API roles twenty-odd findings, most of a\n * report.\n */\nexport function diffGrants(source: RoleGrant[], target: RoleGrant[]): DriftIssue[] {\n const issues: DriftIssue[] = []\n const sourceMap = new Map(source.map(g => [grantKey(g), g]))\n const targetMap = new Map(target.map(g => [grantKey(g), g]))\n\n const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g)\n for (const gs of grouped(missing)) {\n const plural = gs.length > 1 ? 's' : ''\n issues.push({\n id: `roles-grant-missing-${groupKey(gs)}`,\n check: 'roles',\n severity: 'warning',\n title: `Missing grant${plural}: ${describeGroup(gs)}`,\n description: `Grant${plural} \"${describeGroup(gs)}\" ${gs.length > 1 ? 'are' : 'is'} missing from target.`,\n sourceValue: gs.length > 1 ? gs : gs[0],\n sql: {\n up: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? ' WITH GRANT OPTION' : ''};`,\n down: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,\n },\n })\n }\n\n for (const [key, sg] of sourceMap) {\n const tg = targetMap.get(key)\n if (tg && Boolean(sg.is_grantable) !== Boolean(tg.is_grantable)) {\n // The same privilege, held with the grant option on one side only.\n // Keying on the privilege alone reported these identical; the grant\n // option is what lets the grantee pass the privilege on.\n const revokeOption = `REVOKE GRANT OPTION FOR ${grantTarget(sg)} FROM ${granteeSql(sg.grantee)};`\n issues.push({\n id: `roles-grant-option-${key}`,\n check: 'roles',\n severity: 'warning',\n title: `Grant option differs: ${describeGrant(sg)}`,\n description: `\"${describeGrant(sg)}\" is held ${sg.is_grantable ? 'with' : 'without'} the grant option in source `\n + `and ${tg.is_grantable ? 'with' : 'without'} it in target.`,\n sourceValue: sg,\n targetValue: tg,\n sql: sg.is_grantable\n ? { up: grantSql(sg, true), down: revokeOption }\n : { up: revokeOption, down: grantSql(tg, true) },\n })\n }\n }\n\n const extra = [...targetMap].filter(([key]) => !sourceMap.has(key)).map(([, g]) => g)\n for (const gs of grouped(extra)) {\n const plural = gs.length > 1 ? 's' : ''\n issues.push({\n id: `roles-grant-extra-${groupKey(gs)}`,\n check: 'roles',\n severity: extraGrantSeverity(gs[0].grantee),\n title: `Extra grant${plural}: ${describeGroup(gs)}`,\n description: `Grant${plural} \"${describeGroup(gs)}\" exist${gs.length > 1 ? '' : 's'} in target but not in source.`,\n targetValue: gs.length > 1 ? gs : gs[0],\n sql: {\n up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,\n down: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? ' WITH GRANT OPTION' : ''};`,\n },\n })\n }\n\n return issues\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBO,IAAM,iBAAiB;AAevB,SAAS,mBACd,QACA,MAAuD,CAAC,GAC3C;AACb,QAAM,YAAY,eAAe,IAAI,MAAM;AAC3C,QAAM,aAAa,eAAe,IAAI,aAAa;AAEnD,QAAM,eAAe,MAAM,QAAQ,QAAQ,QAAQ,MAAM,IAAI,OAAO,OAAO,SAAS,CAAC;AACrF,QAAM,gBAAgB,MAAM,QAAQ,QAAQ,QAAQ,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;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,66 @@
1
+ import * as _oclif_core_interfaces from '@oclif/core/interfaces';
2
+ import { BaseCommand } from '../base-command.js';
3
+ import { R as RestoreFailure } from '../branch-C4ndfoj5.js';
4
+ import { S as SupaForgeConfig } from '../config-CTbeRlJk.js';
5
+ import '@oclif/core';
6
+
7
+ /**
8
+ * Clone a remote environment to a local database and manage clones.
9
+ *
10
+ * Default: preflight checks (dry-run)
11
+ * --apply: execute the clone
12
+ * --list: list existing clones
13
+ * --delete=NAME: remove a clone
14
+ * --delete=NAME --apply: actually drop the database
15
+ */
16
+ declare class Clone extends BaseCommand {
17
+ static description: string;
18
+ static examples: string[];
19
+ static flags: {
20
+ env: _oclif_core_interfaces.OptionFlag<string | undefined, _oclif_core_interfaces.CustomOptions>;
21
+ 'local-db': _oclif_core_interfaces.OptionFlag<string, _oclif_core_interfaces.CustomOptions>;
22
+ 'local-url': _oclif_core_interfaces.OptionFlag<string, _oclif_core_interfaces.CustomOptions>;
23
+ 'start-local': _oclif_core_interfaces.BooleanFlag<boolean>;
24
+ 'schema-only': _oclif_core_interfaces.BooleanFlag<boolean>;
25
+ force: _oclif_core_interfaces.BooleanFlag<boolean>;
26
+ apply: _oclif_core_interfaces.BooleanFlag<boolean>;
27
+ list: _oclif_core_interfaces.BooleanFlag<boolean>;
28
+ delete: _oclif_core_interfaces.OptionFlag<string | undefined, _oclif_core_interfaces.CustomOptions>;
29
+ json: _oclif_core_interfaces.BooleanFlag<boolean>;
30
+ };
31
+ run(): Promise<void>;
32
+ }
33
+ /**
34
+ * What this server cannot have, in one line: extensions it does not ship and
35
+ * the platform's own event triggers. Every Supabase project has some, so they
36
+ * are stated rather than counted as the clone failing — see restoreFailures.
37
+ */
38
+ declare function formatUnavailable(items: readonly RestoreFailure[]): string[];
39
+ /**
40
+ * What pg_restore could not reproduce, for step 1 of the output.
41
+ *
42
+ * pg_restore exits 1 and carries on when a statement fails, which used to be
43
+ * read as success: the step printed a tick and the objects were simply not in
44
+ * the clone.
45
+ */
46
+ declare function formatRestoreFailures(failures: readonly RestoreFailure[]): string[];
47
+ /**
48
+ * The config a clone leaves behind.
49
+ *
50
+ * The clone becomes the **target**, so a bare `supaforge diff --apply` in this
51
+ * directory writes into the local copy.
52
+ *
53
+ * It used to be the source, with the cloned-from environment as the target —
54
+ * and the closing guidance recommended a bare `diff --apply`. Together those
55
+ * pointed the next unqualified apply at the hosted database the clone had just
56
+ * been taken from, carrying with it exactly the roles-and-grants drift the same
57
+ * screen warns about (issue #89). Pushing that way is still available and is
58
+ * now spelled out in full, which is the direction that deserves to be explicit.
59
+ *
60
+ * Everything else about the config is preserved, including any environment
61
+ * already called `local`, which is replaced rather than merged: it names a
62
+ * database, and the clone is the database it now names.
63
+ */
64
+ declare function configAfterClone(config: SupaForgeConfig, envName: string, localDbUrl: string): SupaForgeConfig;
65
+
66
+ export { configAfterClone, Clone as default, formatRestoreFailures, formatUnavailable };